* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* with key "TransactionElapsedTime".
*/
public void transactionEnded() {
- Instant transactionEndTime = Instant.now();
+ var transactionEndTime = Instant.now();
setTransactionEndTimestamp(transactionEndTime);
setTransactionElapsedTime(transactionEndTime);
}
* "MetricElapsedTime".
*/
public void metricEnded() {
- Instant metricEndTime = Instant.now();
+ var metricEndTime = Instant.now();
setMetricEndTimestamp(metricEndTime);
setMetricElapsedTime(metricEndTime);
}
* @param transactionStartTime transaction start time
*/
public void setTransactionBeginTimestamp(Instant transactionStartTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(TRANSACTION_BEGIN_TIME_STAMP, sdf.format(Date.from(transactionStartTime)));
}
* @param transactionEndTime transaction end time
*/
public void setTransactionEndTimestamp(Instant transactionEndTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(TRANSACTION_END_TIME_STAMP, sdf.format(Date.from(transactionEndTime)));
}
* @param metricStartTime metric start time
*/
public void setMetricBeginTimestamp(Instant metricStartTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(METRIC_BEGIN_TIME_STAMP, sdf.format(Date.from(metricStartTime)));
}
* @param metricEndTime metric end time
*/
public void setMetricEndTimestamp(Instant metricEndTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT);
+ var sdf = new SimpleDateFormat(TIME_FORMAT);
context.put(METRIC_END_TIME_STAMP, sdf.format(Date.from(metricEndTime)));
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.common.logging;
+import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
public class OnapLoggingUtils {
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
+ private static final Pattern CURLS_PAT = Pattern.compile("[{][}]");
+
private OnapLoggingUtils() {
// Private constructor to prevent subclassing
}
*/
public static OnapLoggingContext getLoggingContextForRequest(HttpServletRequest request,
OnapLoggingContext baseContext) {
- OnapLoggingContext requestContext = new OnapLoggingContext(baseContext);
+ var requestContext = new OnapLoggingContext(baseContext);
if (request.getLocalAddr() != null) { // may be null in junit tests
requestContext.setServerIpAddress(request.getLocalAddr());
}
// otherwise from remote address in the request
String forwarded = request.getHeader("X-Forwarded-For");
if (forwarded != null && forwarded.trim().length() > 0) {
- forwarded = forwarded.trim().split(",")[0];
+ forwarded = COMMA_PAT.split(forwarded.trim())[0];
requestContext.setClientIpAddress(forwarded);
} else if (request.getRemoteAddr() != null) { // may be null in junit tests
requestContext.setClientIpAddress(request.getRemoteAddr());
return format;
}
int index;
- StringBuilder builder = new StringBuilder();
- String[] token = format.split("[{][}]");
+ var builder = new StringBuilder();
+ String[] token = CURLS_PAT.split(format);
for (index = 0; index < arguments.length; index++) {
if (index < token.length) {
builder.append(token[index]);
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
+ final var prime = 31;
+ var result = 1;
result = prime * result + ((requestId == null) ? 0 : requestId.hashCode());
return result;
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
private void cleanUp() {
- EventTrackInfo eventTrackInfo = PolicyLogger.getEventTracker();
+ var eventTrackInfo = PolicyLogger.getEventTracker();
if (eventTrackInfo == null) {
return;
}
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
setMdcHostInfo();
- Instant startTime = Instant.now();
- Instant endTime = Instant.now();
+ var startTime = Instant.now();
+ var endTime = Instant.now();
seTimeStamps(startTime, endTime);
MDC.put(MDC_INSTANCE_UUID, "");
MDC.put(MDC_ALERT_SEVERITY, "");
- Instant startTime = Instant.now();
- Instant endTime = Instant.now();
+ var startTime = Instant.now();
+ var endTime = Instant.now();
seTimeStamps(startTime, endTime);
}
private static void seTimeStamps(Instant startTime, Instant endTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
+ var sdf = new SimpleDateFormat(DATE_FORMAT);
String formatedTime = sdf.format(Date.from(startTime));
MDC.put(BEGIN_TIME_STAMP, formatedTime);
if (eventTracker == null) {
eventTracker = new EventTrackInfo();
}
- EventData event = new EventData();
+ var event = new EventData();
event.setRequestId(eventId);
event.setStartTime(Instant.now());
eventTracker.storeEventData(event);
return;
}
- EventData event = eventTracker.getEventDataByRequestId(eventId);
+ var event = eventTracker.getEventDataByRequestId(eventId);
if (event != null) {
Instant endTime = event.getEndTime();
return;
}
- EventData event = eventTracker.getEventDataByRequestId(eventId.toString());
+ var event = eventTracker.getEventDataByRequestId(eventId.toString());
if (event != null) {
Instant endTime = event.getEndTime();
* @param arguments the messages
*/
private static String getNormalizedStackTrace(Throwable throwable, String... arguments) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
+ var sw = new StringWriter();
+ var pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
String newStValue = sw.toString().replace('|', '!').replace("\n", " - ");
int curSize = arguments == null ? 0 : arguments.length;
- StringBuilder newArgument = new StringBuilder();
- for (int i = 0; i < curSize; i++) {
+ var newArgument = new StringBuilder();
+ for (var i = 0; i < curSize; i++) {
newArgument.append(arguments[i]);
newArgument.append(":");
}
private static void startCleanUp() {
if (!isEventTrackerRunning) {
- EventTrackInfoHandler ttrcker = new EventTrackInfoHandler();
+ var ttrcker = new EventTrackInfoHandler();
timer = new Timer(true);
timer.scheduleAtFixedRate(ttrcker, timerDelayTime, checkInterval);
debugLogger.info("EventTrackInfoHandler begins! : {}", new Date());
*/
public static LoggerType init(Properties properties) {
- Properties loggerProperties = getLoggerProperties(properties);
+ var loggerProperties = getLoggerProperties(properties);
// fetch and verify definitions of some properties
try {
}
private static int getIntProp(Properties properties, String propName, int defaultValue) {
- final int propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
+ final var propValue = Integer.parseInt(properties.getProperty(propName, String.valueOf(defaultValue)));
debugLogger.info("{} value: {}", propName, propValue);
* loads the logger properties.
*/
private static LoggerType initlogger() {
- LoggerType loggerType = LoggerType.EELF;
+ var loggerType = LoggerType.EELF;
Properties properties = null;
try {
if (properties != null) {
String overrideLogbackLevel = properties.getProperty("override.logback.level.setup");
displayMessage("FlexLogger:overrideLogbackLevel => " + overrideLogbackLevel);
- String loggerTypeString = properties.getProperty("logger.type");
+ var loggerTypeString = properties.getProperty("logger.type");
if ("EELF".equalsIgnoreCase(loggerTypeString) && "TRUE".equalsIgnoreCase(overrideLogbackLevel)) {
displayMessage("FlexLogger: start listener.");
properties = PropertyUtil.getProperties("config/policyLogger.properties",
String auditLevel = properties.getProperty("audit.level");
String errorLevel = properties.getProperty("error.level");
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
- Instant startTime = Instant.now();
+ var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
+ var startTime = Instant.now();
String formatedTime = sdf.format(Date.from(startTime));
displayMessage("FlexLogger.propertiesChanged : called at time : " + formatedTime);
displayMessage("FlexLogger.propertiesChanged : debugLevel : " + debugLevel);
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
public static Properties getProperties(File file) throws IOException {
// create an InputStream (may throw a FileNotFoundException)
- try (FileInputStream fis = new FileInputStream(file)) {
+ try (var fis = new FileInputStream(file)) {
// create the properties instance
- Properties rval = new Properties();
+ var rval = new Properties();
// load properties (may throw an IOException)
rval.load(fis);
lastModified = timestamp;
// Save old set, and initial set of changed properties.
- Properties oldProperties = properties;
+ var oldProperties = properties;
HashSet<String> changedProperties = new HashSet<>(oldProperties.stringPropertyNames());
// Fetch the list of listeners that we will potentially notify,
for (final Listener notify : listeners) {
// Copy 'properties' and 'changedProperties', so it doesn't
// cause problems if the recipient makes changes.
- final Properties tmpProperties = (Properties) (properties.clone());
+ final var tmpProperties = (Properties) (properties.clone());
final HashSet<String> tmpChangedProperties = new HashSet<>(changedProperties);
// Do the notification in a separate thread, so blocking
// Convert the file to a canonical form in order to avoid the situation
// where different names refer to the same file.
- File tempFile = file.getCanonicalFile();
+ var tempFile = file.getCanonicalFile();
// See if there is an existing registration. The 'synchronized' block
// is needed to handle the case where a new listener is added at about
* @return {@code true} if the value is not null, {@code false} otherwise
*/
public boolean validateNotNull(String subName, Object subObject) {
- ObjectValidationResult result = new ObjectValidationResult(subName, subObject);
+ var result = new ObjectValidationResult(subName, subObject);
if (result.validateNotNull()) {
return true;
return true;
}
- BeanValidationResult result = new BeanValidationResult(listName, null);
+ var result = new BeanValidationResult(listName, null);
for (T item : list) {
if (item == null) {
result.addResult("item", item, ValidationStatus.INVALID, "null");
return true;
}
- BeanValidationResult result = new BeanValidationResult(mapName, null);
+ var result = new BeanValidationResult(mapName, null);
for (Entry<String, V> ent : map.entrySet()) {
entryValidator.accept(result, ent);
}
return null;
}
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append(initialIndentation);
builder.append('"');
* @return the validation result
*/
public BeanValidationResult validateTop(String name, Object object) {
- BeanValidationResult result = new BeanValidationResult(name, object);
+ var result = new BeanValidationResult(name, object);
if (object == null) {
return result;
}
*/
private void validateFields(BeanValidationResult result, Object object, Class<?> clazz) {
for (Field field : clazz.getDeclaredFields()) {
- FieldValidator validator = makeFieldValidator(clazz, field);
+ var validator = makeFieldValidator(clazz, field);
validator.validateField(result, object);
}
}
Collection<?> list = (Collection<?>) value;
- BeanValidationResult result2 = new BeanValidationResult(fieldName, value);
- int count = 0;
+ var result2 = new BeanValidationResult(fieldName, value);
+ var count = 0;
for (Object item : list) {
itemValidator.validateValue(result2, String.valueOf(count++), item);
}
Map<?, ?> map = (Map<?, ?>) value;
- BeanValidationResult result2 = new BeanValidationResult(fieldName, value);
+ var result2 = new BeanValidationResult(fieldName, value);
for (Entry<?, ?> entry : map.entrySet()) {
String name = getEntryName(entry);
- BeanValidationResult result3 = new BeanValidationResult(name, entry);
+ var result3 = new BeanValidationResult(name, entry);
keyValidator.validateValue(result3, "key", entry.getKey());
valueValidator.validateValue(result3, "value", entry.getValue());
* @return a name for the entry
*/
protected <K, V> String getEntryName(Map.Entry<K, V> entry) {
- K key = entry.getKey();
+ var key = entry.getKey();
if (key == null) {
return "";
}
return;
}
- AnnotatedType tannot = field.getAnnotatedType();
+ var tannot = field.getAnnotatedType();
if (!(tannot instanceof AnnotatedParameterizedType)) {
return;
}
return;
}
- ItemValidator itemValidator = new ItemValidator(validator, targs[0]);
+ var itemValidator = new ItemValidator(validator, targs[0]);
if (itemValidator.isEmpty()) {
return;
}
return;
}
- AnnotatedType tannot = field.getAnnotatedType();
+ var tannot = field.getAnnotatedType();
if (!(tannot instanceof AnnotatedParameterizedType)) {
return;
}
return;
}
- ItemValidator keyValidator = new ItemValidator(validator, targs[0]);
- ItemValidator valueValidator = new ItemValidator(validator, targs[1]);
+ var keyValidator = new ItemValidator(validator, targs[0]);
+ var valueValidator = new ItemValidator(validator, targs[1]);
if (keyValidator.isEmpty() && valueValidator.isEmpty()) {
return;
}
public <T extends Annotation> T getAnnotation(Class<T> annotClass) {
// field annotation takes precedence over class annotation
- T annot = field.getAnnotation(annotClass);
+ var annot = field.getAnnotation(annotClass);
if (annot != null) {
setFieldAnnotated(true);
return annot;
* @return the field's "getter" method, or {@code null} if it is not found
*/
private Method getAccessor(Class<?> clazz, String fieldName) {
- String capname = StringUtils.capitalize(fieldName);
- Method accessor2 = getMethod(clazz, "get" + capname);
+ var capname = StringUtils.capitalize(fieldName);
+ var accessor2 = getMethod(clazz, "get" + capname);
if (accessor2 != null) {
return accessor2;
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
/**
* Build a cascaded message from an exception and all its nested exceptions.
- *
+ *
* @param throwable the top level exception
* @return cascaded message string
*/
public static String buildCascadedMessage(final Throwable throwable) {
- final StringBuilder builder = new StringBuilder();
+ final var builder = new StringBuilder();
builder.append(throwable.getMessage());
- for (Throwable t = throwable; t != null; t = t.getCause()) {
+ for (var t = throwable; t != null; t = t.getCause()) {
builder.append("\ncaused by: ");
builder.append(t.getMessage());
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
/**
* The parameter service makes ONAP PF parameter groups available to all classes in a JVM.
- *
+ *
* <p>The reason for having a parameter service is to avoid having to pass parameters down long call chains in modules
* such as PDPs and editors. The parameter service makes correct and verified parameters available statically.
- *
+ *
* <p>The parameter service must be used with care because changing a parameter set anywhere in a JVM will affect all
* users of those parameters anywhere in the JVM.
*
if (overwrite && parameterGroupMap.containsKey(parameterGroup.getName())) {
deregister(parameterGroup);
}
-
+
register(parameterGroup);
}
*/
public static <T extends ParameterGroup> T get(final String parameterGroupName) {
@SuppressWarnings("unchecked")
- final T parameterGroup = (T) parameterGroupMap.get(parameterGroupName);
+ final var parameterGroup = (T) parameterGroupMap.get(parameterGroupName);
if (parameterGroup == null) {
throw new ParameterRuntimeException("\"" + parameterGroupName + "\" not found in parameter service");
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @param parameterValue field's value
*/
private void checkMinValue(final Field field, final Object parameterValue) {
- Min minAnnot = field.getAnnotation(Min.class);
+ var minAnnot = field.getAnnotation(Min.class);
if (minAnnot != null && ((Number) parameterValue).longValue() < minAnnot.value()) {
setResult(ValidationStatus.INVALID, "must be >= " + minAnnot.value());
}
* @param parameterValue field's value
*/
private void checkMaxValue(final Field field, final Object parameterValue) {
- Max maxAnnot = field.getAnnotation(Max.class);
+ var maxAnnot = field.getAnnotation(Max.class);
if (maxAnnot != null && ((Number) parameterValue).longValue() > maxAnnot.value()) {
setResult(ValidationStatus.INVALID, "must be <= " + maxAnnot.value());
}
* @return the field's annotation, or {@code null} if it does not exist
*/
private static <T extends Annotation> T getAnyAnnotation(final Field field, Class<T> annotClass) {
- T annot = field.getAnnotation(annotClass);
+ var annot = field.getAnnotation(annotClass);
if (annot != null) {
return annot;
}
return null;
}
- StringBuilder validationResultBuilder = new StringBuilder();
+ var validationResultBuilder = new StringBuilder();
validationResultBuilder.append(initialIndentation);
validationResultBuilder.append("field \"");
* @param checker function to validate the value
*/
public <T extends Annotation> void addAnnotation(Class<T> annotClass, Checker checker) {
- T annot = getAnnotation(annotClass);
+ var annot = getAnnotation(annotClass);
if (annot != null) {
checkers.add(checker);
* @param checker function to validate the value
*/
public <T extends Annotation> void addAnnotation(Class<T> annotClass, CheckerWithAnnot<T> checker) {
- T annot = getAnnotation(annotClass);
+ var annot = getAnnotation(annotClass);
if (annot != null) {
checkers.add((result, fieldName, value) -> checker.test(result, fieldName, annot, value));
}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
Double num = (Double) value;
- long longval = num.longValue();
+ var longval = num.longValue();
if (Double.compare(num.doubleValue(), longval) != 0) {
// it isn't integral - return unchanged value
}
// it's integral - determine if it's an integer or a long
- int intval = (int) longval;
+ var intval = (int) longval;
if (intval == longval) {
return intval;
public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
- try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
+ try (var writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
Type jsonType = (type.equals(genericType) ? type : genericType);
gson.toJson(object, jsonType, writer);
}
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
- try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
+ try (var streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
Type jsonType = (type.equals(genericType) ? type : genericType);
return gson.fromJson(streamReader, jsonType);
}
in.nextNull();
return null;
} else {
- long millis = in.nextLong();
+ var millis = in.nextLong();
return Instant.ofEpochMilli(millis);
}
}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
return null;
}
- ClassWalker data = new ClassWalker();
+ var data = new ClassWalker();
data.walkClassHierarchy(clazz);
if (data.getInProps(Field.class).isEmpty() && data.getOutProps(Field.class).isEmpty()) {
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
return null;
}
- ClassWalker data = new ClassWalker();
+ var data = new ClassWalker();
data.walkClassHierarchy(clazz);
if (data.getInProps(Method.class).isEmpty() && data.getOutProps(Method.class).isEmpty()
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public T read(JsonReader in) throws IOException {
- T value = delegate.read(in);
+ var value = delegate.read(in);
DoubleConverter.convertFromDouble(value);
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.google.gson.Gson;
import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
JsonElement tree = delegate.toJsonTree(value);
if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
+ var jsonObj = tree.getAsJsonObject();
// serialize each item from the value into the target tree
for (Serializer serializer : serializers) {
@Override
public T read(JsonReader in) throws IOException {
JsonElement tree = elementAdapter.read(in);
- T object = delegate.fromJsonTree(tree);
+ var object = delegate.fromJsonTree(tree);
if (tree.isJsonObject()) {
- JsonObject jsonObj = tree.getAsJsonObject();
+ var jsonObj = tree.getAsJsonObject();
// deserialize each item from the tree into the target object
for (Deserializer dser : deserializers) {
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Collections;
import java.util.Comparator;
-import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
*/
runUntilInterrupted();
+ } catch (InterruptedException e) {
+ handleAuditLoopException(e);
+ Thread.currentThread().interrupt();
+
} catch (Exception e) {
- String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + e.getMessage();
- logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
- integrityAudit.setThreadInitialized(false);
+ handleAuditLoopException(e);
}
dbDao.destroy();
logger.info("AuditThread.run: Exiting");
}
+ private void handleAuditLoopException(Exception exception) {
+ String msg = "AuditThread.run: Could not start audit loop. Exception thrown; message=" + exception.getMessage();
+ logger.error(MessageCodes.EXCEPTION_ERROR, exception, msg);
+ integrityAudit.setThreadInitialized(false);
+ }
+
private void runUntilInterrupted() throws InterruptedException {
- boolean auditCompleted = false;
+ var auditCompleted = false;
- DbAudit dbAudit = new DbAudit(dbDao);
+ var dbAudit = new DbAudit(dbDao);
IntegrityAuditEntity entityCurrentlyDesignated;
IntegrityAuditEntity thisEntity;
integrityAudit.setThreadInitialized(true); // An exception will set it to false
- boolean interrupted = false;
+ var interrupted = false;
while (!interrupted) {
try {
if (isInterruptedException(e)) {
String msg = "AuditThread.run loop - Exception thrown: " + e.getMessage() + "; Stopping.";
logger.error(MessageCodes.EXCEPTION_ERROR, e, msg);
+ Thread.currentThread().interrupt();
interrupted = true;
} else {
IntegrityAuditEntity thisEntity = null;
- int designatedEntityIndex = -1;
- int entityIndex = 0;
- int priorCandidateIndex = -1;
- int subsequentCandidateIndex = -1;
+ var designatedEntityIndex = -1;
+ var entityIndex = 0;
+ var priorCandidateIndex = -1;
+ var subsequentCandidateIndex = -1;
for (IntegrityAuditEntity integrityAuditEntity : integrityAuditEntityList) {
*/
List<IntegrityAuditEntity> integrityAuditEntityList =
dbDao.getIntegrityAuditEntities(this.persistenceUnit, this.nodeType);
- int listSize = integrityAuditEntityList.size();
+ var listSize = integrityAuditEntityList.size();
if (logger.isDebugEnabled()) {
logger.debug("getIntegrityAuditEntityList: Got " + listSize + " IntegrityAuditEntity records");
}
+ integrityAuditEntity.getLastUpdated());
}
- boolean stale = false;
+ var stale = false;
- Date currentTime = AuditorTime.getInstance().getDate();
- Date lastUpdated = integrityAuditEntity.getLastUpdated();
+ var currentTime = AuditorTime.getInstance().getDate();
+ var lastUpdated = integrityAuditEntity.getLastUpdated();
/*
* If lastUpdated is null, we assume that the audit never ran for that node.
long timeDifference;
- Date currentTime = AuditorTime.getInstance().getDate();
- Date lastUpdated = thisEntity.getLastUpdated();
+ var currentTime = AuditorTime.getInstance().getDate();
+ var lastUpdated = thisEntity.getLastUpdated();
long lastUpdatedTime = lastUpdated.getTime();
timeDifference = currentTime.getTime() - lastUpdatedTime;
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* nodes. Since the audit is run in a round-robin, every instance will be compared against
* every other instance.
*/
- IntegrityAuditEntity myIae = dbDao.getMyIntegrityAuditEntity();
+ var myIae = dbDao.getMyIntegrityAuditEntity();
if (myIae == null) {
* @return DAO properties for the given DB node
*/
private Properties getTheirDaoProperties(IntegrityAuditEntity iae) {
- Properties theirProperties = new Properties();
+ var theirProperties = new Properties();
theirProperties.put(IntegrityAuditProperties.DB_DRIVER, iae.getJdbcDriver());
theirProperties.put(IntegrityAuditProperties.DB_URL, iae.getJdbcUrl());
logger.debug("dbAudit: Second comparison; traversing classNameSet, size=" + classNameSet.size());
}
- int errorCount = 0;
+ var errorCount = 0;
for (String clazzName : classNameSet) {
IntegrityAuditEntity myIae, String clazzName, Set<Object> keySet, Map<Object, Object> myEntries)
throws IntegrityAuditException {
- int errorCount = 0;
+ var errorCount = 0;
for (IntegrityAuditEntity iae : iaeList) {
if (iae.getId() == myIae.getId()) {
if (logger.isDebugEnabled()) {
return 0;
}
- StringBuilder keyBuilder = new StringBuilder();
+ var keyBuilder = new StringBuilder();
for (Object key : misMatchedKeySet) {
keyBuilder.append(key.toString());
keyBuilder.append(", ");
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
-import javax.persistence.PersistenceUnitUtil;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.ManagedType;
-import javax.persistence.metamodel.Metamodel;
import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
*/
private void validateProperties(String resourceName, String persistenceUnit, Properties properties)
throws IntegrityAuditPropertiesException {
- StringBuilder badparams = new StringBuilder();
+ var badparams = new StringBuilder();
if (IntegrityAudit.parmsAreBad(resourceName, persistenceUnit, properties, badparams)) {
String msg = "DbDao: Bad parameters: badparams" + badparams;
throw new IntegrityAuditPropertiesException(msg);
public Map<Object, Object> getAllMyEntries(String className) {
logger.debug("getAllMyEntries: Entering, className=" + className);
HashMap<Object, Object> resultMap = new HashMap<>();
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
- CriteriaBuilder cb = em.getCriteriaBuilder();
+ var cb = em.getCriteriaBuilder();
CriteriaQuery<Object> cq = cb.createQuery();
Root<?> rootEntry = cq.from(Class.forName(className));
CriteriaQuery<Object> all = cq.select(rootEntry);
List<Object> objectList = allQuery.getResultList();
// Now create the map
- PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
+ var util = emf.getPersistenceUnitUtil();
for (Object o : objectList) {
Object key = util.getIdentifier(o);
resultMap.put(key, o);
logger.debug("getAllMyEntries: Entering, className=" + className + ",\n keySet=" + keySet);
HashMap<Object, Object> resultMap = new HashMap<>();
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
Class<?> clazz = Class.forName(className);
for (Object key : keySet) {
logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n className=" + className);
HashMap<Object, Object> resultMap = new HashMap<>();
- EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
- EntityManager em = theEmf.createEntityManager();
+ var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+ var em = theEmf.createEntityManager();
try {
- CriteriaBuilder cb = em.getCriteriaBuilder();
+ var cb = em.getCriteriaBuilder();
CriteriaQuery<Object> cq = cb.createQuery();
Root<?> rootEntry = cq.from(Class.forName(className));
CriteriaQuery<Object> all = cq.select(rootEntry);
TypedQuery<Object> allQuery = em.createQuery(all);
List<Object> objectList = allQuery.getResultList();
- PersistenceUnitUtil util = theEmf.getPersistenceUnitUtil();
+ var util = theEmf.getPersistenceUnitUtil();
for (Object o : objectList) {
Object key = util.getIdentifier(o);
resultMap.put(key, o);
Set<Object> keySet) {
logger.debug("getAllEntries: Entering, persistenceUnit=" + persistenceUnit + ",\n properties= " + properties
+ ",\n className=" + className + ",\n keySet= " + keySet);
- EntityManagerFactory theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
- EntityManager em = theEmf.createEntityManager();
+ var theEmf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+ var em = theEmf.createEntityManager();
HashMap<Object, Object> resultMap = new HashMap<>();
try {
Class<?> clazz = Class.forName(className);
logger.debug("getIntegrityAuditEntities: Entering, persistenceUnit=" + persistenceUnit + ",\n nodeType= "
+ nodeType);
try {
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
// Start a transaction
EntityTransaction et = em.getTransaction();
// if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
// found, create a new entry
- Query iaequery = em
+ var iaequery = em
.createQuery("Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt");
iaequery.setParameter("pu", persistenceUnit);
iaequery.setParameter("nt", nodeType);
*/
public IntegrityAuditEntity getIntegrityAuditEntity(long id) throws DbDaoTransactionException {
try {
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
// Start a transaction
EntityTransaction et = em.getTransaction();
public Set<String> getPersistenceClassNames() {
logger.debug("DbDao: getPersistenceClassNames() entry");
HashSet<String> returnList = new HashSet<>();
- final Metamodel mm = emf.getMetamodel();
+ final var mm = emf.getMetamodel();
logger.debug("\n" + persistenceUnit + " persistence unit classes:");
for (final ManagedType<?> managedType : mm.getManagedTypes()) {
Class<?> clazz = managedType.getJavaType();
BiConsumer<EntityManager, IntegrityAuditEntity> updater) throws DbDaoTransactionException {
try {
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
// Start a transaction
EntityTransaction et = em.getTransaction();
throw new DbDaoTransactionException(msg);
}
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
// Start a transaction
EntityTransaction et = em.getTransaction();
// if IntegrityAuditEntity entry exists for resourceName and PU, update it. If not
// found, create a new entry
- Query iaequery = em.createQuery("Delete from IntegrityAuditEntity");
+ var iaequery = em.createQuery("Delete from IntegrityAuditEntity");
int returnCode = iaequery.executeUpdate();
/*
* Define query
*/
- Query query = em.createQuery(
+ var query = em.createQuery(
"Select i from IntegrityAuditEntity i where i.persistenceUnit=:pu and i.nodeType=:nt");
query.setParameter("pu", persistenceUnit);
query.setParameter("nt", nodeType);
continue;
}
- IntegrityAuditEntity integrityAuditEntity = (IntegrityAuditEntity) o;
+ var integrityAuditEntity = (IntegrityAuditEntity) o;
if (integrityAuditEntity.getResourceName().equals(resourceName)) {
if (logger.isDebugEnabled()) {
logger.debug("changeDesignated: Designating resourceName="
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
throws IntegrityAuditException {
logger.info("Constructor: Entering and checking for nulls");
- StringBuilder parmList = new StringBuilder();
+ var parmList = new StringBuilder();
if (parmsAreBad(resourceName, persistenceUnit, properties, parmList)) {
logger.error("Constructor: Parms contain nulls; cannot run audit for resourceName=" + resourceName
+ ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList);
*/
@PrePersist
public void prePersist() {
- Date date = AuditorTime.getInstance().getDate();
+ var date = AuditorTime.getInstance().getDate();
this.createdDate = date;
this.lastUpdated = date;
}
* ============LICENSE_START=======================================================
* Integrity Audit
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
private static Logger logger = FlexLogger.getLogger(DbAuditTest.class);
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
private static final String RESOURCE_NAME = "pdp1";
private EntityManagerFactory emf2;
assertFalse(dbglog.getExtracted().isEmpty());
String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1);
- int mismatchEntries = mismatchIndex.trim().split(",").length;
+ int mismatchEntries = COMMA_PAT.split(mismatchIndex.trim()).length;
logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" + " mismatachEntries = "
+ mismatchEntries);
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Supplier;
+import java.util.regex.Pattern;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Persistence;
-import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.persistence.config.PersistenceUnitProperties;
private static final Logger logger = LoggerFactory.getLogger(IntegrityMonitor.class.getName());
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
+ private static final Pattern SEMICOLON_PAT = Pattern.compile(";");
+
// only allow one instance of IntegrityMonitor
private static IntegrityMonitor instance = null;
// singleton check since this constructor can be called from a child or
// sub-class
if (instance != null) {
- String msg = "IM object exists and only one instance allowed";
+ var msg = "IM object exists and only one instance allowed";
logger.error("{}", msg);
throw new IntegrityMonitorException("IntegrityMonitor constructor exception: " + msg);
}
private static String getJmxUrlFromProps() throws IntegrityMonitorException {
// get the jmx remote port and construct the JMX URL
- Properties systemProps = System.getProperties();
+ var systemProps = System.getProperties();
String jmxPort = systemProps.getProperty("com.sun.management.jmxremote.port");
String jmxErrMsg;
if (jmxPort == null) {
throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
}
- int port = 0;
+ var port = 0;
try {
port = Integer.parseInt(jmxPort);
} catch (NumberFormatException e) {
jmxFqdn = InetAddress.getLocalHost().getCanonicalHostName();
}
} catch (Exception e) {
- String msg = "getJmxUrl could not get hostname";
+ var msg = "getJmxUrl could not get hostname";
logger.error("{}", msg, e);
throw new IntegrityMonitorException("getJmxUrl Exception: " + msg);
}
if (jmxFqdn == null) {
- String msg = "getJmxUrl encountered null hostname";
+ var msg = "getJmxUrl encountered null hostname";
logger.error("{}", msg);
throw new IntegrityMonitorException("getJmxUrl error: " + msg);
}
private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity,
StateManagementEntity stateManagementEntity) {
if (forwardProgressEntity != null && stateManagementEntity != null) {
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
long diffMs = date.getTime() - forwardProgressEntity.getLastUpdated().getTime();
logger.debug("IntegrityMonitor.stateCheck(): diffMs = {}", diffMs);
ArrayList<ForwardProgressEntity> fpList = new ArrayList<>();
withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> {
- Query fquery = em.createQuery("Select e from ForwardProgressEntity e");
+ var fquery = em.createQuery("Select e from ForwardProgressEntity e");
fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList()
.forEach(obj -> fpList.add((ForwardProgressEntity) obj));
return null;
}
logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size());
- int index = 0;
+ var index = 0;
for (ForwardProgressEntity fpe : fpList) {
logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++,
fpe.getResourceName());
synchronized (dependencyCheckLock) {
// Start with the error message empty
- StringBuilder errorMsg = new StringBuilder();
+ var errorMsg = new StringBuilder();
/*
* Before we check dependency groups we need to check subsystemTest.
* @return {@code true} if the dependencies are OK, {@code false} otherwise
*/
private boolean checkDependencies(StringBuilder errorMsg) {
- boolean dependencyOk = true;
+ var dependencyOk = true;
// check state of resources in dependency groups
for (String group : depGroups) {
// ignore empty group
return false;
}
- String[] dependencies = group.split(",");
+ String[] dependencies = COMMA_PAT.split(group);
if (logger.isDebugEnabled()) {
logger.debug("group dependencies = {}", Arrays.toString(dependencies));
}
- int realDepCount = 0;
- int failDepCount = 0;
+ var realDepCount = 0;
+ var failDepCount = 0;
for (String dep : dependencies) {
dep = dep.trim();
if (dep.isEmpty()) {
* An entity has reported that it is not well. We must not allow the the forward progress counter to
* advance.
*/
- String msg = "allNotWellMap:";
- for (Entry<String, String> entry : allNotWellMap.entrySet()) {
- msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
- }
+ var msg = new StringBuilder("allNotWellMap:");
+ buildMapString(msg, allNotWellMap);
logger.error("endTransaction: allNotWellMap is NOT EMPTY. Not advancing forward"
+ "progress counter. \n{}\n", msg);
return;
}
if (logger.isDebugEnabled() && getAllSeemsWellMap() != null && !(getAllSeemsWellMap().isEmpty())) {
- String msg = "allSeemsWellMap:";
- for (Entry<String, String> entry : allSeemsWellMap.entrySet()) {
- msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
- }
+ var msg = new StringBuilder("allSeemsWellMap:");
+ buildMapString(msg, allSeemsWellMap);
logger.debug("endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY. "
+ "Advancing forward progress counter. \n{}\n", msg);
}
}
}
+ private void buildMapString(StringBuilder msg, Map<String, String> map) {
+ for (Entry<String, String> entry : map.entrySet()) {
+ msg.append("\nkey = ");
+ msg.append(entry.getKey());
+ msg.append(" msg = ");
+ msg.append(entry.getValue());
+ }
+ }
+
// update FP count in DB with local FP count
private void writeFpc() throws IntegrityMonitorException {
// site_1.pdp_2
String depGroupsValue = prop.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS);
if (!StringUtils.isBlank(depGroupsValue)) {
- depGroups = depGroupsValue.split(";");
+ depGroups = SEMICOLON_PAT.split(depGroupsValue);
if (logger.isDebugEnabled()) {
logger.debug("dependency groups property = {}", Arrays.toString(depGroups));
}
return;
}
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
long timeSinceLastStateAudit = date.getTime() - lastStateAuditTime.getTime();
if (timeSinceLastStateAudit < stateAuditIntervalMs) {
logger.debug("IntegrityMonitor.stateAudit(): Not time to run. returning");
*/
public void executeStateAudit() {
logger.debug("IntegrityMonitor.executeStateAudit(): entry");
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
// Get all entries in the forwardprogressentity table
List<ForwardProgressEntity> fpList = getAllForwardProgressEntity();
private void disableEntity(String dep) {
try {
// create instance of StateMangement class for dependent
- StateManagement depStateManager = new StateManagement(emf, dep);
+ var depStateManager = new StateManagement(emf, dep);
if (!depStateManager.getOpState().equals(StateManagement.DISABLED)) {
logger.debug("Forward progress not detected for dependent resource {}. Setting dependent's "
+ "state to disable failed.", dep);
logger.debug("executeRefreshStateAudit(): entry");
synchronized (refreshStateAuditLock) {
logger.debug("refreshStateAudit: entry");
- Date now = MonitorTime.getInstance().getDate();
+ var now = MonitorTime.getInstance().getDate();
long nowMs = now.getTime();
long lastTimeMs = refreshStateAuditLastRunDate.getTime();
logger.debug("refreshStateAudit: ms since last run = {}", nowMs - lastTimeMs);
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
resourceName);
logger.debug("StateManagement: {}() operation started, resourceName = {}", methodName, resourceName);
- final EntityManager em = emf.createEntityManager();
+ final var em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
+ try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
logger.debug(FIND_MESSAGE, resourceName);
- final StateManagementEntity sm = findStateManagementEntity(em, resourceName);
+ final var sm = findStateManagementEntity(em, resourceName);
String changed = updateState.update(sm);
em.persist(sm);
throws StateManagementException {
setState(actionName, resourceName, sm -> {
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+ final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
sm.getAvailStatus(), sm.getStandbyStatus(), actionName);
sm.setAdminState(stateElement.getEndingAdminState());
AtomicReference<String> newStatus = new AtomicReference<>();
setState(PROMOTE_ACTION, resourceName, sm -> {
- final StateElement stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
+ final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE_ACTION);
sm.setAdminState(stateElement.getEndingAdminState());
logger.debug("StateManagement(6/1/16): {} for resourceName {}", methodName, resourceName);
- final EntityManager em = emf.createEntityManager();
- try (final EntityMgrCloser emc = new EntityMgrCloser(em)) {
+ final var em = emf.createEntityManager();
+ try (final var emc = new EntityMgrCloser(em)) {
final TypedQuery<StateManagementEntity> query =
em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!resourceList.isEmpty()) {
// exist
- final StateManagementEntity stateManagementEntity = resourceList.get(0);
+ final var stateManagementEntity = resourceList.get(0);
// refresh the object from DB in case cached data was returned
em.refresh(stateManagementEntity);
function.accept(stateManagementEntity);
query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!resourceList.isEmpty()) {
// exist
- final StateManagementEntity stateManagementEntity = resourceList.get(0);
+ final var stateManagementEntity = resourceList.get(0);
// refresh the object from DB in case cached data was returned
em.refresh(stateManagementEntity);
stateManagementEntity.setModifiedDate(MonitorTime.getInstance().getDate());
return stateManagementEntity;
} else {
// not exist - create one
- final StateManagementEntity stateManagementEntity = new StateManagementEntity();
+ final var stateManagementEntity = new StateManagementEntity();
stateManagementEntity.setResourceName(otherResourceName);
stateManagementEntity.setAdminState(UNLOCKED);
stateManagementEntity.setOpState(ENABLED);
return stateManagementEntity;
}
} catch (final Exception ex) {
- final String message = "findStateManagementEntity exception";
- throw new EntityRetrievalException(message, ex);
+ throw new EntityRetrievalException("findStateManagementEntity exception", ex);
}
}
/*
* Start transaction
*/
- final EntityManager em = emf.createEntityManager();
+ final var em = emf.createEntityManager();
- try (EntityMgrCloser emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
+ try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
final TypedQuery<StateManagementEntity> stateManagementEntityListQuery =
em.createQuery("SELECT p FROM StateManagementEntity p", StateManagementEntity.class);
final List<StateManagementEntity> stateManagementEntityList = stateManagementEntityListQuery
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* The StateTransition class coordinates all state transitions.
*/
public class StateTransition {
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
+
private static final String DEPENDENCY_FAILED = "dependency.failed";
private static final String ANY_DISABLED_ANY_COLDSTANDBY = "${1},disabled,${3},coldstandby,";
}
- StateElement stateElement = new StateElement();
+ var stateElement = new StateElement();
// dependency,failed is stored as dependency.failed in StateTable
String availStatus2 = availStatus;
String value = STATE_TABLE.get(key);
if (value != null) {
- String[] parts = value.split(",", 5);
+ String[] parts = COMMA_PAT.split(value, 5);
stateElement.setEndingAdminState(parts[0].trim());
stateElement.setEndingOpState(parts[1].trim());
stateElement.setEndingAvailStatus(parts[2].trim().replace(".", ","));
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
try {
logger.debug("Registering {} MBean", name);
- MBeanServer mbeanServer = findMBeanServer();
+ var mbeanServer = findMBeanServer();
if (mbeanServer == null) {
return;
}
- ObjectName objectName = new ObjectName(name);
+ var objectName = new ObjectName(name);
if (mbeanServer.isRegistered(objectName)) {
logger.debug("Unregistering a previously registered {} MBean", name);
*/
@PrePersist
public void prePersist() {
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
this.createdDate = date;
this.lastUpdated = date;
this.fpcCount = 0;
*/
@PrePersist
public void prePersist() {
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
this.createdDate = date;
this.modifiedDate = date;
}
*/
@PrePersist
public void prePersist() {
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
this.createdDate = date;
this.lastUpdated = date;
}
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @return a new StateManagementEntity
*/
public static StateManagementEntity clone(StateManagementEntity sm) {
- StateManagementEntity newStateManagementEntity = new StateManagementEntity();
+ var newStateManagementEntity = new StateManagementEntity();
newStateManagementEntity.setResourceName(sm.getResourceName());
newStateManagementEntity.setAdminState(sm.getResourceName());
newStateManagementEntity.setOpState(sm.getOpState());
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
final List<Startable> endpoints = this.getEndpoints();
- boolean success = true;
+ var success = true;
for (final Startable endpoint : endpoints) {
try {
success = endpoint.start() && success;
final List<Startable> endpoints = this.getEndpoints();
- boolean success = true;
+ var success = true;
for (final Startable endpoint : endpoints) {
try {
success = endpoint.stop() && success;
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.event.comm.bus.internal.InlineDmaapTopicSink;
*/
class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private static final String MISSING_TOPIC = "A topic must be provided";
/**
return dmaapTopicWriters.get(busTopicParams.getTopic());
}
- DmaapTopicSink dmaapTopicSink = makeSink(busTopicParams);
+ var dmaapTopicSink = makeSink(busTopicParams);
if (busTopicParams.isManaged()) {
dmaapTopicWriters.put(busTopicParams.getTopic(), dmaapTopicSink);
List<DmaapTopicSink> newDmaapTopicSinks = new ArrayList<>();
synchronized (this) {
- for (String topic : writeTopics.split("\\s*,\\s*")) {
+ for (String topic : COMMA_SPACE_PAT.split(writeTopics)) {
addTopic(newDmaapTopicSinks, properties, topic);
}
return newDmaapTopicSinks;
String topicPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic;
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+ var props = new PropertyUtils(properties, topicPrefix,
(name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
return;
}
- DmaapTopicSink dmaapTopicSink = this.build(DmaapPropertyUtils.makeBuilder(props, topic, servers)
+ var dmaapTopicSink = this.build(DmaapPropertyUtils.makeBuilder(props, topic, servers)
.partitionId(props.getString(PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, null))
.build());
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.event.comm.bus.internal.SingleThreadedDmaapTopicSource;
*/
class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private static final String MISSING_TOPIC = "A topic must be provided";
/**
return dmaapTopicSources.get(busTopicParams.getTopic());
}
- DmaapTopicSource dmaapTopicSource = makeSource(busTopicParams);
+ var dmaapTopicSource = makeSource(busTopicParams);
if (busTopicParams.isManaged()) {
dmaapTopicSources.put(busTopicParams.getTopic(), dmaapTopicSource);
List<DmaapTopicSource> dmaapTopicSourceLst = new ArrayList<>();
synchronized (this) {
- for (String topic : readTopics.split("\\s*,\\s*")) {
+ for (String topic : COMMA_SPACE_PAT.split(readTopics)) {
addTopic(dmaapTopicSourceLst, properties, topic);
}
}
String topicPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic;
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+ var props = new PropertyUtils(properties, topicPrefix,
(name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.event.comm.bus.internal.InlineUebTopicSink;
* Factory of UEB Reader Topics indexed by topic name.
*/
class IndexedUebTopicSinkFactory implements UebTopicSinkFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private static final String MISSING_TOPIC = "A topic must be provided";
/**
List<UebTopicSink> newUebTopicSinks = new ArrayList<>();
synchronized (this) {
- for (String topic : writeTopics.split("\\s*,\\s*")) {
+ for (String topic : COMMA_SPACE_PAT.split(writeTopics)) {
addTopic(newUebTopicSinks, topic, properties);
}
return newUebTopicSinks;
String topicPrefix = PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic;
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+ var props = new PropertyUtils(properties, topicPrefix,
(name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("IndexedUebTopicSinkFactory []");
- return builder.toString();
+ return "IndexedUebTopicSinkFactory []";
}
}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.event.comm.bus.internal.SingleThreadedUebTopicSource;
* Factory of UEB Source Topics indexed by topic name.
*/
class IndexedUebTopicSourceFactory implements UebTopicSourceFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private static final String MISSING_TOPIC = "A topic must be provided";
/**
return uebTopicSources.get(busTopicParams.getTopic());
}
- UebTopicSource uebTopicSource = makeSource(busTopicParams);
+ var uebTopicSource = makeSource(busTopicParams);
if (busTopicParams.isManaged()) {
uebTopicSources.put(busTopicParams.getTopic(), uebTopicSource);
List<UebTopicSource> newUebTopicSources = new ArrayList<>();
synchronized (this) {
- for (String topic : readTopics.split("\\s*,\\s*")) {
+ for (String topic : COMMA_SPACE_PAT.split(readTopics)) {
addTopic(newUebTopicSources, topic, properties);
}
}
String topicPrefix = PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic;
- PropertyUtils props = new PropertyUtils(properties, topicPrefix,
+ var props = new PropertyUtils(properties, topicPrefix,
(name, value, ex) -> logger.warn("{}: {} {} is in invalid format for topic {} ", this, name, value, topic));
String servers = properties.getProperty(topicPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
return;
}
- UebTopicSource uebTopicSource = this.build(UebPropertyUtils.makeBuilder(props, topic, servers)
+ var uebTopicSource = this.build(UebPropertyUtils.makeBuilder(props, topic, servers)
.consumerGroup(props.getString(
PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, null))
.consumerInstance(props.getString(
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("IndexedUebTopicSourceFactory []");
- return builder.toString();
+ return "IndexedUebTopicSourceFactory []";
}
}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.Collections;
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
* Noop Topic Factory.
*/
public abstract class NoopTopicFactory<T extends NoopTopicEndpoint> extends TopicBaseHashedFactory<T> {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* Get Topics Property Name.
return new ArrayList<>();
}
- return Arrays.asList(topics.split("\\s*,\\s*"));
+ return Arrays.asList(COMMA_SPACE_PAT.split(topics));
}
/**
servers = CommInfrastructure.NOOP.toString();
}
- return new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+ return new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
}
/**
*/
@Override
protected boolean isManaged(String topicName, Properties properties) {
- String managedString =
+ var managedString =
properties.getProperty(getTopicsPropertyName()
+ "." + topicName + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX);
- boolean managed = true;
+ var managed = true;
if (managedString != null && !managedString.isEmpty()) {
managed = Boolean.parseBoolean(managedString);
}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
return this.endpoints.get(topic);
}
- T endpoint = build(servers, topic);
+ var endpoint = build(servers, topic);
if (managed) {
this.endpoints.put(topic, endpoint);
}
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
* ================================================================================
import com.att.nsa.apiClient.http.HttpClient.ConnectionType;
import com.att.nsa.cambria.client.CambriaBatchingPublisher;
import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
import java.net.MalformedURLException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
*/
public CambriaPublisherWrapper(BusTopicParams busTopicParams) {
- PublisherBuilder builder = new CambriaClientBuilders.PublisherBuilder();
+ var builder = new CambriaClientBuilders.PublisherBuilder();
builder.usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic());
try {
this.publisher.close(1, TimeUnit.SECONDS);
+
+ } catch (InterruptedException e) {
+ logger.warn("{}: CLOSE FAILED", this, e);
+ Thread.currentThread().interrupt();
+
} catch (Exception e) {
- logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
+ logger.warn("{}: CLOSE FAILED", this, e);
}
}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append("InlineUebTopicSink [getTopicCommInfrastructure()=").append(getTopicCommInfrastructure())
.append(", toString()=").append(super.toString()).append("]");
return builder.toString();
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append("SingleThreadedDmaapTopicSource [userName=").append(userName).append(", password=")
.append((password == null || password.isEmpty()) ? "-" : password.length())
.append(", getTopicCommInfrastructure()=").append(getTopicCommInfrastructure()).append(", toString()=")
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append("SingleThreadedUebTopicSource [getTopicCommInfrastructure()=")
.append(getTopicCommInfrastructure()).append(", toString()=").append(super.toString()).append("]");
return builder.toString();
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
protected boolean broadcast(String message) {
List<TopicListener> snapshotListeners = this.snapshotTopicListeners();
- boolean success = true;
+ var success = true;
for (TopicListener topicListener : snapshotListeners) {
try {
topicListener.onTopicEvent(this.getTopicCommInfrastructure(), this.topic, message);
@Override
public synchronized String[] getRecentEvents() {
- String[] events = new String[recentEvents.size()];
+ var events = new String[recentEvents.size()];
return recentEvents.toArray(events);
}
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.http.client.internal.JerseyClient;
* HTTP client factory implementation indexed by name.
*/
class IndexedHttpClientFactory implements HttpClientFactory {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* Logger.
return clientList;
}
- for (String clientName : clientNames.split("\\s*,\\s*")) {
+ for (String clientName : COMMA_SPACE_PAT.split(clientNames)) {
addClient(clientList, clientName, properties);
}
private void addClient(ArrayList<HttpClient> clientList, String clientName, Properties properties) {
String clientPrefix = PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + clientName;
- PropertyUtils props = new PropertyUtils(properties, clientPrefix,
+ var props = new PropertyUtils(properties, clientPrefix,
(name, value, ex) ->
logger.warn("{}: {} {} is in invalid format for http client {} ", this, name, value, clientName));
- int port = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
+ var port = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
if (port < 0) {
logger.warn("No HTTP port for client in {}", clientName);
return;
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
+import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
* Http Client implementation using a Jersey Client.
*/
public class JerseyClient implements HttpClient {
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
/**
* Logger.
this.client = detmClient();
if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
- HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
+ var authFeature = HttpAuthenticationFeature.basic(userName, password);
this.client.register(authFeature);
}
private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
if (this.https) {
ClientBuilder clientBuilder;
- SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
+ var sslContext = SSLContext.getInstance("TLSv1.2");
if (this.selfSignedCerts) {
sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
String providers = (StringUtils.isBlank(serializationProvider)
? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
- for (String prov : providers.split(",")) {
+ for (String prov : COMMA_PAT.split(providers)) {
this.client.register(Class.forName(prov));
}
}
@Override
public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
- Builder builder = getWebTarget().request();
+ var builder = getWebTarget().request();
if (headers != null) {
headers.forEach(builder::header);
}
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append("JerseyClient [name=");
builder.append(name);
builder.append(", https=");
}
private Builder getBuilder(String path, Map<String, Object> headers) {
- Builder builder = getWebTarget().path(path).request();
+ var builder = getWebTarget().path(path).request();
for (Entry<String, Object> header : headers.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.http.server.internal.JettyJerseyServer;
import org.onap.policy.common.endpoints.http.server.internal.JettyStaticResourceServer;
* Indexed factory implementation.
*/
class IndexedHttpServletServerFactory implements HttpServletServerFactory {
-
- private static final String SPACES_COMMA_SPACES = "\\s*,\\s*";
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* logger.
return servers.get(port);
}
- JettyJerseyServer server = new JettyJerseyServer(name, https, host, port, contextPath, swagger);
+ var server = new JettyJerseyServer(name, https, host, port, contextPath, swagger);
if (managed) {
servers.put(port, server);
}
return serviceList;
}
- for (String serviceName : serviceNames.split(SPACES_COMMA_SPACES)) {
+ for (String serviceName : COMMA_SPACE_PAT.split(serviceNames)) {
addService(serviceList, serviceName, properties);
}
return servers.get(port);
}
- JettyStaticResourceServer server = new JettyStaticResourceServer(name, https, host, port, contextPath);
+ var server = new JettyStaticResourceServer(name, https, host, port, contextPath);
if (managed) {
servers.put(port, server);
}
String servicePrefix = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + serviceName;
- PropertyUtils props = new PropertyUtils(properties, servicePrefix,
+ var props = new PropertyUtils(properties, servicePrefix,
(name, value, ex) -> logger
.warn("{}: {} {} is in invalid format for http service {} ", this, name, value, serviceName));
- int servicePort = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
+ var servicePort = props.getInteger(PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, -1);
if (servicePort < 0) {
logger.warn("No HTTP port for service in {}", serviceName);
return;
}
- final String hostName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, null);
- final String contextUriPath =
- props.getString(PolicyEndPointProperties.PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX, null);
- boolean managed = props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true);
- boolean swagger = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, false);
- boolean https = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false);
+ final var hostName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, null);
+ final var contextUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX, null);
+ var managed = props.getBoolean(PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, true);
+ var swagger = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, false);
+ var https = props.getBoolean(PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, false);
// create the service
HttpServletServer service = build(serviceName, https, hostName, servicePort, contextUriPath, swagger, managed);
setSerializationProvider(props, service);
setAuthentication(props, service, contextUriPath);
- final String restUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_URIPATH_SUFFIX, null);
+ final var restUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_URIPATH_SUFFIX, null);
addFilterClasses(props, service, restUriPath);
addServletClasses(props, service, restUriPath);
private void setSerializationProvider(PropertyUtils props, HttpServletServer service) {
- final String classProv = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, null);
+ final var classProv = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, null);
if (!StringUtils.isBlank(classProv)) {
service.setSerializationProvider(classProv);
private void setAuthentication(PropertyUtils props, HttpServletServer service, final String contextUriPath) {
/* authentication method either AAF or HTTP Basic Auth */
- boolean aaf = props.getBoolean(PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, false);
- final String userName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, null);
- final String password = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, null);
- final String authUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_URIPATH_SUFFIX, null);
+ final var aaf = props.getBoolean(PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, false);
+ final var userName = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, null);
+ final var password = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, null);
+ final var authUriPath = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_AUTH_URIPATH_SUFFIX, null);
if (aaf) {
service.setAafAuthentication(contextUriPath);
private void addFilterClasses(PropertyUtils props, HttpServletServer service, final String restUriPath) {
- final String filterClasses =
+ final var filterClasses =
props.getString(PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX, null);
if (!StringUtils.isBlank(filterClasses)) {
- for (String filterClass : filterClasses.split(SPACES_COMMA_SPACES)) {
+ for (String filterClass : COMMA_SPACE_PAT.split(filterClasses)) {
service.addFilterClass(restUriPath, filterClass);
}
}
private void addServletClasses(PropertyUtils props, HttpServletServer service, final String restUriPath) {
- final String restClasses = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, null);
+ final var restClasses = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, null);
if (!StringUtils.isBlank(restClasses)) {
- for (String restClass : restClasses.split(SPACES_COMMA_SPACES)) {
+ for (String restClass : COMMA_SPACE_PAT.split(restClasses)) {
service.addServletClass(restUriPath, restClass);
}
}
private void addServletPackages(PropertyUtils props, HttpServletServer service, final String restUriPath) {
- final String restPackages = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, null);
+ final var restPackages = props.getString(PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, null);
if (!StringUtils.isBlank(restPackages)) {
- for (String restPackage : restPackages.split(SPACES_COMMA_SPACES)) {
+ for (String restPackage : COMMA_SPACE_PAT.split(restPackages)) {
service.addServletPackage(restUriPath, restPackage);
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property.
+ * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @return the properties object
*/
protected Properties getServerProperties(RestServerParameters restServerParameters, String names) {
- final Properties props = new Properties();
+ final var props = new Properties();
props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, restServerParameters.getName());
final String svcpfx =
* @return the provider class names
*/
private String getProviderClassNames(Class<?>[] jaxrsProviders) {
- StringBuilder names = new StringBuilder();
+ var names = new StringBuilder();
for (Class<?> prov : jaxrsProviders) {
if (names.length() > 0) {
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
- try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
+ try (var writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) {
translator.toYaml(writer, object);
}
}
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
- try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
+ try (var streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) {
Class<?> clazz = (Class<?>) genericType;
return translator.fromYaml(streamReader, clazz);
* ============LICENSE_START=======================================================
* policy-endpoints
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append("JettyJerseyServer [Jerseyservlets=").append(servlets).append(", swaggerId=").append(swaggerId)
.append(", toString()=").append(super.toString()).append("]");
return builder.toString();
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019-2020 Nordix Foundation.
* Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
* ================================================================================
this.jettyServer = new Server();
- CustomRequestLog requestLog =
- new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
+ var requestLog = new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
this.jettyServer.setRequestLog(requestLog);
if (https) {
}
}
- HttpConfiguration https = new HttpConfiguration();
+ var https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
srvltPath = "/*";
}
- final HashLoginService hashLoginService = new HashLoginService();
- final UserStore userStore = new UserStore();
+ final var hashLoginService = new HashLoginService();
+ final var userStore = new UserStore();
userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
hashLoginService.setUserStore(userStore);
hashLoginService.setName(this.connector.getName() + "-login-service");
- Constraint constraint = new Constraint();
+ var constraint = new Constraint();
constraint.setName(Constraint.__BASIC_AUTH);
constraint.setRoles(new String[] {"user"});
constraint.setAuthenticate(true);
- ConstraintMapping constraintMapping = new ConstraintMapping();
+ var constraintMapping = new ConstraintMapping();
constraintMapping.setConstraint(constraint);
constraintMapping.setPathSpec(srvltPath);
- ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
+ var securityHandler = new ConstraintSecurityHandler();
securityHandler.setAuthenticator(new BasicAuthenticator());
securityHandler.setRealmName(this.connector.getName() + "-realm");
securityHandler.addConstraintMapping(constraintMapping);
}
this.jettyServer.join();
+
+ } catch (InterruptedException e) {
+ logger.error("{}: error found while bringing up server", this, e);
+ Thread.currentThread().interrupt();
+
} catch (Exception e) {
logger.error("{}: error found while bringing up server", this, e);
}
@Override
public String toString() {
- StringBuilder builder = new StringBuilder();
+ var builder = new StringBuilder();
builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
.append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
.append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public void onTopicEvent(CommInfrastructure infra, String topic, StandardCoderObject sco) {
// extract the message type
- final String type = sco.getString(messageFieldNames);
+ final var type = sco.getString(messageFieldNames);
if (type == null) {
logger.warn("unable to extract {}: {}", fullMessageFieldName, sco);
return;
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public void onTopicEvent(CommInfrastructure infra, String topic, StandardCoderObject sco, T message) {
// extract the request id
- String reqid = sco.getString(requestIdFieldNames);
+ var reqid = sco.getString(requestIdFieldNames);
// dispatch the message
if (Strings.isNullOrEmpty(reqid)) {
public BeanValidationResult validate() {
BeanValidationResult result = super.validate();
if (result.isValid()) {
- StringBuilder errorMsg = new StringBuilder();
+ var errorMsg = new StringBuilder();
StringBuilder missingSourceParams = checkMissingMandatoryParams(topicSources);
if (missingSourceParams.length() > 0) {
errorMsg.append(missingSourceParams.append("missing in topicSources. "));
}
private StringBuilder checkMissingMandatoryParams(List<TopicParameters> topicParametersList) {
- StringBuilder missingParams = new StringBuilder();
+ var missingParams = new StringBuilder();
for (TopicParameters topicParameters : topicParametersList) {
if (StringUtils.isBlank(topicParameters.getTopic())) {
missingParams.append("topic, ");
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public String toString() {
- final StringBuilder builder = new StringBuilder();
+ final var builder = new StringBuilder();
builder.append("Report [name=");
builder.append(getName());
builder.append(", url=");
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
public class DmaapPropertyUtils {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
/**
* Maps a topic property to a DME property.
for (Map.Entry<String, String> ent : PROP_TO_DME.entrySet()) {
String propName = ent.getKey();
- String value = props.getString(propName, null);
+ var value = props.getString(propName, null);
if (!StringUtils.isBlank(value)) {
String dmeName = ent.getValue();
}
}
- final List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+ final List<String> serverList = new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
return BusTopicParams.builder()
.servers(serverList)
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.regex.Pattern;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
public class UebPropertyUtils {
+ private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
private UebPropertyUtils() {
// do nothing
*/
public static TopicParamsBuilder makeBuilder(PropertyUtils props, String topic, String servers) {
- final List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*")));
+ final List<String> serverList = new ArrayList<>(Arrays.asList(COMMA_SPACE_PAT.split(servers)));
return BusTopicParams.builder()
.servers(serverList)
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
-import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
-import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
*/
public void compareGson(Object object, File expected) {
// file is not required to have a full path - find it via getResource()
- URL url = object.getClass().getResource(expected.getName());
+ var url = object.getClass().getResource(expected.getName());
if (url == null) {
throw new JsonParseException(new FileNotFoundException(expected.getName()));
}
* @return the text, after interpolating the script elements
*/
public String applyScripts(String text, Object object) {
- Matcher mat = SCRIPT_PAT.matcher(text);
+ var mat = SCRIPT_PAT.matcher(text);
if (!mat.find()) {
// contains no script elements - just return it as is
return text;
context.set("obj", object);
// work our way through the text, interpolating script elements as we go
- StringBuilder bldr = new StringBuilder();
- int ilast = 0;
+ var bldr = new StringBuilder();
+ var ilast = 0;
mat.reset();
while (mat.find(ilast)) {
// append segment that appears between last match and this
* @return a new object, without the null items
*/
public JsonObject reorder(JsonObject jsonObj) {
- JsonObject newjo = new JsonObject();
+ var newjo = new JsonObject();
// sort the keys before copying to the new object
List<Entry<String, JsonElement>> sortedSet = new ArrayList<>(jsonObj.entrySet());
* @return a new array, with null items removed from all elements
*/
public JsonArray reorder(JsonArray jsonArray) {
- JsonArray newarr = new JsonArray();
+ var newarr = new JsonArray();
for (JsonElement ent : jsonArray) {
newarr.add(reorder(ent));
}
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @throws IOException if an error occurs
*/
public static <T> byte[] serialize(T object) throws IOException {
- try (ByteArrayOutputStream out = factory.makeByteArrayOutputStream()) {
- try (ObjectOutputStream oos = factory.makeObjectOutputStream(out)) {
+ try (var out = factory.makeByteArrayOutputStream()) {
+ try (var oos = factory.makeObjectOutputStream(out)) {
/*
* writeObject() is final and mockito can't mock final methods. In
* addition, powermock seemed to be having difficulty with the junit test
*/
private static <T> T deserialize(Class<T> clazz, byte[] data) throws IOException {
- try (ByteArrayInputStream in = factory.makeByteArrayInputStream(data);
- ObjectInputStream ois = factory.makeObjectInputStream(in)) {
+ try (var in = factory.makeByteArrayInputStream(data);
+ var ois = factory.makeObjectInputStream(in)) {
/*
* readObject() is final and mockito can't mock final methods. In addition,
* powermock seemed to be having difficulty with the junit test class as well,
keystoreName = System.getProperty("user.dir") + "/" + relativePath;
// use existing file if it isn't too old
- File keystore = new File(keystoreName);
+ var keystore = new File(keystoreName);
if (keystore.exists()) {
if (System.currentTimeMillis() < keystore.lastModified()
+ TimeUnit.MILLISECONDS.convert(5, TimeUnit.HOURS)) {
* dropping the trailing comma.
*/
String sanName = getKeystoreSanName();
- String subAltNames = ResourceUtils.getResourceAsString(sanName);
+ var subAltNames = ResourceUtils.getResourceAsString(sanName);
if (subAltNames == null) {
throw new FileNotFoundException(sanName);
}
// build up the "keytool" command
// @formatter:off
- ProcessBuilder builder = new ProcessBuilder("keytool", "-genkeypair",
+ var builder = new ProcessBuilder("keytool", "-genkeypair",
"-alias", "policy@policy.onap.org",
"-validity", "1",
"-keyalg", "RSA",
* ============LICENSE_START====================================================
* Common Utils-Test
* =============================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights reserved.
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* if the constructed objects fail to pass various tests
*/
public <T extends Exception> int testAllException(final Class<T> claz) {
- int ncons = 0;
+ var ncons = 0;
ncons += testAllThrowable(claz);
ncons += testException(claz);
return 0;
}
- Exception cause = new Exception(EXPECTED_EXCEPTION_MSG);
- T ex = newInstance(cons, cause);
+ var cause = new Exception(EXPECTED_EXCEPTION_MSG);
+ var ex = newInstance(cons, cause);
assertNotNull(ex.toString());
assertEquals(ex.getMessage(), ex.getMessage());
return 0;
}
- Exception cause = new Exception(EXPECTED_EXCEPTION_MSG);
- T ex = newInstance(cons, "world", cause);
+ var cause = new Exception(EXPECTED_EXCEPTION_MSG);
+ var ex = newInstance(cons, "world", cause);
assertNotNull(ex.toString());
assertEquals("world", ex.getMessage());
* ============LICENSE_START====================================================
* Common Utils-Test
* =============================================================================
- * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
public final <T extends Throwable> int testAllThrowable(
final Class<T> claz) {
- int ncons = 0;
+ var ncons = 0;
ncons += testDefault(claz);
ncons += testString(claz);
return 0;
}
- T ex = newInstance(cons);
+ var ex = newInstance(cons);
assertNotNull(ex.toString());
assertNull(ex.getMessage());
return 0;
}
- T ex = newInstance(cons, "hello");
+ var ex = newInstance(cons, "hello");
assertNotNull(ex.toString());
assertEquals("hello", ex.getMessage());
return 0;
}
- T ex = newInstance(cons, CAUSE);
+ var ex = newInstance(cons, CAUSE);
assertEquals(ex.getMessage(), ex.getMessage());
assertNotNull(ex.toString());
return 0;
}
- T ex = newInstance(cons, "world", CAUSE);
+ var ex = newInstance(cons, "world", CAUSE);
assertNotNull(ex.toString());
assertEquals("world", ex.getMessage());
*/
public final <T extends Throwable> void testSuppressStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "yes,yes", CAUSE, true, true);
+ var ex = newInstance(cons, "yes,yes", CAUSE, true, true);
ex.addSuppressed(SUPPRESSED);
*/
public final <T extends Throwable> void testSuppressNoStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "yes,no", CAUSE, true, false);
+ var ex = newInstance(cons, "yes,no", CAUSE, true, false);
ex.addSuppressed(SUPPRESSED);
*/
public final <T extends Throwable> void testNoSuppressStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "no,yes", CAUSE, false, true);
+ var ex = newInstance(cons, "no,yes", CAUSE, false, true);
ex.addSuppressed(SUPPRESSED);
*/
public final <T extends Throwable> void testNoSuppressNoStack(
final Constructor<T> cons) {
- T ex = newInstance(cons, "no,no", CAUSE, false, false);
+ var ex = newInstance(cons, "no,no", CAUSE, false, false);
ex.addSuppressed(SUPPRESSED);
* ============LICENSE_START====================================================
* Common Utils-Test
* =============================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights reserved.
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
for (Pattern p : patterns.values()) {
- Matcher matcher = p.matcher(msg);
+ var matcher = p.matcher(msg);
if (matcher.find()) {
addGroupMatch(matcher);
private void addGroupMatch(final Matcher mat) {
int ngroups = mat.groupCount();
- for (int x = 1; x <= ngroups; ++x) {
+ for (var x = 1; x <= ngroups; ++x) {
String txt = mat.group(x);
if (txt != null) {
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* tasks have been reached before the queue was emptied
*/
public boolean runAll(int maxTasks) {
- for (int count = 0; count < maxTasks && !tasks.isEmpty(); ++count) {
+ for (var count = 0; count < maxTasks && !tasks.isEmpty(); ++count) {
tasks.remove().run();
}
return;
}
- SleepItem item = new SleepItem(this, sleepMs, Thread.currentThread());
+ var item = new SleepItem(this, sleepMs, Thread.currentThread());
enqueue(item);
// wait for the item to fire
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URISyntaxException;
-import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
* @return the help string
*/
public String help() {
- final HelpFormatter helpFormatter = new HelpFormatter();
- final StringWriter stringWriter = new StringWriter();
- final PrintWriter printWriter = new PrintWriter(stringWriter);
+ final var helpFormatter = new HelpFormatter();
+ final var stringWriter = new StringWriter();
+ final var printWriter = new PrintWriter(stringWriter);
final String cmdLineSyntax = this.helpClassName + " [options...]";
helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, cmdLineSyntax, "options", options, 0, 0, "");
}
// The file name refers to a resource on the local file system
- final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
+ final var fileUrl = ResourceUtils.getUrl4Resource(fileName);
if (fileUrl == null) {
throw new CommandLineException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
}
try {
- Path path = Path.of(fileUrl.toURI());
+ var path = Path.of(fileUrl.toURI());
if (!Files.isRegularFile(path)) {
throw new CommandLineException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file");
}
* ============LICENSE_START=======================================================
* ONAP PAP
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @return a class T object
*/
public <T> T decode(String json, String keyProperty, Class<T> clazz) {
- JsonElement jsonElement = GSON.fromJson(json, JsonElement.class);
+ var jsonElement = GSON.fromJson(json, JsonElement.class);
return new MyDecoder(jsonElement, keyProperty).decrypt(jsonElement, clazz);
}
public <T> T decode(Reader reader, String keyProperty, Class<T> clazz) {
- JsonElement jsonElement = GSON.fromJson(reader, JsonElement.class);
+ var jsonElement = GSON.fromJson(reader, JsonElement.class);
return new MyDecoder(jsonElement, keyProperty).decrypt(jsonElement, clazz);
}
if (!jsonElement.isJsonObject()) {
return;
}
- JsonObject jsonObject = jsonElement.getAsJsonObject();
+ var jsonObject = jsonElement.getAsJsonObject();
// Use keyProperty from input to retrieve secretKey
- String secretKey = jsonObject.get(keyProperty).getAsString();
+ var secretKey = jsonObject.get(keyProperty).getAsString();
if (!StringUtils.isBlank(secretKey)) {
crypto = new CryptoUtils(secretKey);
}
if (!jsonElement.getAsJsonPrimitive().isString()) {
return jsonElement;
}
- String value = jsonElement.getAsString();
+ var value = jsonElement.getAsString();
if (!value.startsWith("enc:")) {
return jsonElement;
}
if (crypto == null) {
return jsonArray;
}
- JsonArray newArray = new JsonArray();
+ var newArray = new JsonArray();
for (JsonElement element: jsonArray) {
newArray.add(decrypt(element));
}
if (crypto == null) {
return jsonObject;
}
- JsonObject newObject = new JsonObject();
+ var newObject = new JsonObject();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
- JsonElement jsonElement = decrypt(entry.getValue());
+ var jsonElement = decrypt(entry.getValue());
newObject.add(key, jsonElement);
}
return newObject;
}
}
-}
\ No newline at end of file
+}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public void encode(OutputStream target, Object object) throws CoderException {
try {
- Writer wtr = makeWriter(target);
+ var wtr = makeWriter(target);
toJson(wtr, object);
// flush, but don't close
@Override
public void encode(File target, Object object) throws CoderException {
- try (Writer wtr = makeWriter(target)) {
+ try (var wtr = makeWriter(target)) {
toJson(wtr, object);
// no need to flush or close here
@Override
public <T> T decode(File source, Class<T> clazz) throws CoderException {
- try (Reader input = makeReader(source)) {
+ try (var input = makeReader(source)) {
return fromJson(input, clazz);
} catch (RuntimeException | IOException e) {
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.common.utils.coder;
-import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import java.io.Serializable;
return null;
}
- JsonArray array = element.getAsJsonArray();
+ var array = element.getAsJsonArray();
if (index >= array.size()) {
return null;
/*--
* ============LICENSE_START=======================================================
- * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
protected String toJson(@NonNull Object object) {
- StringWriter output = new StringWriter();
+ var output = new StringWriter();
toJson(output, object);
return output.toString();
}
@Override
protected <T> T fromJson(String json, Class<T> clazz) {
- StringReader reader = new StringReader(json);
+ var reader = new StringReader(json);
return convertFromDouble(clazz, gson.fromJson(validatorApi.createJsonReader(validator, reader), clazz));
}
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @return YAML representing the original object
*/
public String toYaml(Object object) {
- StringWriter output = new StringWriter();
+ var output = new StringWriter();
toYaml(output, object);
return output.toString();
}
* @param object POJO to be translated
*/
public void toYaml(Writer target, Object object) {
- DumperOptions dumper = new DumperOptions();
- Serializer serializer = new Serializer(new Emitter(target, dumper), new Resolver(), dumper, null);
+ var dumper = new DumperOptions();
+ var serializer = new Serializer(new Emitter(target, dumper), new Resolver(), dumper, null);
try {
serializer.open();
* @return a POJO representing the YAML read from the reader
*/
public <T> T fromYaml(Reader source, Class<T> clazz) {
- Node node = new Yaml().compose(source);
+ var node = new Yaml().compose(source);
return fromJson(makeJson(node), clazz);
}
protected JsonArray makeJsonArray(SequenceNode node) {
List<Node> nodes = node.getValue();
- JsonArray array = new JsonArray(nodes.size());
+ var array = new JsonArray(nodes.size());
nodes.forEach(subnode -> array.add(makeJson(subnode)));
return array;
* @return a gson element corresponding to the node
*/
protected JsonObject makeJsonObject(MappingNode node) {
- JsonObject obj = new JsonObject();
+ var obj = new JsonObject();
for (NodeTuple tuple : node.getValue()) {
- Node key = tuple.getKeyNode();
+ var key = tuple.getKeyNode();
String skey = ((ScalarNode) key).getValue();
obj.add(skey, makeJson(tuple.getValueNode()));
*/
protected JsonElement makeJsonPrim(ScalarNode node) {
try {
- Tag tag = node.getTag();
+ var tag = node.getTag();
if (tag == Tag.INT) {
return new JsonPrimitive(Long.valueOf(node.getValue()));
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
public static boolean isTcpPortOpen(String host, int port, int retries, long interval)
throws InterruptedException {
- int retry = 0;
+ var retry = 0;
while (retry < retries) {
/*
* As with the server socket, this is only used to see if the port is open,
* ============LICENSE_START=======================================================
* ONAP - Common Modules
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.common.utils.properties;
+import com.google.re2j.Pattern;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
* <i>accept</i> includes the "empty" option.
*/
public class BeanConfigurator {
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
/**
* The "empty" option that may appear within the {@link Property}'s <i>accept</i>
* @return {@code true} if the <i>accept</i> attribute includes "empty"
*/
protected boolean isEmptyOk(Property prop) {
- for (String option : prop.accept().split(",")) {
+ for (String option : COMMA_PAT.split(prop.accept())) {
if (ACCEPT_EMPTY.equals(option)) {
return true;
}
* @throws PropertyAccessException if a "get" method cannot be identified
*/
private Method getGetter(Field field, Property prop) throws PropertyAccessException {
- String capnm = StringUtils.capitalize(field.getName());
+ var capnm = StringUtils.capitalize(field.getName());
try {
return getGetter(field, "get" + capnm);
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.List;
import java.util.Map;
import java.util.Properties;
-import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public static final Logger logger = LoggerFactory.getLogger(PropertyObjectUtils.class);
private static final Pattern NAME_PAT = Pattern.compile("\\[(\\d{1,3})\\]$");
+ private static final Pattern DOT_PAT = Pattern.compile("[.]");
private PropertyObjectUtils() {
// do nothing
for (String name : properties.stringPropertyNames()) {
if (name.startsWith(dottedPrefix)) {
- String[] components = name.substring(pfxlen).split("[.]");
+ String[] components = DOT_PAT.split(name.substring(pfxlen));
setProperty(map, components, properties.getProperty(name));
}
}
final int lastComp = names.length - 1;
// process all but the final component
- for (int comp = 0; comp < lastComp; ++comp) {
+ for (var comp = 0; comp < lastComp; ++comp) {
node = getNode(node, names[comp]);
}
// process the final component
String name = names[lastComp];
- Matcher matcher = NAME_PAT.matcher(name);
+ var matcher = NAME_PAT.matcher(name);
if (!matcher.find()) {
// no subscript
// subscripted
List<Object> array = getArray(node, name.substring(0, matcher.start()));
- int index = Integer.parseInt(matcher.group(1));
+ var index = Integer.parseInt(matcher.group(1));
expand(array, index);
array.set(index, value);
}
*/
@SuppressWarnings("unchecked")
private static Map<String, Object> getNode(Map<String, Object> map, String name) {
- Matcher matcher = NAME_PAT.matcher(name);
+ var matcher = NAME_PAT.matcher(name);
if (!matcher.find()) {
// no subscript
// subscripted
List<Object> array = getArray(map, name.substring(0, matcher.start()));
- int index = Integer.parseInt(matcher.group(1));
+ var index = Integer.parseInt(matcher.group(1));
expand(array, index);
Object item = array.get(index);
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
return super.getProperty(key);
}
- String suffix = key.substring(prefix.length());
+ var suffix = key.substring(prefix.length());
String val = super.getProperty(specPrefix + suffix);
if (val != null) {
* ============LICENSE_START=======================================================
* ONAP Policy Engine - Common Modules
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/**
* Constructor.
- *
+ *
* @param propName name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
*/
/**
* Constructor.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param message error message
/**
* Constructor.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param cause cause of the exception
/**
* Constructor.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param message error message
/**
* Get the property name.
- *
+ *
* @return name of the property for which the exception was thrown, or {@code null} if
* no name was provided
*/
/**
* Get the field name.
- *
+ *
* @return name of the field for which the exception was thrown, or {@code null} if no
* field was provided
*/
/**
* Make the message.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @param message error message, never {@code null}
/**
* Make the message.
- *
+ *
* @param propnm name of the property causing the exception, or {@code null}
* @param fieldName name of the field causing the exception, or {@code null}
* @return an error message composed of the two items
*/
private static String makeMessage(String propnm, String fieldName) {
- StringBuilder bldr = new StringBuilder(50);
+ var bldr = new StringBuilder(50);
if (propnm == null) {
bldr.append("property exception");
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
- * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
+import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Get a reference to the logger
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class);
+ private static final Pattern SLASH_PAT = Pattern.compile("/");
+
// The length of byte buffers used to read resources into strings
private static final int BYTE_BUFFER_LENGH = 1024;
*/
public static URL getUrl4Resource(final String resourceName) {
// Check the local fine system first
- final URL urlToResource = getLocalFile(resourceName);
+ final var urlToResource = getLocalFile(resourceName);
// Check if this is a local file
if (urlToResource != null) {
}
// Read the stream contents in to an output stream
- final ByteArrayOutputStream resourceOutputStreamBuffer = new ByteArrayOutputStream();
- final byte[] resourceBuffer = new byte[BYTE_BUFFER_LENGH];
+ final var resourceOutputStreamBuffer = new ByteArrayOutputStream();
+ final var resourceBuffer = new byte[BYTE_BUFFER_LENGH];
int length;
try {
while ((length = resourceStream.read(resourceBuffer)) != -1) {
*/
public static InputStream getResourceAsStream(final String resourceName) {
// Find a URL to the resource first
- final URL urlToResource = getUrl4Resource(resourceName);
+ final var urlToResource = getUrl4Resource(resourceName);
// Check if the resource exists
if (urlToResource == null) {
*/
public static URL getUrlResource(final String resourceName) {
try {
- final ClassLoader classLoader = ResourceUtils.class.getClassLoader();
+ final var classLoader = ResourceUtils.class.getClassLoader();
- final String[] fileParts = resourceName.split("/");
+ final String[] fileParts = SLASH_PAT.split(resourceName);
// Read the resource
- URL url = classLoader.getResource(resourceName);
+ var url = classLoader.getResource(resourceName);
// Check if the resource is defined
if (url != null) {
public static URL getLocalFile(final String resourceName) {
try {
// Input might already be in URL format
- final URL ret = new URL(resourceName);
- final File f = new File(ret.toURI());
+ final var ret = new URL(resourceName);
+ final var f = new File(ret.toURI());
if (f.exists()) {
return ret;
}
}
try {
- final File f = new File(resourceName);
+ final var f = new File(resourceName);
// Check if the file exists
if (f.exists()) {
- final URL urlret = f.toURI().toURL();
+ final var urlret = f.toURI().toURL();
LOGGER.debug("resource \"{}\" was found on the local file system", f.toURI().toURL());
return urlret;
} else {
return null;
}
- URL modelFileUrl = getUrl4Resource(resource);
+ var modelFileUrl = getUrl4Resource(resource);
if (modelFileUrl != null) {
return modelFileUrl.getPath();
} else {
*/
public static Set<String> getDirectoryContents(final String resourceDirectoryName) {
// Find the location of the resource, is it in a Jar or on the local file system?
- URL directoryUrl = ResourceUtils.getUrl4Resource(resourceDirectoryName);
+ var directoryUrl = ResourceUtils.getUrl4Resource(resourceDirectoryName);
if (directoryUrl == null) {
LOGGER.debug("resource \"{}\" was not found", resourceDirectoryName);
*/
public static Set<String> getDirectoryContentsLocal(final URL localResourceDirectoryUrl,
final String resourceDirectoryName) {
- File localDirectory = new File(localResourceDirectoryUrl.getFile());
+ var localDirectory = new File(localResourceDirectoryUrl.getFile());
if (!localDirectory.isDirectory()) {
LOGGER.debug("resource \"{}\" is not a directory", resourceDirectoryName);
final String resourceDirectoryName) {
String dirNameWithSlash = resourceDirectoryName + "/";
int minLength = dirNameWithSlash.length() + 1;
- File jarResourceDirectory = new File(jarResourceDirectoryUrl.getPath());
+ var jarResourceDirectory = new File(jarResourceDirectoryUrl.getPath());
String jarFileName = jarResourceDirectory.getParent().replaceFirst("^file:", "").replaceFirst("!.*$", "");
Set<String> localDirectorySet = new TreeSet<>();
- try (JarFile jarFile = new JarFile(jarFileName)) {
+ try (var jarFile = new JarFile(jarFileName)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @throws IOException on errors reading text from the file
*/
public static String getTextFileAsString(final String textFilePath) throws IOException {
- final File textFile = new File(textFilePath);
+ final var textFile = new File(textFilePath);
return Files.readString(textFile.toPath());
}
* @throws IOException on errors reading text from the file
*/
public static void putStringAsTextFile(final String outString, final String textFilePath) throws IOException {
- final File textFile = new File(textFilePath);
+ final var textFile = new File(textFilePath);
if (!textFile.getParentFile().exists()) {
textFile.getParentFile().mkdirs();
}
* @throws IOException on errors reading text from the file
*/
public static String getReaderAsString(final Reader textReader) throws IOException {
- final StringBuilder builder = new StringBuilder();
+ final var builder = new StringBuilder();
int charsRead = -1;
- final char[] chars = new char[READER_CHAR_BUFFER_SIZE_4096];
+ final var chars = new char[READER_CHAR_BUFFER_SIZE_4096];
do {
charsRead = textReader.read(chars);
if (charsRead > 0) {
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @return The encrypted String
*/
public static String encrypt(String value, String secretKey) {
- SecretKeySpec keySpec = readSecretKeySpec(secretKey);
+ var keySpec = readSecretKeySpec(secretKey);
return encryptValue(value, keySpec);
}
return value;
}
try {
- Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS);
- byte[] iv = new byte[IV_BLOCK_SIZE_IN_BYTES];
+ var cipher = Cipher.getInstance(ALGORITHM_DETAILS);
+ var iv = new byte[IV_BLOCK_SIZE_IN_BYTES];
RANDOM.nextBytes(iv);
- GCMParameterSpec ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS, iv);
+ var ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS, iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
return "enc:" + DatatypeConverter.printBase64Binary(
* @return The String decrypted if string begin with 'enc:'
*/
public static String decrypt(String value, String secretKey) {
- SecretKeySpec keySpec = readSecretKeySpec(secretKey);
+ var keySpec = readSecretKeySpec(secretKey);
if (keySpec != null) {
return decryptValue(value, keySpec);
} else {
throw new IllegalArgumentException("Invalid size on input value");
}
try {
- String pureValue = value.substring(4);
+ var pureValue = value.substring(4);
byte[] encryptedValue = DatatypeConverter.parseBase64Binary(pureValue);
- Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS);
- GCMParameterSpec ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS,
+ var cipher = Cipher.getInstance(ALGORITHM_DETAILS);
+ var ivspec = new GCMParameterSpec(TAG_SIZE_IN_BITS,
ArrayUtils.subarray(encryptedValue, 0, IV_BLOCK_SIZE_IN_BYTES));
byte[] realData = ArrayUtils.subarray(encryptedValue, IV_BLOCK_SIZE_IN_BYTES, encryptedValue.length);
* ============LICENSE_START=======================================================
* ONAP COMMON
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
package org.onap.policy.common.utils.validation;
-import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
import lombok.Data;
import lombok.NoArgsConstructor;
* @param versionString the version string
*/
public Version(@NonNull final String versionString) {
- Version newVersion = makeVersion("String", "constructor", versionString);
+ var newVersion = makeVersion("String", "constructor", versionString);
if (newVersion != null) {
this.major = newVersion.major;
* that does not match the major.minor.patch form)
*/
public static Version makeVersion(String type, String name, String versionText) {
- Matcher matcher = VERSION_PAT.matcher(versionText);
+ var matcher = VERSION_PAT.matcher(versionText);
if (!matcher.matches()) {
logger.info("invalid version for {} {}: {}", type, name, versionText);
return null;
@Override
public int compareTo(Version other) {
- int result = Integer.compare(major, other.major);
+ var result = Integer.compare(major, other.major);
if (result != 0) {
return result;
}