diff --git a/core/citrus-base/src/main/java/org/citrusframework/AbstractTestContainerBuilder.java b/core/citrus-base/src/main/java/org/citrusframework/AbstractTestContainerBuilder.java index 8ff791e169..1842106e1d 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/AbstractTestContainerBuilder.java +++ b/core/citrus-base/src/main/java/org/citrusframework/AbstractTestContainerBuilder.java @@ -16,16 +16,16 @@ package org.citrusframework; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.citrusframework.actions.NoopTestAction; import org.citrusframework.container.TestActionContainer; import org.citrusframework.spi.ReferenceResolver; import org.citrusframework.spi.ReferenceResolverAware; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + /** * Abstract container builder takes care on calling the container runner when actions are placed in the container. */ @@ -129,7 +129,7 @@ public T doBuild() { @Override public T build() { - if (container.getActions().size() > 0) { + if (!container.getActions().isEmpty()) { return container; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/CitrusContextProvider.java b/core/citrus-base/src/main/java/org/citrusframework/CitrusContextProvider.java index 33c19afd8d..2a57de23b8 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/CitrusContextProvider.java +++ b/core/citrus-base/src/main/java/org/citrusframework/CitrusContextProvider.java @@ -16,15 +16,15 @@ package org.citrusframework; -import java.util.Map; -import java.util.Optional; - import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.spi.ResourcePathTypeResolver; import org.citrusframework.spi.TypeResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; +import java.util.Optional; + @FunctionalInterface public interface CitrusContextProvider { @@ -85,7 +85,7 @@ static Optional lookup(String name) { CitrusContextProvider instance = TYPE_RESOLVER.resolve(name); return Optional.of(instance); } catch (CitrusRuntimeException e) { - logger.warn(String.format("Failed to resolve Citrus context provider from resource '%s/%s'", RESOURCE_PATH, name)); + logger.warn("Failed to resolve Citrus context provider from resource '{}/{}'", RESOURCE_PATH, name); } return Optional.empty(); diff --git a/core/citrus-base/src/main/java/org/citrusframework/TestCaseRunnerFactory.java b/core/citrus-base/src/main/java/org/citrusframework/TestCaseRunnerFactory.java index 4e9b1a9b9b..074a029f02 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/TestCaseRunnerFactory.java +++ b/core/citrus-base/src/main/java/org/citrusframework/TestCaseRunnerFactory.java @@ -25,7 +25,7 @@ * Citrus' built-in runner, but it also offers the flexibility to replace the default runner with a * custom implementation. To do this, it leverages the Citrus {@link ResourcePathTypeResolver} * mechanism. - * + *

* To provide a custom runner, the following file needs to be added to the classpath: *

* diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/AntRunAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/AntRunAction.java index de79a038c6..44aa241e4c 100755 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/AntRunAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/AntRunAction.java @@ -16,12 +16,6 @@ package org.citrusframework.actions; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Stack; - import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.DefaultLogger; @@ -38,10 +32,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Stack; + /** * Action calls Apache ANT with given build file and runs ANT targets * as separate build. User can set and overwrite properties for the build. - * + *

* Build logging output is forwarded to test run logger. * * @since 1.3 @@ -95,7 +95,7 @@ public void doExecute(TestContext context) { for (Entry entry : properties.entrySet()) { String propertyValue = entry.getValue() != null ? context.replaceDynamicContentInString(entry.getValue().toString()) : ""; - logger.debug("Set build property: " + entry.getKey() + "=" + propertyValue); + logger.debug("Set build property: {}={}", entry.getKey(), propertyValue); project.setProperty(entry.getKey().toString(), propertyValue); } @@ -109,20 +109,20 @@ public void doExecute(TestContext context) { project.addBuildListener(consoleLogger); - logger.info("Executing ANT build: " + buildFileResource); + logger.info("Executing ANT build: {}", buildFileResource); if (StringUtils.hasText(targets)) { - logger.info("Executing ANT targets: " + targets); + logger.info("Executing ANT targets: {}", targets); project.executeTargets(parseTargets()); } else { - logger.info("Executing ANT target: " + target); + logger.info("Executing ANT target: {}", target); project.executeTarget(target); } } catch (BuildException e) { throw new CitrusRuntimeException("Failed to run ANT build file", e); } - logger.info("Executed ANT build: " + buildFileResource); + logger.info("Executed ANT build: {}", buildFileResource); } private static DefaultLogger getDefaultConsoleLogger() { @@ -166,7 +166,7 @@ private Stack parseTargets() { private void loadBuildPropertyFile(Project project, TestContext context) { if (StringUtils.hasText(propertyFilePath)) { String propertyFileResource = context.replaceDynamicContentInString(propertyFilePath); - logger.info("Reading build property file: " + propertyFileResource); + logger.info("Reading build property file: {}", propertyFileResource); Properties fileProperties = new Properties(); try { Resource propertyResource = Resources.fromClasspath(propertyFileResource); @@ -174,10 +174,7 @@ private void loadBuildPropertyFile(Project project, TestContext context) { for (Entry entry : fileProperties.entrySet()) { String propertyValue = entry.getValue() != null ? context.replaceDynamicContentInString(entry.getValue().toString()) : ""; - - if (logger.isDebugEnabled()) { - logger.debug("Set build property from file resource: " + entry.getKey() + "=" + propertyValue); - } + logger.debug("Set build property from file resource: {}={}", entry.getKey(), propertyValue); project.setProperty(entry.getKey().toString(), propertyValue); } } catch (IOException e) { diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/CreateVariablesAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/CreateVariablesAction.java index 2788d24009..8f87eefdd3 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/CreateVariablesAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/CreateVariablesAction.java @@ -16,16 +16,16 @@ package org.citrusframework.actions; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.variable.VariableUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + /** * Action creating new test variables during a test. Existing test variables are overwritten * by new values. @@ -64,7 +64,7 @@ public void doExecute(TestContext context) { //check if value is variable or function (and resolve it if yes) value = context.replaceDynamicContentInString(value); - logger.info("Setting variable: " + key + " to value: " + value); + logger.info("Setting variable: {} to value: {}", key, value); context.setVariable(key, value); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/EchoAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/EchoAction.java index 357b9ec178..930c7cab79 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/EchoAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/EchoAction.java @@ -16,13 +16,13 @@ package org.citrusframework.actions; -import java.util.Date; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Date; + /** * Prints messages to the console/logger during test execution. * @@ -49,7 +49,7 @@ private EchoAction(Builder builder) { @Override public void doExecute(TestContext context) { if (message == null) { - logger.info("Citrus test " + new Date(System.currentTimeMillis())); + logger.info("Citrus test {}", new Date(System.currentTimeMillis())); } else { logger.info(context.getLogModifier().mask(context.replaceDynamicContentInString(message))); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/InputAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/InputAction.java index 24e85d8661..34228e74c4 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/InputAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/InputAction.java @@ -16,6 +16,13 @@ package org.citrusframework.actions; +import org.citrusframework.AbstractTestActionBuilder; +import org.citrusframework.context.TestContext; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -24,17 +31,10 @@ import java.util.StringTokenizer; import java.util.stream.Stream; -import org.citrusframework.AbstractTestActionBuilder; -import org.citrusframework.context.TestContext; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.citrusframework.util.StringUtils; - /** * Test action prompts user data from standard input stream. The input data is then stored as new * test variable. Test workflow stops until user input is complete. - * + *

* Action can declare a set of valid answers, so user will be prompted until a valid * answer was returned. * @@ -77,7 +77,7 @@ public void doExecute(TestContext context) { if (context.getVariables().containsKey(variable)) { input = context.getVariable(variable); - logger.info("Variable " + variable + " is already set (='" + input + "'). Skip waiting for user input"); + logger.info("Variable {} is already set (='{}'). Skip waiting for user input", variable, input); return; } @@ -123,7 +123,7 @@ private boolean checkAnswer(String input) { } } - logger.info("User input is not valid - must be one of " + validAnswers); + logger.info("User input is not valid - must be one of {}", validAnswers); return false; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/JavaAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/JavaAction.java index a8009c3fb9..39c6c22617 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/JavaAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/JavaAction.java @@ -16,14 +16,6 @@ package org.citrusframework.actions; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; @@ -32,6 +24,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + /** * Action to enable class invocation through java reflection * @@ -125,7 +125,7 @@ private void invokeMethod(Object instance, Class[] methodTypes, Object[] meth Arrays.stream(methodTypes).map(Class::getSimpleName).collect(Collectors.joining(",")) + ")' for class '" + instance.getClass() + "'"); } - logger.info("Invoking method '" + methodToRun.toString() + "' on instance '" + instance.getClass() + "'"); + logger.info("Invoking method '{}' on instance '{}'", methodToRun, instance.getClass()); methodToRun.invoke(instance, methodObjects); } @@ -152,7 +152,7 @@ private Object getObjectInstanceFromClass(TestContext context) throws ClassNotFo "is set for Java reflection call"); } - logger.info("Instantiating class for name '" + className + "'"); + logger.info("Instantiating class for name '{}'", className); Class classToRun = Class.forName(className); diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/LoadPropertiesAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/LoadPropertiesAction.java index 29f989a8d3..70f340e33b 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/LoadPropertiesAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/LoadPropertiesAction.java @@ -16,11 +16,6 @@ package org.citrusframework.actions; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; @@ -29,6 +24,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + /** * Action reads property files and creates test variables for every property entry. File * resource path can define a resource located on classpath or file system. @@ -55,9 +55,7 @@ public LoadPropertiesAction(Builder builder) { public void doExecute(TestContext context) { Resource resource = FileUtils.getFileResource(filePath, context); - if (logger.isDebugEnabled()) { - logger.debug("Reading property file " + FileUtils.getFileName(resource.getLocation())); - } + logger.debug("Reading property file {}", FileUtils.getFileName(resource.getLocation())); Properties props = FileUtils.loadAsProperties(resource); @@ -65,13 +63,10 @@ public void doExecute(TestContext context) { for (Entry entry : props.entrySet()) { String key = entry.getKey().toString(); - if (logger.isDebugEnabled()) { - logger.debug("Loading property: " + key + "=" + props.getProperty(key) + " into variables"); - } + logger.debug("Loading property: {}={} into variables", key, props.getProperty(key)); if (logger.isDebugEnabled() && context.getVariables().containsKey(key)) { - logger.debug("Overwriting property " + key + " old value:" + context.getVariable(key) - + " new value:" + props.getProperty(key)); + logger.debug("Overwriting property {} old value:{} new value:{}", key, context.getVariable(key), props.getProperty(key)); } try { @@ -83,7 +78,7 @@ public void doExecute(TestContext context) { context.resolveDynamicValuesInMap(unresolved).forEach(context::setVariable); - logger.info("Loaded property file " + FileUtils.getFileName(resource.getLocation())); + logger.info("Loaded property file {}", FileUtils.getFileName(resource.getLocation())); } /** diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/PurgeEndpointAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/PurgeEndpointAction.java index b01217db4f..bb7424e0eb 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/PurgeEndpointAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/PurgeEndpointAction.java @@ -85,9 +85,7 @@ public PurgeEndpointAction(Builder builder) { @Override public void doExecute(TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug("Purging message endpoints ..."); - } + logger.debug("Purging message endpoints ..."); for (Endpoint endpoint : endpoints) { purgeEndpoint(endpoint, context); @@ -108,9 +106,7 @@ public void doExecute(TestContext context) { * @param context */ private void purgeEndpoint(Endpoint endpoint, TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug("Try to purge message endpoint " + endpoint.getName()); - } + logger.debug("Try to purge message endpoint {}", endpoint.getName()); int messagesPurged = 0; Consumer messageConsumer = endpoint.createConsumer(); @@ -124,14 +120,12 @@ private void purgeEndpoint(Endpoint endpoint, TestContext context) { message = (receiveTimeout >= 0) ? messageConsumer.receive(context, receiveTimeout) : messageConsumer.receive(context); } } catch (ActionTimeoutException e) { - if (logger.isDebugEnabled()) { - logger.debug("Stop purging due to timeout - " + e.getMessage()); - } + logger.debug("Stop purging due to timeout - {}", e.getMessage()); break; } if (message != null) { - logger.debug("Removed message from endpoint " + endpoint.getName()); + logger.debug("Removed message from endpoint {}", endpoint.getName()); messagesPurged++; try { @@ -142,9 +136,7 @@ private void purgeEndpoint(Endpoint endpoint, TestContext context) { } } while (message != null); - if (logger.isDebugEnabled()) { - logger.debug("Purged " + messagesPurged + " messages from endpoint"); - } + logger.debug("Purged {} messages from endpoint", messagesPurged); } /** diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveMessageAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveMessageAction.java index 5f064dc168..113c285c4a 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveMessageAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveMessageAction.java @@ -16,16 +16,6 @@ package org.citrusframework.actions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.citrusframework.context.TestContext; import org.citrusframework.endpoint.Endpoint; import org.citrusframework.exceptions.CitrusRuntimeException; @@ -62,10 +52,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + /** * This action receives messages from a service destination. Action uses a {@link org.citrusframework.endpoint.Endpoint} * to receive the message, this means that this action is independent of any message transport. - * + *

* The received message is validated using a {@link MessageValidator} supporting expected * control message payload and header templates. * @@ -184,9 +184,7 @@ private Message receive(TestContext context) { * @return */ private Message receiveSelected(TestContext context, String selectorString) { - if (logger.isDebugEnabled()) { - logger.debug("Setting message selector: '" + selectorString + "'"); - } + logger.debug("Setting message selector: '{}'", selectorString); Endpoint messageEndpoint = getOrCreateEndpoint(context); Consumer consumer = messageEndpoint.createConsumer(); @@ -201,7 +199,7 @@ private Message receiveSelected(TestContext context, String selectorString) { context, messageEndpoint.getEndpointConfiguration().getTimeout()); } } else { - logger.warn(String.format("Unable to receive selective with consumer implementation: '%s'", consumer.getClass())); + logger.warn("Unable to receive selective with consumer implementation: '{}'", consumer.getClass()); return receive(context); } } @@ -213,9 +211,7 @@ private Message receiveSelected(TestContext context, String selectorString) { protected void validateMessage(Message message, TestContext context) { messageProcessors.forEach(processor -> processor.process(message, context)); - if (logger.isDebugEnabled()) { - logger.debug("Received message:\n" + message.print(context)); - } + logger.debug("Received message:\n{}", message.print(context)); // extract variables from received message content for (VariableExtractor variableExtractor : variableExtractors) { @@ -232,9 +228,7 @@ protected void validateMessage(Message message, TestContext context) { if (validationProcessor != null) { validationProcessor.validate(message, context); } else { - if (logger.isDebugEnabled()) { - logger.debug("Control message:\n" + controlMessage.print(context)); - } + logger.debug("Control message:\n{}", controlMessage.print(context)); if (!validators.isEmpty()) { for (MessageValidator messageValidator : validators) { @@ -733,13 +727,13 @@ public HeaderValidationContext getHeaderValidationContext() { /** * Revisit configured validation context list and automatically add context based on message payload and path * expression contexts if any. - * + *

* This method makes sure that validation contexts are configured. If no validation context has been set yet the method * automatically adds proper validation contexts for Json and XML message payloads. - * + *

* In case a path expression (JsonPath, XPath) context is set but no proper message validation context (Json, Xml) the * method automatically adds the proper message validation context. - * + *

* Only when validation contexts are set properly according to the message type and content the message validation * steps will execute later on. */ diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveTimeoutAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveTimeoutAction.java index 3a8da7ef60..6bc8431aee 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveTimeoutAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/ReceiveTimeoutAction.java @@ -16,9 +16,6 @@ package org.citrusframework.actions; -import java.util.HashMap; -import java.util.Map; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.endpoint.Endpoint; @@ -28,9 +25,12 @@ import org.citrusframework.message.MessageSelectorBuilder; import org.citrusframework.messaging.Consumer; import org.citrusframework.messaging.SelectiveConsumer; +import org.citrusframework.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.citrusframework.util.StringUtils; + +import java.util.HashMap; +import java.util.Map; /** * Action expecting a timeout on a message destination, this means that no message @@ -85,9 +85,7 @@ public void doExecute(TestContext context) { } if (receivedMessage != null) { - if (logger.isDebugEnabled()) { - logger.debug("Received message:\n" + receivedMessage.print(context)); - } + logger.debug("Received message:\n{}", receivedMessage.print(context)); throw new CitrusRuntimeException("Message timeout validation failed! " + "Received message while waiting for timeout on destination"); diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java index 6283ea0ee7..bf449167d7 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java @@ -26,7 +26,6 @@ import org.citrusframework.message.MessageProcessor; import org.citrusframework.message.builder.MessageBuilderSupport; import org.citrusframework.message.builder.SendMessageBuilderSupport; -import org.citrusframework.util.StringUtils; import org.citrusframework.variable.VariableExtractor; import org.citrusframework.variable.dictionary.DataDictionary; import org.slf4j.Logger; @@ -37,6 +36,7 @@ import java.util.concurrent.CompletableFuture; import static java.util.concurrent.Executors.newSingleThreadExecutor; +import static org.citrusframework.util.StringUtils.hasText; /** * This action sends a messages to a specified message endpoint. The action holds a reference to @@ -120,10 +120,8 @@ public void doExecute(final TestContext context) { finished.whenComplete((ctx, ex) -> { if (ex != null) { - if (logger.isWarnEnabled()) { - logger.warn("Failure in forked send action: %s".formatted(ex.getMessage())); - } - } else { + logger.warn("Failure in forked send action", ex); + } else if (logger.isWarnEnabled()) { for (Exception ctxEx : ctx.getExceptions()) { logger.warn(ctxEx.getMessage()); } @@ -137,12 +135,11 @@ public void doExecute(final TestContext context) { final Endpoint messageEndpoint = getOrCreateEndpoint(context); - if (StringUtils.hasText(message.getName())) { + if (hasText(message.getName())) { context.getMessageStore().storeMessage(message.getName(), message); } else { context.getMessageStore() - .storeMessage(context.getMessageStore().constructMessageName(this, messageEndpoint), - message); + .storeMessage(context.getMessageStore().constructMessageName(this, messageEndpoint), message); } if (forkMode) { @@ -178,12 +175,11 @@ public void doExecute(final TestContext context) { * Validate the message against registered schema validators. */ protected void validateMessage(Message message, TestContext context) { - context.getMessageValidatorRegistry().getSchemaValidators().values().stream() - .filter(validator -> validator.canValidate(message, isSchemaValidation())).forEach(validator -> - validator.validate(message, context, this.schemaRepository, this.schema)); + context.getMessageValidatorRegistry().getSchemaValidators().values().stream() + .filter(validator -> validator.canValidate(message, isSchemaValidation())) + .forEach(validator -> validator.validate(message, context, this.schemaRepository, this.schema)); } - /** * {@inheritDoc} */ @@ -236,7 +232,7 @@ protected Message createMessage(TestContext context, String messageType) { public Endpoint getOrCreateEndpoint(TestContext context) { if (endpoint != null) { return endpoint; - } else if (StringUtils.hasText(endpointUri)) { + } else if (hasText(endpointUri)) { return context.getEndpointFactory().create(endpointUri, context); } else { throw new CitrusRuntimeException("Neither endpoint nor endpoint uri is set properly!"); @@ -434,8 +430,7 @@ public final T build() { if (referenceResolver != null) { if (messageBuilderSupport.getDataDictionaryName() != null) { this.messageBuilderSupport.dictionary( - referenceResolver.resolve(messageBuilderSupport.getDataDictionaryName(), - DataDictionary.class)); + referenceResolver.resolve(messageBuilderSupport.getDataDictionaryName(), DataDictionary.class)); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/SleepAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/SleepAction.java index 4be7addf79..d5daac2fe3 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/SleepAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/SleepAction.java @@ -16,15 +16,15 @@ package org.citrusframework.actions; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.time.Duration; +import java.util.concurrent.TimeUnit; + /** * Stop the test execution for a given amount of time. * @@ -55,7 +55,7 @@ public void doExecute(TestContext context) { String duration = context.resolveDynamicValue(time); try { - logger.info(String.format("Sleeping %s %s", duration, timeUnit)); + logger.info("Sleeping {} {}", duration, timeUnit); if (duration.indexOf(".") > 0) { switch (timeUnit) { @@ -76,7 +76,7 @@ public void doExecute(TestContext context) { timeUnit.sleep(Long.parseLong(duration)); } - logger.info(String.format("Returning after %s %s", duration, timeUnit)); + logger.info("Returning after {} {}", duration, timeUnit); } catch (InterruptedException e) { throw new CitrusRuntimeException(e); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/StartServerAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/StartServerAction.java index 98bfb7ae9f..a1c40cd3dc 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/StartServerAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/StartServerAction.java @@ -16,11 +16,6 @@ package org.citrusframework.actions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.server.Server; @@ -29,6 +24,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + /** * Action starting a {@link Server} instance. * @@ -54,7 +54,7 @@ public StartServerAction(Builder builder) { public void doExecute(TestContext context) { for (Server server : servers) { server.start(); - logger.info("Started server: " + server.getName()); + logger.info("Started server: {}", server.getName()); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/StopServerAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/StopServerAction.java index 12cf143651..5e2b439db2 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/StopServerAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/StopServerAction.java @@ -16,11 +16,6 @@ package org.citrusframework.actions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.server.Server; @@ -29,6 +24,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + /** * Action stopping {@link Server} instances. * @@ -54,7 +54,7 @@ public StopServerAction(Builder builder) { public void doExecute(TestContext context) { for (Server server : servers) { server.stop(); - logger.info("Stopped server: " + server.getName()); + logger.info("Stopped server: {}", server.getName()); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimeAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimeAction.java index 0436a1bee1..b82d9f6a52 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimeAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimeAction.java @@ -61,12 +61,12 @@ public void doExecute(TestContext context) { context.setVariable(timeLineId + timeLineSuffix, time); if (description != null) { - logger.info("TimeWatcher " + timeLineId + " after " + time + " ms (" + description + ")"); + logger.info("TimeWatcher {} after {} ms ({})", timeLineId, time, description); } else { - logger.info("TimeWatcher " + timeLineId + " after " + time + " ms"); + logger.info("TimeWatcher {} after {} ms", timeLineId, time); } } else { - logger.info("Starting TimeWatcher: " + timeLineId); + logger.info("Starting TimeWatcher: {}", timeLineId); context.setVariable(timeLineId, System.currentTimeMillis()); context.setVariable(timeLineId + timeLineSuffix, 0L); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimerAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimerAction.java index 9c2e2a8b79..142324e29a 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimerAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/StopTimerAction.java @@ -47,7 +47,7 @@ public String getTimerId() { public void doExecute(TestContext context) { if (timerId != null) { boolean success = context.stopTimer(timerId); - logger.info(String.format("Stopping timer %s - stop successful: %s", timerId, success)); + logger.info("Stopping timer {} - stop successful: {}", timerId, success); } else { context.stopTimers(); logger.info("Stopping all timers"); diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/TraceVariablesAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/TraceVariablesAction.java index d387beb395..d3d24b9d1a 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/TraceVariablesAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/TraceVariablesAction.java @@ -16,16 +16,16 @@ package org.citrusframework.actions; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Stream; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.context.TestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Stream; + /** * Action that prints variable values to the console/logger. Action requires a list of variable * names. Tries to find the variables in the test context and print its values. @@ -53,7 +53,7 @@ public void doExecute(TestContext context) { logger.info("Trace variables"); Iterator it; - if (variableNames != null && variableNames.size() > 0) { + if (variableNames != null && !variableNames.isEmpty()) { it = variableNames.iterator(); } else { it = context.getVariables().keySet().iterator(); @@ -63,7 +63,7 @@ public void doExecute(TestContext context) { String key = it.next(); String value = context.getVariable(key); - logger.info("Variable " + context.getLogModifier().mask(key + " = " + value)); + logger.info("Variable {}", context.getLogModifier().mask(key + " = " + value)); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/TransformAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/TransformAction.java index d32c8773d5..d9e5293399 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/TransformAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/TransformAction.java @@ -85,9 +85,7 @@ public TransformAction(Builder builder) { @Override public void doExecute(TestContext context) { try { - if (logger.isDebugEnabled()) { - logger.debug("Starting XSLT transformation"); - } + logger.debug("Starting XSLT transformation"); //parse XML document and define XML source for transformation Source xmlSource; diff --git a/core/citrus-base/src/main/java/org/citrusframework/annotations/CitrusAnnotations.java b/core/citrus-base/src/main/java/org/citrusframework/annotations/CitrusAnnotations.java index 88fa8578b2..e6af3437ba 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/annotations/CitrusAnnotations.java +++ b/core/citrus-base/src/main/java/org/citrusframework/annotations/CitrusAnnotations.java @@ -16,10 +16,6 @@ package org.citrusframework.annotations; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.util.Arrays; - import org.citrusframework.Citrus; import org.citrusframework.CitrusContext; import org.citrusframework.GherkinTestActionRunner; @@ -34,6 +30,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.util.Arrays; + /** * Dependency injection support for {@link CitrusFramework}, {@link CitrusResource} and {@link CitrusEndpoint} annotations. * @@ -105,7 +105,7 @@ public static void injectCitrusFramework(final Object testCase, final Citrus cit return; } - logger.trace(String.format("Injecting Citrus framework instance on test class field '%s'", field.getName())); + logger.trace("Injecting Citrus framework instance on test class field '{}'", field.getName()); ReflectionHelper.setField(field, testCase, citrusFramework); }); } @@ -121,7 +121,7 @@ public static void injectCitrusContext(final Object target, final CitrusContext return; } - logger.trace(String.format("Injecting Citrus context instance on test class field '%s'", field.getName())); + logger.trace("Injecting Citrus context instance on test class field '{}'", field.getName()); ReflectionHelper.setField(field, target, context); }); } @@ -139,7 +139,7 @@ public static void injectTestContext(final Object target, final TestContext cont Class type = field.getType(); if (TestContext.class.isAssignableFrom(type)) { - logger.trace(String.format("Injecting test context instance on test class field '%s'", field.getName())); + logger.trace("Injecting test context instance on test class field '{}'", field.getName()); ReflectionHelper.setField(field, target, context); } else { throw new CitrusRuntimeException("Not able to provide a Citrus resource injection for type " + type); @@ -160,7 +160,7 @@ public static void injectTestRunner(final Object target, final TestCaseRunner ru Class type = field.getType(); if (TestCaseRunner.class.isAssignableFrom(type)) { - logger.trace(String.format("Injecting test runner instance on test class field '%s'", field.getName())); + logger.trace("Injecting test runner instance on test class field '{}'", field.getName()); ReflectionHelper.setField(field, target, runner); } else { throw new CitrusRuntimeException("Not able to provide a Citrus resource injection for type " + type); @@ -184,7 +184,7 @@ private static void injectTestActionRunner(final Object target, final TestAction Class type = field.getType(); if (TestActionRunner.class.isAssignableFrom(type)) { - logger.trace(String.format("Injecting test action runner instance on test class field '%s'", field.getName())); + logger.trace("Injecting test action runner instance on test class field '{}'", field.getName()); ReflectionHelper.setField(field, target, runner); } else { throw new CitrusRuntimeException("Not able to provide a Citrus resource injection for type " + type); @@ -205,7 +205,7 @@ private static void injectGherkinTestActionRunner(final Object target, final Ghe Class type = field.getType(); if (GherkinTestActionRunner.class.isAssignableFrom(type)) { - logger.trace(String.format("Injecting test action runner instance on test class field '%s'", field.getName())); + logger.trace("Injecting test action runner instance on test class field '{}'", field.getName()); ReflectionHelper.setField(field, target, runner); } else { throw new CitrusRuntimeException("Not able to provide a Citrus resource injection for type " + type); diff --git a/core/citrus-base/src/main/java/org/citrusframework/condition/ActionCondition.java b/core/citrus-base/src/main/java/org/citrusframework/condition/ActionCondition.java index fee180ff40..6f7ceff1e5 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/condition/ActionCondition.java +++ b/core/citrus-base/src/main/java/org/citrusframework/condition/ActionCondition.java @@ -16,13 +16,13 @@ package org.citrusframework.condition; -import java.util.Optional; - import org.citrusframework.TestAction; import org.citrusframework.context.TestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Optional; + /** * @since 2.7.6 */ @@ -62,9 +62,10 @@ public boolean isSatisfied(TestContext context) { action.execute(context); } catch (Exception e) { this.caughtException = e; - logger.warn(String.format("Nested action did not perform as expected - %s", Optional.ofNullable(e.getMessage()) - .map(msg -> e.getClass().getName() + ": " + msg) - .orElseGet(() -> e.getClass().getName()))); + logger.warn("Nested action did not perform as expected - {}", + Optional.ofNullable(e.getMessage()) + .map(msg -> e.getClass().getName() + ": " + msg) + .orElseGet(() -> e.getClass().getName())); return false; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/condition/FileCondition.java b/core/citrus-base/src/main/java/org/citrusframework/condition/FileCondition.java index ac2c844f11..65951b8549 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/condition/FileCondition.java +++ b/core/citrus-base/src/main/java/org/citrusframework/condition/FileCondition.java @@ -16,13 +16,13 @@ package org.citrusframework.condition; -import java.io.File; - import org.citrusframework.context.TestContext; import org.citrusframework.util.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; + /** * Tests for the presence of a file and returns true if the file exists * @@ -46,9 +46,7 @@ public FileCondition() { @Override public boolean isSatisfied(TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Checking file path '%s'", file != null ? file.getPath() : filePath)); - } + logger.debug("Checking file path '{}'", file != null ? file.getPath() : filePath); if (file != null) { return file.exists() && file.isFile(); @@ -56,7 +54,7 @@ public boolean isSatisfied(TestContext context) { try { return FileUtils.getFileResource(context.replaceDynamicContentInString(filePath), context).getFile().isFile(); } catch (Exception e) { - logger.warn(String.format("Failed to access file resource '%s'", e.getMessage())); + logger.warn("Failed to access file resource '{}'", e.getMessage()); return false; } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/condition/HttpCondition.java b/core/citrus-base/src/main/java/org/citrusframework/condition/HttpCondition.java index 95be6db182..a252af571b 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/condition/HttpCondition.java +++ b/core/citrus-base/src/main/java/org/citrusframework/condition/HttpCondition.java @@ -16,16 +16,16 @@ package org.citrusframework.condition; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + /** * Tests if a HTTP Endpoint is reachable. The test is successful if the endpoint responds with the expected response * code. By default a HTTP 200 response code is expected. @@ -76,9 +76,7 @@ public String getErrorMessage(TestContext context) { */ private int invokeUrl(TestContext context) { URL contextUrl = getUrl(context); - if (logger.isDebugEnabled()) { - logger.debug(String.format("Probing Http request url '%s'", contextUrl.toExternalForm())); - } + logger.debug("Probing Http request url '{}'", contextUrl.toExternalForm()); int responseCode = -1; @@ -90,7 +88,7 @@ private int invokeUrl(TestContext context) { responseCode = httpURLConnection.getResponseCode(); } catch (IOException e) { - logger.warn(String.format("Could not access Http url '%s' - %s", contextUrl.toExternalForm(), e.getMessage())); + logger.warn("Could not access Http url '{}' - {}", contextUrl.toExternalForm(), e.getMessage()); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); diff --git a/core/citrus-base/src/main/java/org/citrusframework/condition/MessageCondition.java b/core/citrus-base/src/main/java/org/citrusframework/condition/MessageCondition.java index 986762dee5..f9e0d1e228 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/condition/MessageCondition.java +++ b/core/citrus-base/src/main/java/org/citrusframework/condition/MessageCondition.java @@ -22,7 +22,7 @@ * Condition checks whether a message is present in test context message store. Messages are automatically * stored in that store when sending and receiving messages with respective test actions. So this condition * can be used to wait for a message to arrive or being sent out. - * + *

* Message to check is identified by its name in the message store. * * @since 2.6.2 diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/AbstractActionContainer.java b/core/citrus-base/src/main/java/org/citrusframework/container/AbstractActionContainer.java index 1f52b35f7e..4691c02a34 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/AbstractActionContainer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/AbstractActionContainer.java @@ -16,13 +16,6 @@ package org.citrusframework.container; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.citrusframework.AbstractTestContainerBuilder; import org.citrusframework.Completable; import org.citrusframework.TestAction; @@ -32,6 +25,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + /** * Abstract base class for all containers holding several embedded test actions. * @@ -106,10 +106,8 @@ public boolean isDone(TestContext context) { for (TestAction action : new ArrayList<>(executedActions)) { if (action instanceof Completable && !((Completable) action).isDone(context)) { - if (logger.isDebugEnabled()) { - logger.debug(Optional.ofNullable(action.getName()).filter(name -> name.trim().length() > 0) - .orElseGet(() -> action.getClass().getName()) + " not completed yet"); - } + logger.debug("{} not completed yet", Optional.ofNullable(action.getName()).filter(name -> !name.trim().isEmpty()) + .orElseGet(() -> action.getClass().getName())); return false; } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/AbstractSuiteActionContainer.java b/core/citrus-base/src/main/java/org/citrusframework/container/AbstractSuiteActionContainer.java index 9c7265d35b..56b4e3cce9 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/AbstractSuiteActionContainer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/AbstractSuiteActionContainer.java @@ -16,15 +16,15 @@ package org.citrusframework.container; +import org.citrusframework.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.citrusframework.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Abstract suit container actions executed before and after test suite run. Container decides * weather to execute according to given suite name and included test groups if any. @@ -57,29 +57,30 @@ public abstract class AbstractSuiteActionContainer extends AbstractActionContain public boolean shouldExecute(String suiteName, String[] includedGroups) { String baseErrorMessage = "Skip before/after suite container because of %s restriction - do not execute container '%s'"; - if (StringUtils.hasText(suiteName) && - suiteNames != null && !suiteNames.isEmpty() && !suiteNames.contains(suiteName)) { - logger.warn(String.format(baseErrorMessage, "suite name", getName())); + if (StringUtils.hasText(suiteName) + && suiteNames != null && !suiteNames.isEmpty() + && !suiteNames.contains(suiteName)) { + logger.warn("{} suite name {}", baseErrorMessage, getName()); return false; } if (!checkTestGroups(includedGroups)) { - logger.warn(String.format(baseErrorMessage, "test groups", getName())); + logger.warn("{} test groups {}", baseErrorMessage, getName()); return false; } for (Map.Entry envEntry : env.entrySet()) { - if (!System.getenv().containsKey(envEntry.getKey()) || - (StringUtils.hasText(envEntry.getValue()) && !System.getenv().get(envEntry.getKey()).equals(envEntry.getValue()))) { - logger.warn(String.format(baseErrorMessage, "env properties", getName())); + if (!System.getenv().containsKey(envEntry.getKey()) + || (StringUtils.hasText(envEntry.getValue()) && !System.getenv().get(envEntry.getKey()).equals(envEntry.getValue()))) { + logger.warn("{} env properties {}", baseErrorMessage, getName()); return false; } } for (Map.Entry systemProperty : systemProperties.entrySet()) { - if (!System.getProperties().containsKey(systemProperty.getKey()) || - (StringUtils.hasText(systemProperty.getValue()) && !System.getProperties().get(systemProperty.getKey()).equals(systemProperty.getValue()))) { - logger.warn(String.format(baseErrorMessage, "system properties", getName())); + if (!System.getProperties().containsKey(systemProperty.getKey()) + || (StringUtils.hasText(systemProperty.getValue()) && !System.getProperties().get(systemProperty.getKey()).equals(systemProperty.getValue()))) { + logger.warn("{} system properties {}", baseErrorMessage, getName()); return false; } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/AbstractTestBoundaryActionContainer.java b/core/citrus-base/src/main/java/org/citrusframework/container/AbstractTestBoundaryActionContainer.java index b955a04f40..cd59c119ad 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/AbstractTestBoundaryActionContainer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/AbstractTestBoundaryActionContainer.java @@ -16,16 +16,16 @@ package org.citrusframework.container; +import org.citrusframework.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; -import org.citrusframework.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Abstract test action container describes methods to enable/disable container execution based on given test name, package * and test groups. This action container is typically used by before and after test action containers. @@ -64,27 +64,27 @@ public boolean shouldExecute(String testName, String packageName, String[] inclu if (StringUtils.hasText(packageNamePattern)) { if (!Pattern.compile(packageNamePattern).matcher(packageName).matches()) { - logger.warn(String.format(baseErrorMessage, "test package", getName())); + logger.warn("{} test package {}", baseErrorMessage, getName()); return false; } } if (StringUtils.hasText(namePattern)) { if (!Pattern.compile(sanitizePatten(namePattern)).matcher(testName).matches()) { - logger.warn(String.format(baseErrorMessage, "test name", getName())); + logger.warn("{} test name {}", baseErrorMessage, getName()); return false; } } if (!checkTestGroups(includedGroups)) { - logger.warn(String.format(baseErrorMessage, "test groups", getName())); + logger.warn("{} test groups {}", baseErrorMessage, getName()); return false; } for (Map.Entry envEntry : env.entrySet()) { if (!System.getenv().containsKey(envEntry.getKey()) || (StringUtils.hasText(envEntry.getValue()) && !System.getenv().get(envEntry.getKey()).equals(envEntry.getValue()))) { - logger.warn(String.format(baseErrorMessage, "env properties", getName())); + logger.warn("{} env properties {}", baseErrorMessage, getName()); return false; } } @@ -92,7 +92,7 @@ public boolean shouldExecute(String testName, String packageName, String[] inclu for (Map.Entry systemProperty : systemProperties.entrySet()) { if (!System.getProperties().containsKey(systemProperty.getKey()) || (StringUtils.hasText(systemProperty.getValue()) && !System.getProperties().get(systemProperty.getKey()).equals(systemProperty.getValue()))) { - logger.warn(String.format(baseErrorMessage, "system properties", getName())); + logger.warn("{} system properties {}", baseErrorMessage, getName()); return false; } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Assert.java b/core/citrus-base/src/main/java/org/citrusframework/container/Assert.java index 13e93aee68..a4b805ba9f 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Assert.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Assert.java @@ -72,9 +72,7 @@ public Assert(Builder builder) { @Override public void doExecute(TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug("Assert container asserting exceptions of type {}", exception.getSimpleName()); - } + logger.debug("Assert container asserting exceptions of type {}", exception.getSimpleName()); try { executeAction(this.action.build(), context); diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Catch.java b/core/citrus-base/src/main/java/org/citrusframework/container/Catch.java index 2730af0cee..30b7392f61 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Catch.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Catch.java @@ -45,16 +45,14 @@ public Catch(Builder builder) { @Override public void doExecute(TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug("Catch container catching exceptions of type " + exception); - } + logger.debug("Catch container catching exceptions of type {}", exception); for (TestActionBuilder actionBuilder: actions) { try { executeAction(actionBuilder.build(), context); } catch (Exception e) { if (exception != null && exception.equals(e.getClass().getName())) { - logger.info("Caught exception " + e.getClass() + ": " + e.getLocalizedMessage()); + logger.info("Caught exception {}: {}", e.getClass(), e.getLocalizedMessage()); continue; } throw new CitrusRuntimeException(e); diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Iterate.java b/core/citrus-base/src/main/java/org/citrusframework/container/Iterate.java index f70505ce47..c71d452244 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Iterate.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Iterate.java @@ -22,7 +22,7 @@ /** * Class executes nested test actions in loops. Iteration continues as long * as looping condition evaluates to true. - * + *

* Each loop an index variable is incremented. The index variable is accessible inside the nested * test actions as normal test variable. Iteration starts with index=1 and increments with a * default step=1. diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/RepeatOnErrorUntilTrue.java b/core/citrus-base/src/main/java/org/citrusframework/container/RepeatOnErrorUntilTrue.java index 1f9a34e065..471fc64c03 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/RepeatOnErrorUntilTrue.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/RepeatOnErrorUntilTrue.java @@ -25,10 +25,10 @@ /** * Looping test container iterating the nested test actions in case an error occurred in one * of them. Iteration continues until a aborting condition evaluates to true. - * + *

* Number of iterations is kept in a index variable. The nested test actions can access this variable * as normal test variable. - * + *

* Between the iterations container can sleep automatically a given amount of time. * */ @@ -60,8 +60,7 @@ public void executeIteration(TestContext context) { } catch (CitrusRuntimeException e) { exception = e; - logger.info("Caught exception of type " + e.getClass().getName() + " '" + - e.getMessage() + "' - performing retry #" + index); + logger.info("Caught exception of type {} '{}' - performing retry #{}", e.getClass().getName(), e.getMessage(), index); doAutoSleep(); index++; @@ -69,7 +68,7 @@ public void executeIteration(TestContext context) { } if (exception != null) { - logger.info("All retries failed - raising exception " + exception.getClass().getName()); + logger.info("All retries failed - raising exception {}", exception.getClass().getName()); throw exception; } } @@ -79,7 +78,7 @@ public void executeIteration(TestContext context) { */ private void doAutoSleep() { if (autoSleep > 0) { - logger.info("Sleeping " + autoSleep + " milliseconds"); + logger.info("Sleeping {} milliseconds", autoSleep); try { Thread.sleep(autoSleep); @@ -87,7 +86,7 @@ private void doAutoSleep() { logger.error("Error during doc generation", e); } - logger.info("Returning after " + autoSleep + " milliseconds"); + logger.info("Returning after {} milliseconds", autoSleep); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/RepeatUntilTrue.java b/core/citrus-base/src/main/java/org/citrusframework/container/RepeatUntilTrue.java index b28f7187d3..8ba4089a87 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/RepeatUntilTrue.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/RepeatUntilTrue.java @@ -22,7 +22,7 @@ /** * Typical implementation of repeat iteration loop. Nested test actions are executed until * aborting condition evaluates to true. - * + *

* Index is incremented each iteration and stored as test variable accessible in the nested test actions * as normal variable. Index starts with 1 by default. * diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterSuite.java b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterSuite.java index 55a95ad1bf..b60c1d6c52 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterSuite.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterSuite.java @@ -41,7 +41,7 @@ public void doExecute(TestContext context) { logger.info("Entering after suite block"); if (logger.isDebugEnabled()) { - logger.debug("Executing " + actions.size() + " actions after suite"); + logger.debug("Executing {} actions after suite", actions.size()); logger.debug(""); } @@ -51,7 +51,7 @@ public void doExecute(TestContext context) { /* Executing test action and validate its success */ action.execute(context); } catch (Exception e) { - logger.error("After suite action failed " + action.getName() + "Nested exception is: ", e); + logger.error("After suite action failed {}Nested exception is: ", action.getName(), e); logger.error("Continue after suite actions"); success = false; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterTest.java b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterTest.java index 17349516eb..4d14b10678 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterTest.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceAfterTest.java @@ -42,7 +42,7 @@ public void doExecute(TestContext context) { logger.info("Entering after test block"); if (logger.isDebugEnabled()) { - logger.debug("Executing " + actions.size() + " actions after test"); + logger.debug("Executing {} actions after test", actions.size()); logger.debug(""); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeSuite.java b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeSuite.java index c99a064e30..7e97a314a5 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeSuite.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeSuite.java @@ -39,7 +39,7 @@ public void doExecute(TestContext context) { logger.info("Entering before suite block"); if (logger.isDebugEnabled()) { - logger.debug("Executing " + actions.size() + " actions before suite"); + logger.debug("Executing {} actions before suite", actions.size()); logger.debug(""); } @@ -49,7 +49,7 @@ public void doExecute(TestContext context) { /* Executing test action and validate its success */ action.execute(context); } catch (Exception e) { - logger.error("Task failed " + action.getName() + "Nested exception is: ", e); + logger.error("Task failed {}Nested exception is: ", action.getName(), e); throw new CitrusRuntimeException(e); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeTest.java b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeTest.java index 3cc9afd8cf..172f88d886 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeTest.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/SequenceBeforeTest.java @@ -42,7 +42,7 @@ public void doExecute(TestContext context) { logger.info("Entering before test block"); if (logger.isDebugEnabled()) { - logger.debug("Executing " + actions.size() + " actions before test"); + logger.debug("Executing {} actions before test", actions.size()); logger.debug(""); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Template.java b/core/citrus-base/src/main/java/org/citrusframework/container/Template.java index 4c05685ac3..113f456143 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Template.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Template.java @@ -16,15 +16,6 @@ package org.citrusframework.container; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.stream.Collectors; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.TestAction; import org.citrusframework.TestActionBuilder; @@ -42,15 +33,24 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; + /** * This class represents a previously defined block of test actions. Test cases can call * templates and reuse their functionality. - * + *

* Templates operate on test variables. While calling, the template caller can set these * variables as parameters. - * + *

* Nested test actions are executed in sequence. - * + *

* The template execution may affect existing variable values in the calling test case. So * variables may have different values in the test case after template execution. Therefore * users can create a local test context by setting globalContext to false. Templates then will @@ -91,9 +91,7 @@ public Template(AbstractTemplateBuilder builder) { @Override public void doExecute(TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug("Executing template '" + getName() + "' with " + actions.size() + " embedded actions"); - } + logger.debug("Executing template '{}' with {} embedded actions", getName(), actions.size()); TestContext innerContext; @@ -113,9 +111,7 @@ public void doExecute(TestContext context) { paramValue = FunctionUtils.resolveFunction(paramValue, context); } - if (logger.isDebugEnabled()) { - logger.debug("Setting parameter for template " + param + "=" + paramValue); - } + logger.debug("Setting parameter for template {}={}", param, paramValue); innerContext.setVariable(param, paramValue); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/TemplateLoader.java b/core/citrus-base/src/main/java/org/citrusframework/container/TemplateLoader.java index 0f0dc251e3..3add3c2a57 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/TemplateLoader.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/TemplateLoader.java @@ -16,10 +16,6 @@ package org.citrusframework.container; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.functions.Function; import org.citrusframework.spi.ReferenceResolverAware; @@ -28,10 +24,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + public interface TemplateLoader extends ReferenceResolverAware { /** Logger */ - Logger logger = LoggerFactory.getLogger(Function.class); + Logger logger = LoggerFactory.getLogger(TemplateLoader.class); /** Function resource lookup path */ String RESOURCE_PATH = "META-INF/citrus/template/loader"; @@ -53,7 +53,7 @@ static Optional lookup(String name) { TemplateLoader instance = TYPE_RESOLVER.resolve(name); return Optional.of(instance); } catch (CitrusRuntimeException e) { - logger.warn(String.format("Failed to resolve template loader from resource '%s/%s'", RESOURCE_PATH, name)); + logger.warn("Failed to resolve template loader from resource '{}/{}'", RESOURCE_PATH, name); } return Optional.empty(); diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java b/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java index 59ea25bad5..c9b768c807 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java @@ -87,13 +87,13 @@ public void run() { try { indexCount++; updateIndexCountInTestContext(context); - logger.debug(String.format("Timer event fired #%s - executing nested actions", indexCount)); + logger.debug("Timer event fired #{} - executing nested actions", indexCount); for (TestActionBuilder actionBuilder : actions) { executeAction(actionBuilder.build(), context); } if (indexCount >= repeatCount) { - logger.debug(String.format("Timer complete: %s iterations reached", repeatCount)); + logger.debug("Timer complete: {} iterations reached", repeatCount); stopTimer(); } } catch (Exception e) { @@ -111,7 +111,7 @@ private void handleException(Exception e) { } else { timerException = new CitrusRuntimeException(e); } - logger.error(String.format("Timer stopped as a result of nested action error (%s)", e.getMessage())); + logger.error("Timer stopped as a result of nested action error ({})", e.getMessage()); stopTimer(); if (fork) { diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java b/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java index b02056d8f9..c4b17baa0e 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java @@ -83,9 +83,7 @@ public void doExecute(final TestContext context) { while (timeLeft > 0) { timeLeft -= intervalMs; - if (logger.isDebugEnabled()) { - logger.debug(String.format("Waiting for condition %s", condition.getName())); - } + logger.debug("Waiting for condition {}", condition.getName()); var executor = newSingleThreadExecutor(); long checkStartTime = System.currentTimeMillis(); diff --git a/core/citrus-base/src/main/java/org/citrusframework/endpoint/AbstractEndpointComponent.java b/core/citrus-base/src/main/java/org/citrusframework/endpoint/AbstractEndpointComponent.java index 1fe8f46fe6..b4c9b5b3e9 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/endpoint/AbstractEndpointComponent.java +++ b/core/citrus-base/src/main/java/org/citrusframework/endpoint/AbstractEndpointComponent.java @@ -16,6 +16,13 @@ package org.citrusframework.endpoint; +import org.citrusframework.context.TestContext; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.spi.ReferenceResolverAware; +import org.citrusframework.util.ReflectionHelper; +import org.citrusframework.util.StringUtils; +import org.citrusframework.util.TypeConversionUtils; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URI; @@ -26,17 +33,10 @@ import java.util.Map; import java.util.StringTokenizer; -import org.citrusframework.context.TestContext; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.citrusframework.spi.ReferenceResolverAware; -import org.citrusframework.util.ReflectionHelper; -import org.citrusframework.util.TypeConversionUtils; -import org.citrusframework.util.StringUtils; - /** * Default endpoint component reads component name from endpoint uri and parses parameters from uri using * the HTTP uri pattern. - * + *

* http://localhost:8080?param1=value1¶m2=value2¶m3=value3 * jms:queue.name?connectionFactory=specialConnectionFactory * soap:localhost:8080?soapAction=sayHello @@ -185,16 +185,13 @@ protected String getParameterString(Map parameters, Field field = ReflectionHelper.findField(endpointConfigurationType, parameterEntry.getKey()); if (field == null) { - if (paramString.length() == 0) { + if (paramString.isEmpty()) { paramString.append("?").append(parameterEntry.getKey()); - if (parameterEntry.getValue() != null) { - paramString.append("=").append(parameterEntry.getValue()); - } } else { paramString.append("&").append(parameterEntry.getKey()); - if (parameterEntry.getValue() != null) { - paramString.append("=").append(parameterEntry.getValue()); - } + } + if (parameterEntry.getValue() != null) { + paramString.append("=").append(parameterEntry.getValue()); } } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectConsumer.java b/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectConsumer.java index 0f6ccd4468..78237afb6b 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectConsumer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectConsumer.java @@ -24,9 +24,9 @@ import org.citrusframework.message.MessageSelector; import org.citrusframework.message.selector.DelegatingMessageSelector; import org.citrusframework.messaging.AbstractSelectiveMessageConsumer; +import org.citrusframework.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.citrusframework.util.StringUtils; public class DirectConsumer extends AbstractSelectiveMessageConsumer { @@ -57,9 +57,7 @@ public Message receive(String selector, TestContext context, long timeout) { destinationQueueName = getDestinationQueueName(); } - if (logger.isDebugEnabled()) { - logger.debug(String.format("Receiving message from queue: '%s'", destinationQueueName)); - } + logger.debug("Receiving message from queue: '{}'", destinationQueueName); Message message; if (StringUtils.hasText(selector)) { @@ -82,7 +80,7 @@ public Message receive(String selector, TestContext context, long timeout) { throw new MessageTimeoutException(timeout, destinationQueueName); } - logger.info(String.format("Received message from queue: '%s'", destinationQueueName)); + logger.info("Received message from queue: '{}'", destinationQueueName); return message; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncConsumer.java b/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncConsumer.java index 5b25d7597a..26308b3850 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncConsumer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncConsumer.java @@ -67,12 +67,12 @@ public void send(Message message, TestContext context) { ObjectHelper.assertNotNull(replyQueue, "Failed to find reply channel for message correlation key: " + correlationKey); if (logger.isDebugEnabled()) { - logger.debug("Sending message to reply channel: '" + replyQueue + "'"); - logger.debug("Message to send is:\n" + message.toString()); + logger.debug("Sending message to reply channel: '{}'", replyQueue); + logger.debug("Message to send is:\n{}", message); } replyQueue.send(message); - logger.info("Message was sent to reply channel: '" + replyQueue + "'"); + logger.info("Message was sent to reply channel: '{}'", replyQueue); } /** @@ -94,8 +94,7 @@ public void saveReplyMessageQueue(Message receivedMessage, TestContext context) correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context); correlationManager.store(correlationKey, replyQueue); } else { - logger.warn("Unable to retrieve reply message channel for message \n" + - receivedMessage + "\n - no reply channel found in message headers!"); + logger.warn("Unable to retrieve reply message channel for message \n{}\n - no reply channel found in message headers!", receivedMessage); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncProducer.java b/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncProducer.java index c5788fdb67..9dad1395e7 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncProducer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/endpoint/direct/DirectSyncProducer.java @@ -16,8 +16,6 @@ package org.citrusframework.endpoint.direct; -import java.util.UUID; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.MessageTimeoutException; import org.citrusframework.exceptions.ReplyMessageTimeoutException; @@ -30,6 +28,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.UUID; + public class DirectSyncProducer extends DirectProducer implements ReplyConsumer { /** Logger */ private static final Logger logger = LoggerFactory.getLogger(DirectSyncProducer.class); @@ -62,11 +62,11 @@ public void send(Message message, TestContext context) { String destinationQueueName = getDestinationQueueName(); if (logger.isDebugEnabled()) { - logger.debug("Sending message to queue: '" + destinationQueueName + "'"); - logger.debug("Message to send is:\n" + message.toString()); + logger.debug("Sending message to queue: '{}'", destinationQueueName); + logger.debug("Message to send is:\n{}", message.toString()); } - logger.info("Message was sent to queue: '" + destinationQueueName + "'"); + logger.info("Message was sent to queue: '{}'", destinationQueueName); MessageQueue replyQueue = getReplyQueue(message, context); getDestinationQueue(context).send(message); @@ -89,7 +89,7 @@ public void send(Message message, TestContext context) { */ private MessageQueue getReplyQueue(Message message, TestContext context) { if (message.getHeader(DirectMessageHeaders.REPLY_QUEUE) == null) { - MessageQueue temporaryQueue = new DefaultMessageQueue(getName() + "." + UUID.randomUUID().toString()); + MessageQueue temporaryQueue = new DefaultMessageQueue(getName() + "." + UUID.randomUUID()); message.setHeader(DirectMessageHeaders.REPLY_QUEUE, temporaryQueue); return temporaryQueue; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/endpoint/resolver/DynamicEndpointUriResolver.java b/core/citrus-base/src/main/java/org/citrusframework/endpoint/resolver/DynamicEndpointUriResolver.java index 6d2cb8d20c..0b1305590f 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/endpoint/resolver/DynamicEndpointUriResolver.java +++ b/core/citrus-base/src/main/java/org/citrusframework/endpoint/resolver/DynamicEndpointUriResolver.java @@ -16,13 +16,13 @@ package org.citrusframework.endpoint.resolver; -import java.util.Map; -import java.util.StringTokenizer; - import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.message.Message; import org.citrusframework.util.StringUtils; +import java.util.Map; +import java.util.StringTokenizer; + /** * Endpoint uri resolver working on message headers. Resolver is searching for a specific header entry which holds the actual * target endpoint uri. @@ -78,7 +78,7 @@ private String appendRequestPath(String uri, Map headers) { requestUri = requestUri.substring(0, requestUri.length() - 1); } - while (path.startsWith("/") && path.length() > 0) { + while (path.startsWith("/") && !path.isEmpty()) { path = path.length() == 1 ? "" : path.substring(1); } @@ -114,7 +114,7 @@ private String appendQueryParams(String uri, Map headers) { queryParamBuilder.append("&").append(tok.nextToken()); } - return requestUri + queryParamBuilder.toString(); + return requestUri + queryParamBuilder; } /** diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/DefaultFunctionLibrary.java b/core/citrus-base/src/main/java/org/citrusframework/functions/DefaultFunctionLibrary.java index caf65a1d31..593438a0de 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/DefaultFunctionLibrary.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/DefaultFunctionLibrary.java @@ -17,6 +17,7 @@ package org.citrusframework.functions; import org.citrusframework.functions.core.AbsoluteFunction; +import org.citrusframework.functions.core.AdvancedRandomNumberFunction; import org.citrusframework.functions.core.AvgFunction; import org.citrusframework.functions.core.CeilingFunction; import org.citrusframework.functions.core.ChangeDateFunction; @@ -31,7 +32,6 @@ import org.citrusframework.functions.core.LowerCaseFunction; import org.citrusframework.functions.core.MaxFunction; import org.citrusframework.functions.core.MinFunction; -import org.citrusframework.functions.core.AdvancedRandomNumberFunction; import org.citrusframework.functions.core.RandomEnumValueFunction; import org.citrusframework.functions.core.RandomNumberFunction; import org.citrusframework.functions.core.RandomPatternFunction; @@ -46,10 +46,10 @@ import org.citrusframework.functions.core.SumFunction; import org.citrusframework.functions.core.SystemPropertyFunction; import org.citrusframework.functions.core.TranslateFunction; +import org.citrusframework.functions.core.UnixTimestampFunction; import org.citrusframework.functions.core.UpperCaseFunction; import org.citrusframework.functions.core.UrlDecodeFunction; import org.citrusframework.functions.core.UrlEncodeFunction; -import org.citrusframework.functions.core.UnixTimestampFunction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -108,9 +108,7 @@ public DefaultFunctionLibrary() { private void lookupFunctions() { Function.lookup().forEach((k, m) -> { getMembers().put(k, m); - if (logger.isDebugEnabled()) { - logger.debug(String.format("Register function '%s' as %s", k, m.getClass())); - } + logger.debug("Register function '{}' as {}", k, m.getClass()); }); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/AdvancedRandomNumberFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/AdvancedRandomNumberFunction.java index 6cde8506c4..9a01d65dea 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/AdvancedRandomNumberFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/AdvancedRandomNumberFunction.java @@ -16,16 +16,17 @@ package org.citrusframework.functions.core; -import static java.lang.String.format; +import org.citrusframework.context.TestContext; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.exceptions.InvalidFunctionUsageException; +import org.citrusframework.functions.Function; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import org.citrusframework.context.TestContext; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.citrusframework.exceptions.InvalidFunctionUsageException; -import org.citrusframework.functions.Function; + +import static java.lang.String.format; /** * A function for generating random double values with specified decimal places and range. This @@ -64,20 +65,15 @@ public String execute(List parameterList, TestContext context) { "Decimal places must be a non-negative integer value."); } - BigDecimal minValue = getParameter(parameterList, 1, BigDecimal.class, BigDecimal::new, - DEFAULT_MIN_VALUE); - BigDecimal maxValue = getParameter(parameterList, 2, BigDecimal.class, BigDecimal::new, - DEFAULT_MAX_VALUE); + BigDecimal minValue = getParameter(parameterList, 1, BigDecimal.class, BigDecimal::new, DEFAULT_MIN_VALUE); + BigDecimal maxValue = getParameter(parameterList, 2, BigDecimal.class, BigDecimal::new, DEFAULT_MAX_VALUE); if (minValue.compareTo(maxValue) > 0) { throw new InvalidFunctionUsageException("Min value must be less than max value."); } - boolean excludeMin = getParameter(parameterList, 3, Boolean.class, Boolean::parseBoolean, - false); - boolean excludeMax = getParameter(parameterList, 4, Boolean.class, Boolean::parseBoolean, - false); - BigDecimal multiple = getParameter(parameterList, 5, BigDecimal.class, BigDecimal::new, - null); + boolean excludeMin = getParameter(parameterList, 3, Boolean.class, Boolean::parseBoolean, false); + boolean excludeMax = getParameter(parameterList, 4, Boolean.class, Boolean::parseBoolean, false); + BigDecimal multiple = getParameter(parameterList, 5, BigDecimal.class, BigDecimal::new, null); return getRandomNumber(decimalPlaces, minValue, maxValue, excludeMin, excludeMax, multiple); } @@ -96,27 +92,27 @@ private T parseParameter(int index, String text, Class type, java.util.function.Function parseFunction) { T value; try { - value = parseFunction.apply(text); if (value == null) { throw new CitrusRuntimeException( - "Text '%s' could not be parsed to '%s'. Resulting value is null".formatted(text, - type.getSimpleName())); + "Text '%s' could not be parsed to '%s'. Resulting value is null".formatted(text, type.getSimpleName())); } return value; } catch (Exception e) { throw new InvalidFunctionUsageException( - format("Invalid parameter at index %d. %s must be parsable to %s.", index, text, - type.getSimpleName())); + format("Invalid parameter at index %d. %s must be parsable to %s.", index, text, type.getSimpleName())); } } /** * Static number generator method. */ - private String getRandomNumber(int decimalPlaces, BigDecimal minValue, BigDecimal maxValue, - boolean excludeMin, boolean excludeMax, BigDecimal multiple) { - + private String getRandomNumber(int decimalPlaces, + BigDecimal minValue, + BigDecimal maxValue, + boolean excludeMin, + boolean excludeMax, + BigDecimal multiple) { minValue = excludeMin ? incrementToExclude(minValue) : minValue; maxValue = excludeMax ? decrementToExclude(maxValue) : maxValue; @@ -145,20 +141,18 @@ private String getRandomNumber(int decimalPlaces, BigDecimal minValue, BigDecima BigDecimal createRandomValue(BigDecimal minValue, BigDecimal range, double random) { BigDecimal offset = range.multiply(BigDecimal.valueOf(random)); BigDecimal value = minValue.add(offset); - return value.compareTo(BigDecimal.valueOf(Double.MAX_VALUE)) > 0 ? BigDecimal.valueOf( - Double.MAX_VALUE) : value; + return value.compareTo(BigDecimal.valueOf(Double.MAX_VALUE)) > 0 ? BigDecimal.valueOf(Double.MAX_VALUE) + : value; } private BigDecimal largestMultipleOf(BigDecimal highest, BigDecimal multipleOf) { - RoundingMode roundingMode = - highest.compareTo(BigDecimal.ZERO) < 0 ? RoundingMode.UP : RoundingMode.DOWN; + RoundingMode roundingMode = highest.compareTo(BigDecimal.ZERO) < 0 ? RoundingMode.UP : RoundingMode.DOWN; BigDecimal factor = highest.divide(multipleOf, 0, roundingMode); return multipleOf.multiply(factor); } private BigDecimal lowestMultipleOf(BigDecimal lowest, BigDecimal multipleOf) { - RoundingMode roundingMode = - lowest.compareTo(java.math.BigDecimal.ZERO) < 0 ? RoundingMode.DOWN : RoundingMode.UP; + RoundingMode roundingMode = lowest.compareTo(java.math.BigDecimal.ZERO) < 0 ? RoundingMode.DOWN : RoundingMode.UP; BigDecimal factor = lowest.divide(multipleOf, 0, roundingMode); return multipleOf.multiply(factor); } @@ -174,8 +168,7 @@ private BigDecimal decrementToExclude(BigDecimal val) { } private BigDecimal determineIncrement(BigDecimal number) { - return java.math.BigDecimal.valueOf( - 1.0d / (Math.pow(10d, findLeastSignificantDecimalPlace(number)))); + return BigDecimal.valueOf(.0d / (Math.pow(10d, findLeastSignificantDecimalPlace(number)))); } private int findLeastSignificantDecimalPlace(BigDecimal number) { @@ -190,12 +183,9 @@ private int findLeastSignificantDecimalPlace(BigDecimal number) { return parts[1].length(); } - private BigDecimal createMultipleOf( - BigDecimal minimum, + private BigDecimal createMultipleOf(BigDecimal minimum, BigDecimal maximum, - BigDecimal multipleOf - ) { - + BigDecimal multipleOf) { BigDecimal lowestMultiple = lowestMultipleOf(minimum, multipleOf); BigDecimal largestMultiple = largestMultipleOf(maximum, multipleOf); @@ -223,5 +213,4 @@ private BigDecimal createMultipleOf( return randomMultiple; } - -} \ No newline at end of file +} diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/DecodeBase64Function.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/DecodeBase64Function.java index 35fc0d6c96..2c7c074c7e 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/DecodeBase64Function.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/DecodeBase64Function.java @@ -16,15 +16,15 @@ package org.citrusframework.functions.core; -import java.io.UnsupportedEncodingException; -import java.util.List; - import org.apache.commons.codec.binary.Base64; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.citrusframework.functions.Function; +import java.io.UnsupportedEncodingException; +import java.util.List; + /** * Decodes base64 binary data to a character sequence. * @@ -33,7 +33,7 @@ public class DecodeBase64Function implements Function { @Override public String execute(List parameterList, TestContext context) { - if (parameterList == null || parameterList.size() < 1) { + if (parameterList == null || parameterList.isEmpty()) { throw new InvalidFunctionUsageException("Invalid function parameter usage! Missing parameters!"); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/EncodeBase64Function.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/EncodeBase64Function.java index 2465903570..494c4b7b64 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/EncodeBase64Function.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/EncodeBase64Function.java @@ -16,15 +16,15 @@ package org.citrusframework.functions.core; -import java.io.UnsupportedEncodingException; -import java.util.List; - import org.apache.commons.codec.binary.Base64; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.citrusframework.functions.Function; +import java.io.UnsupportedEncodingException; +import java.util.List; + /** * Encodes a character sequence to base64 binary using given charset. * @@ -33,7 +33,7 @@ public class EncodeBase64Function implements Function { @Override public String execute(List parameterList, TestContext context) { - if (parameterList == null || parameterList.size() < 1) { + if (parameterList == null || parameterList.isEmpty()) { throw new InvalidFunctionUsageException("Invalid function parameter usage! Missing parameters!"); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomNumberFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomNumberFunction.java index a3fa489e5a..aacd485b9d 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomNumberFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomNumberFunction.java @@ -16,13 +16,13 @@ package org.citrusframework.functions.core; -import java.util.List; -import java.util.Random; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.citrusframework.functions.Function; +import java.util.List; +import java.util.Random; + import static java.lang.Boolean.parseBoolean; import static java.lang.Integer.parseInt; @@ -113,7 +113,7 @@ private static String removeLeadingZeros(String generated) { } } - if (builder.length() == 0) { + if (builder.isEmpty()) { // very unlikely to happen, ensures that empty string is not returned builder.append('0'); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomPatternFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomPatternFunction.java index 377b2d5fe7..7fd8ec7b94 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomPatternFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomPatternFunction.java @@ -16,14 +16,15 @@ package org.citrusframework.functions.core; -import static org.citrusframework.util.StringUtils.hasText; - import com.mifmif.common.regex.Generex; -import java.util.List; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.citrusframework.functions.Function; +import java.util.List; + +import static org.citrusframework.util.StringUtils.hasText; + /** * The RandomPatternFunction generates a random string based on a provided regular expression pattern. * It uses the Generex library to generate the random string. @@ -34,9 +35,7 @@ */ public class RandomPatternFunction implements Function { - public String execute(List parameterList, TestContext context) { - if (parameterList == null) { throw new InvalidFunctionUsageException("Function parameters must not be null."); } @@ -52,8 +51,6 @@ public String execute(List parameterList, TestContext context) { "Function called with a pattern, the algorithm is not able to create a string for."); } - Generex generex = new Generex(pattern); - return generex.random(); + return new Generex(pattern).random(); } - -} \ No newline at end of file +} diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomStringFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomStringFunction.java index 326471a2b5..75064ae56b 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomStringFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/RandomStringFunction.java @@ -33,6 +33,7 @@ * */ public class RandomStringFunction implements Function { + private static final Random generator = new Random(System.currentTimeMillis()); private static final char[] ALPHABET_UPPER = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/ReadFileResourceFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/ReadFileResourceFunction.java index 710600b8c1..2d6a554039 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/ReadFileResourceFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/ReadFileResourceFunction.java @@ -16,9 +16,6 @@ package org.citrusframework.functions.core; -import java.io.IOException; -import java.util.List; - import org.apache.commons.codec.binary.Base64; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; @@ -26,12 +23,15 @@ import org.citrusframework.functions.Function; import org.citrusframework.util.FileUtils; +import java.io.IOException; +import java.util.List; + /** * Function reads file from given file path and returns the complete file content as function result. * File content is automatically parsed for test variables. - * + *

* File path can also have test variables as part of the file name or path. - * + *

* The function accepts the following parameters: * *

    diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/SubstringFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/SubstringFunction.java index a5f23b5973..f6270f56cc 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/SubstringFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/SubstringFunction.java @@ -16,18 +16,18 @@ package org.citrusframework.functions.core; -import java.util.List; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.citrusframework.functions.Function; +import java.util.List; + import static java.lang.Integer.parseInt; import static org.citrusframework.util.StringUtils.hasText; /** * Function implements simple substring functionality. - * + *

    * Function requires at least a target string and a beginIndex as function parameters. A * optional endIndex may be given as function parameter, too. The parameter usage looks * like this: substring(targetString, beginIndex, [endIndex]). diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlDecodeFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlDecodeFunction.java index 0f3abd5c5c..13bb58756c 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlDecodeFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlDecodeFunction.java @@ -16,15 +16,15 @@ package org.citrusframework.functions.core; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.List; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.citrusframework.functions.Function; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.List; + /** * Decodes URL encoded string to a character sequence. * @@ -33,7 +33,7 @@ public class UrlDecodeFunction implements Function { @Override public String execute(List parameterList, TestContext context) { - if (parameterList == null || parameterList.size() < 1) { + if (parameterList == null || parameterList.isEmpty()) { throw new InvalidFunctionUsageException("Invalid function parameter usage! Missing parameters!"); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlEncodeFunction.java b/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlEncodeFunction.java index 293cebb0e6..aad80ba6b3 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlEncodeFunction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/functions/core/UrlEncodeFunction.java @@ -16,15 +16,15 @@ package org.citrusframework.functions.core; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.List; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.citrusframework.functions.Function; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.List; + /** * Encodes a character sequence to URL encoded string using given charset. * @@ -33,7 +33,7 @@ public class UrlEncodeFunction implements Function { @Override public String execute(List parameterList, TestContext context) { - if (parameterList == null || parameterList.size() < 1) { + if (parameterList == null || parameterList.isEmpty()) { throw new InvalidFunctionUsageException("Invalid function parameter usage! Missing parameters!"); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/log/DefaultLogModifier.java b/core/citrus-base/src/main/java/org/citrusframework/log/DefaultLogModifier.java index d99d2fd5ca..d14fc2c58e 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/log/DefaultLogModifier.java +++ b/core/citrus-base/src/main/java/org/citrusframework/log/DefaultLogModifier.java @@ -16,12 +16,12 @@ package org.citrusframework.log; +import org.citrusframework.CitrusSettings; + import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.citrusframework.CitrusSettings; - /** * Default modifier implementation uses regular expressions to mask logger output. * Regular expressions match on default keywords. @@ -44,7 +44,7 @@ public class DefaultLogModifier implements LogMessageModifier { @Override public String mask(String source) { - if (!CitrusSettings.isLogModifierEnabled() || source == null || source.length() == 0) { + if (!CitrusSettings.isLogModifierEnabled() || source == null || source.isEmpty()) { return source; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/main/scan/ClassPathTestScanner.java b/core/citrus-base/src/main/java/org/citrusframework/main/scan/ClassPathTestScanner.java index 2bccded319..f6bc7fc907 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/main/scan/ClassPathTestScanner.java +++ b/core/citrus-base/src/main/java/org/citrusframework/main/scan/ClassPathTestScanner.java @@ -16,6 +16,14 @@ package org.citrusframework.main.scan; +import org.citrusframework.TestClass; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.spi.ClasspathResourceResolver; +import org.citrusframework.util.FileUtils; +import org.citrusframework.util.ReflectionHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.lang.annotation.Annotation; import java.nio.file.Path; @@ -25,14 +33,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; -import org.citrusframework.TestClass; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.citrusframework.spi.ClasspathResourceResolver; -import org.citrusframework.util.FileUtils; -import org.citrusframework.util.ReflectionHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @since 2.7.4 */ @@ -97,7 +97,7 @@ protected boolean isIncluded(String className) { }); return hasTestMethod.get(); } catch (NoClassDefFoundError | ClassNotFoundException e) { - logger.warn("Unable to access class: " + className); + logger.warn("Unable to access class: {}", className); return false; } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessage.java b/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessage.java index 0b56ce8c7c..cdb38f5ee0 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessage.java +++ b/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessage.java @@ -67,7 +67,6 @@ public DefaultMessage() { * @param message */ public DefaultMessage(Message message) { - this(message.getPayload(), message.getHeaders()); this.setName(message.getName()); diff --git a/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessageQueue.java b/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessageQueue.java index 607990f568..091d60ea13 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessageQueue.java +++ b/core/citrus-base/src/main/java/org/citrusframework/message/DefaultMessageQueue.java @@ -15,12 +15,12 @@ */ package org.citrusframework.message; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + /** * Default message queue implementation. Holds queued messages in memory and adds selective consumption of messages * according to a message selector implementation. @@ -76,8 +76,7 @@ public Message receive(MessageSelector selector, long timeout) { timeLeft -= pollingInterval; if (RETRY_LOG.isDebugEnabled()) { - RETRY_LOG.debug("No message received with message selector - retrying in " + - (timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft) + "ms"); + RETRY_LOG.debug("No message received with message selector - retrying in {}ms", timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft); } try { @@ -99,11 +98,9 @@ public void purge(MessageSelector selector) { Message message = (Message) o; if (selector.accept(message)) { if (this.queue.remove(message)) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Purged message '%s' from in memory queue", message.getId())); - } + logger.debug("Purged message '{}' from in memory queue", message.getId()); } else { - logger.warn(String.format("Failed to purge message '%s' from in memory queue", message.getId())); + logger.warn("Failed to purge message '{}' from in memory queue", message.getId()); } } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/message/ZipMessage.java b/core/citrus-base/src/main/java/org/citrusframework/message/ZipMessage.java index f2a1ac6f31..f63361d4dc 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/message/ZipMessage.java +++ b/core/citrus-base/src/main/java/org/citrusframework/message/ZipMessage.java @@ -16,6 +16,13 @@ package org.citrusframework.message; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.spi.Resource; +import org.citrusframework.util.FileUtils; +import org.citrusframework.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -26,13 +33,6 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.citrusframework.spi.Resource; -import org.citrusframework.util.FileUtils; -import org.citrusframework.util.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @since 2.7.5 */ @@ -139,7 +139,7 @@ public ZipMessage addEntry(Entry entry) { private void addToZip(String path, Entry entry, ZipOutputStream zos) throws IOException { String name = (path.endsWith("/") ? path : path + "/") + entry.getName(); if (entry.isDirectory()) { - logger.debug("Adding directory to zip: " + name); + logger.debug("Adding directory to zip: {}", name); zos.putNextEntry(new ZipEntry(name.endsWith("/") ? name : name + "/")); for (Entry child : entry.getEntries()) { @@ -151,7 +151,7 @@ private void addToZip(String path, Entry entry, ZipOutputStream zos) throws IOEx } zos.closeEntry(); } else { - logger.debug("Adding file to zip: " + name); + logger.debug("Adding file to zip: {}", name); zos.putNextEntry(new ZipEntry(name)); zos.write(entry.getContent()); diff --git a/core/citrus-base/src/main/java/org/citrusframework/message/correlation/DefaultCorrelationManager.java b/core/citrus-base/src/main/java/org/citrusframework/message/correlation/DefaultCorrelationManager.java index ffea23f0a1..29773dc60d 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/message/correlation/DefaultCorrelationManager.java +++ b/core/citrus-base/src/main/java/org/citrusframework/message/correlation/DefaultCorrelationManager.java @@ -37,18 +37,13 @@ public class DefaultCorrelationManager implements CorrelationManager { @Override public void saveCorrelationKey(String correlationKeyName, String correlationKey, TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Saving correlation key for '%s'", correlationKeyName)); - } - + logger.debug("Saving correlation key for '{}'", correlationKeyName); context.setVariable(correlationKeyName, correlationKey); } @Override public String getCorrelationKey(String correlationKeyName, TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Get correlation key for '%s'", correlationKeyName)); - } + logger.debug("Get correlation key for '{}'", correlationKeyName); if (context.getVariables().containsKey(correlationKeyName)) { return context.getVariable(correlationKeyName); @@ -60,23 +55,18 @@ public String getCorrelationKey(String correlationKeyName, TestContext context) @Override public void store(String correlationKey, T object) { if (object == null) { - logger.warn(String.format("Ignore correlated null object for '%s'", correlationKey)); + logger.warn("Ignore correlated null object for '{}'", correlationKey); return; } - if (logger.isDebugEnabled()) { - logger.debug(String.format("Saving correlated object for '%s'", correlationKey)); - } + logger.debug("Saving correlated object for '{}'", correlationKey); objectStore.add(correlationKey, object); } @Override public T find(String correlationKey, long timeout) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Finding correlated object for '%s'", correlationKey)); - } - + logger.debug("Finding correlated object for '{}'", correlationKey); return objectStore.remove(correlationKey); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/message/correlation/PollingCorrelationManager.java b/core/citrus-base/src/main/java/org/citrusframework/message/correlation/PollingCorrelationManager.java index 4c445b7c1d..991d9bf6c6 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/message/correlation/PollingCorrelationManager.java +++ b/core/citrus-base/src/main/java/org/citrusframework/message/correlation/PollingCorrelationManager.java @@ -62,9 +62,7 @@ public T find(String correlationKey) { @Override public String getCorrelationKey(String correlationKeyName, TestContext context) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Get correlation key for '%s'", correlationKeyName)); - } + logger.debug("Get correlation key for '{}'", correlationKeyName); String correlationKey = null; if (context.getVariables().containsKey(correlationKeyName)) { @@ -77,7 +75,7 @@ public String getCorrelationKey(String correlationKeyName, TestContext context) timeLeft -= pollingInterval; if (RETRY_LOG.isDebugEnabled()) { - RETRY_LOG.debug("Correlation key not available yet - retrying in " + (timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft) + "ms"); + RETRY_LOG.debug("Correlation key not available yet - retrying in {}ms", timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft); } try { @@ -109,7 +107,7 @@ public T find(String correlationKey, long timeout) { timeLeft -= pollingInterval; if (RETRY_LOG.isDebugEnabled()) { - RETRY_LOG.debug(retryLogMessage + " - retrying in " + (timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft) + "ms"); + RETRY_LOG.debug("{} - retrying in {}ms", retryLogMessage, timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft); } try { diff --git a/core/citrus-base/src/main/java/org/citrusframework/report/AbstractOutputFileReporter.java b/core/citrus-base/src/main/java/org/citrusframework/report/AbstractOutputFileReporter.java index 72f3265347..4a056888ff 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/report/AbstractOutputFileReporter.java +++ b/core/citrus-base/src/main/java/org/citrusframework/report/AbstractOutputFileReporter.java @@ -16,15 +16,15 @@ package org.citrusframework.report; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @since 2.7.4 */ @@ -64,7 +64,7 @@ private void createReportFile(String reportFileName, String content) { try (Writer fileWriter = new FileWriter(new File(targetDirectory, reportFileName))) { fileWriter.append(content); fileWriter.flush(); - logger.info("Generated test report: " + targetDirectory + File.separator + reportFileName); + logger.info("Generated test report: {}{}{}", targetDirectory, File.separator, reportFileName); } catch (IOException e) { logger.error("Failed to create test report", e); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/report/HtmlReporter.java b/core/citrus-base/src/main/java/org/citrusframework/report/HtmlReporter.java index e093ce1e96..84ae87edef 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/report/HtmlReporter.java +++ b/core/citrus-base/src/main/java/org/citrusframework/report/HtmlReporter.java @@ -16,16 +16,6 @@ package org.citrusframework.report; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.text.DateFormat; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Properties; - import org.apache.commons.codec.binary.Base64; import org.citrusframework.TestCase; import org.citrusframework.TestCaseMetaInfo; @@ -37,6 +27,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.text.DateFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; + /** * Basic logging reporter generating a HTML report with detailed test results. * @@ -243,7 +243,7 @@ private String getStackTraceHtml(Throwable cause) { } return "" + - "

    " + stackTraceBuilder.toString() +
    +        		"
    " + stackTraceBuilder +
             		"
    " + getCodeSnippetHtml(cause) + "
    "; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/report/MessageTracingTestListener.java b/core/citrus-base/src/main/java/org/citrusframework/report/MessageTracingTestListener.java index 771973daa4..65ab37fd2d 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/report/MessageTracingTestListener.java +++ b/core/citrus-base/src/main/java/org/citrusframework/report/MessageTracingTestListener.java @@ -16,15 +16,6 @@ package org.citrusframework.report; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - import org.citrusframework.CitrusSettings; import org.citrusframework.TestCase; import org.citrusframework.context.TestContext; @@ -34,10 +25,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + /** * Test listener collects all messages sent and received by Citrus during test execution. Listener * writes a trace file with all message content per test case to a output directory. - * + *

    * Note: This class is not thread safe! Parallel test execution leads to behaviour that messages get mixed. * Proper correlation to test case is not possible here. * @@ -129,7 +129,7 @@ private String separator() { * @return */ private String newLine() { - return System.getProperty("line.separator"); + return System.lineSeparator(); } /** @@ -151,7 +151,7 @@ protected File getTraceFile(String testName) { File traceFile = new File(targetDirectory, filename); if (traceFile.exists()) { - logger.warn(String.format("Trace file '%s' already exists. Normally a new file is created on each test execution ", traceFile.getName())); + logger.warn("Trace file '{}' already exists. Normally a new file is created on each test execution ", traceFile.getName()); } return traceFile; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/server/AbstractServer.java b/core/citrus-base/src/main/java/org/citrusframework/server/AbstractServer.java index d9d1d14b3f..a5b7b8adff 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/server/AbstractServer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/server/AbstractServer.java @@ -16,9 +16,6 @@ package org.citrusframework.server; -import java.util.ArrayList; -import java.util.List; - import org.citrusframework.common.InitializingPhase; import org.citrusframework.common.ShutdownPhase; import org.citrusframework.context.TestContextFactory; @@ -36,6 +33,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + /** * Abstract base class for {@link Server} implementations. * @@ -85,9 +85,7 @@ public AbstractServer() { @Override public void start() { - if (logger.isDebugEnabled()) { - logger.debug("Starting server: " + getName() + " ..."); - } + logger.debug("Starting server: {} ...", getName()); startup(); @@ -99,15 +97,13 @@ public void start() { thread.setDaemon(false); thread.start(); - logger.info("Started server: " + getName()); + logger.info("Started server: {}", getName()); } @Override public void stop() { if (isRunning()) { - if (logger.isDebugEnabled()) { - logger.debug("Stopping server: " + getName() + " ..."); - } + logger.debug("Stopping server: {} ...", getName()); shutdown(); @@ -117,7 +113,7 @@ public void stop() { thread = null; - logger.info("Stopped server: " + getName()); + logger.info("Stopped server: {}", getName()); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/sharding/ShardingConfiguration.java b/core/citrus-base/src/main/java/org/citrusframework/sharding/ShardingConfiguration.java index b203f4e4c0..85ccd5963b 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/sharding/ShardingConfiguration.java +++ b/core/citrus-base/src/main/java/org/citrusframework/sharding/ShardingConfiguration.java @@ -109,7 +109,7 @@ public ShardingConfiguration() { * * @param systemProvider a provider for system environment variables and properties. */ - protected ShardingConfiguration(SystemProvider systemProvider) { + ShardingConfiguration(SystemProvider systemProvider) { this(getTotalNumberOfShards(systemProvider), getShardNumber(systemProvider), systemProvider); } @@ -131,7 +131,7 @@ public ShardingConfiguration(int totalNumberOfShards, int shardNumber) { * @param shardNumber the shard number for this loader, zero-based. * @param systemProvider a provider for system environment variables and properties. */ - protected ShardingConfiguration(int totalNumberOfShards, int shardNumber, SystemProvider systemProvider) { + private ShardingConfiguration(int totalNumberOfShards, int shardNumber, SystemProvider systemProvider) { this.totalNumberOfShards = totalNumberOfShards; this.shardNumber = shardNumber; diff --git a/core/citrus-base/src/main/java/org/citrusframework/util/BooleanExpressionParser.java b/core/citrus-base/src/main/java/org/citrusframework/util/BooleanExpressionParser.java index c33f14288f..09e91ef776 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/util/BooleanExpressionParser.java +++ b/core/citrus-base/src/main/java/org/citrusframework/util/BooleanExpressionParser.java @@ -127,9 +127,7 @@ public static boolean evaluate(final String expression) { result = parseBoolean(evaluateExpressionStack(operators, values)); - if (logger.isDebugEnabled()) { - logger.debug("Boolean expression {} evaluates to {}", expression, result); - } + logger.debug("Boolean expression {} evaluates to {}", expression, result); } catch (final NoSuchElementException e) { throw new CitrusRuntimeException("Unable to parse boolean expression '" + expression + "'. Maybe expression is incomplete!", e); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/util/FileUtils.java b/core/citrus-base/src/main/java/org/citrusframework/util/FileUtils.java index ce40894de1..86c94dd5ec 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/util/FileUtils.java +++ b/core/citrus-base/src/main/java/org/citrusframework/util/FileUtils.java @@ -16,6 +16,15 @@ package org.citrusframework.util; +import org.citrusframework.CitrusSettings; +import org.citrusframework.TestSource; +import org.citrusframework.context.TestContext; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.spi.Resource; +import org.citrusframework.spi.Resources; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; @@ -32,15 +41,6 @@ import java.util.Set; import java.util.Stack; -import org.citrusframework.CitrusSettings; -import org.citrusframework.TestSource; -import org.citrusframework.context.TestContext; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.citrusframework.spi.Resource; -import org.citrusframework.spi.Resources; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Class to provide general file utilities, such as listing all XML files in a directory, * or finding certain tests in a directory. @@ -121,9 +121,8 @@ public static String readToString(Resource resource, Charset charset) throws IOE throw new CitrusRuntimeException("Failed to read resource %s - does not exist".formatted(resource.getLocation())); } - if (logger.isDebugEnabled()) { - logger.debug(String.format("Reading file resource: '%s' (encoding is '%s')", resource.getLocation(), charset.displayName())); - } + logger.debug("Reading file resource: '{}' (encoding is '{}')", resource.getLocation(), charset.displayName()); + return readToString(resource.getInputStream(), charset); } @@ -148,9 +147,7 @@ public static String readToString(InputStream inputStream, Charset charset) thro * @param file */ public static void writeToFile(InputStream inputStream, File file) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Writing file resource: '%s'", file.getName())); - } + logger.debug("Writing file resource: '{}'", file.getName()); if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { @@ -180,9 +177,7 @@ public static void writeToFile(String content, File file) { * @param file */ public static void writeToFile(String content, File file, Charset charset) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Writing file resource: '%s' (encoding is '%s')", file.getName(), charset.displayName())); - } + logger.debug("Writing file resource: '{}' (encoding is '{}')", file.getName(), charset.displayName()); if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { @@ -224,7 +219,7 @@ public static List findFiles(final String startDir, final Set file } /* walk through the directories */ - while (dirs.size() > 0) { + while (!dirs.isEmpty()) { final File file = dirs.pop(); File[] foundFiles = file.listFiles((dir, name) -> { File tmp = new File(dir.getPath() + File.separator + name); diff --git a/core/citrus-base/src/main/java/org/citrusframework/util/PropertyUtils.java b/core/citrus-base/src/main/java/org/citrusframework/util/PropertyUtils.java index 43788a1abf..588616bfb5 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/util/PropertyUtils.java +++ b/core/citrus-base/src/main/java/org/citrusframework/util/PropertyUtils.java @@ -16,12 +16,12 @@ package org.citrusframework.util; -import java.io.IOException; -import java.util.Properties; - import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.spi.Resource; +import java.io.IOException; +import java.util.Properties; + /** * Utility class supporting property replacement in template files. * For usage see doc generators and test case creator. @@ -99,7 +99,7 @@ public static String replacePropertiesInString(final String line, Properties pro if (!properties.containsKey(propertyName.toString())) { throw new CitrusRuntimeException("No such property '" - + PROPERTY_MARKER + propertyName.toString() + PROPERTY_MARKER + "'"); + + PROPERTY_MARKER + propertyName + PROPERTY_MARKER + "'"); } newStr.append(line, startIndex, searchIndex); diff --git a/core/citrus-base/src/main/java/org/citrusframework/util/StringUtils.java b/core/citrus-base/src/main/java/org/citrusframework/util/StringUtils.java index 7b68e39ddb..3cf0086ac4 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/util/StringUtils.java +++ b/core/citrus-base/src/main/java/org/citrusframework/util/StringUtils.java @@ -62,7 +62,6 @@ public static boolean isNotEmpty(String str) { } public static String appendSegmentToUrlPath(String path, String segment) { - if (path == null) { return segment; } @@ -88,7 +87,7 @@ public static String quote(String text, boolean quote) { /** * Trims trailing whitespace characters and the first trailing comma from the end of the given StringBuilder. - * + *

    * This method removes all trailing whitespace characters (such as spaces, tabs, and newline characters) * and the first trailing comma found from the end of the content in the provided StringBuilder. * Any additional commas or whitespace characters after the first trailing comma are not removed. @@ -114,11 +113,11 @@ public static void trimTrailingComma(StringBuilder builder) { * the rest of the string unchanged. If the input string is empty or null, * an empty string is returned. * - * @param input The string to be converted to title case. It can be null or empty. - * @return the strnig in title case + * @param input The string to be converted. It can be null or empty. + * @return the string in with upper case first letter */ - public static String titleCase(String input) { - if (input != null && !"".equals(input)) { + public static String convertFirstChartToUpperCase(String input) { + if (input != null && !input.isEmpty()) { String firstLetter = input.substring(0, 1).toUpperCase(Locale.ROOT); return input.length() == 1 ? firstLetter : firstLetter + input.substring(1); } else { diff --git a/core/citrus-base/src/main/java/org/citrusframework/util/TestUtils.java b/core/citrus-base/src/main/java/org/citrusframework/util/TestUtils.java index 67ba7afd8a..469d2963fe 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/util/TestUtils.java +++ b/core/citrus-base/src/main/java/org/citrusframework/util/TestUtils.java @@ -93,7 +93,7 @@ public static void waitForCompletion(final ScheduledExecutorService scheduledExe if (logger.isDebugEnabled()) { logger.debug("Failed to wait for completion of nested test actions", e); } else { - logger.warn(String.format("Failed to wait for completion of nested test actions because of %s", e.getMessage())); + logger.warn("Failed to wait for completion of nested test actions because of {}", e.getMessage()); } } }, 100L, timeout / 10, TimeUnit.MILLISECONDS); @@ -110,7 +110,7 @@ public static void waitForCompletion(final ScheduledExecutorService scheduledExe scheduledExecutor.shutdown(); scheduledExecutor.awaitTermination((timeout / 10) / 2, TimeUnit.MICROSECONDS); } catch (InterruptedException e) { - logger.warn(String.format("Failed to await orderly termination of waiting tasks to complete, caused by %s", e.getMessage())); + logger.warn("Failed to await orderly termination of waiting tasks to complete, caused by {}", e.getMessage()); } if (!scheduledExecutor.isTerminated()) { diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultHeaderValidator.java b/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultHeaderValidator.java index d62bce85db..d0233cfec9 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultHeaderValidator.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultHeaderValidator.java @@ -16,13 +16,6 @@ package org.citrusframework.validation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.ValidationException; import org.citrusframework.util.StringUtils; @@ -31,6 +24,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; + /** * @since 2.7.6 */ @@ -76,9 +77,7 @@ public void validateHeader(String headerName, Object receivedValue, Object contr + null + "'"); } - if (logger.isDebugEnabled()) { - logger.debug("Validating header element: %s='%s' : OK".formatted(headerName, expectedValue)); - } + logger.debug("Validating header element: {}='{}' : OK", headerName, expectedValue); } public void validateHeaderArray(String headerName, Object receivedValue, Object controlValue, TestContext context, HeaderValidationContext validationContext) { @@ -121,15 +120,12 @@ public void validateHeaderArray(String headerName, Object receivedValue, Object throw new ValidationException(String.format("Values not equal for header element '%s', expected '%s' but was '%s'", headerName, String.join(", ", expectedValues), String.join(", ", receivedValues))); } - } else if (!expectedValues.isEmpty()) { throw new ValidationException(String.format("Values not equal for header element '%s', expected '%s' but was 'null'", headerName, String.join(", ", expectedValues))); } - if (logger.isDebugEnabled()) { - logger.debug("Validating header element: %s='%s' : OK".formatted(headerName, String.join(", ", expectedValues))); - } + logger.debug("Validating header element: {}='{}' : OK", headerName, String.join(", ", expectedValues)); } private static boolean validateExpected(String headerName, TestContext context, @@ -156,6 +152,7 @@ private static boolean validateExpected(String headerName, TestContext context, } } } + return validated; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultMessageHeaderValidator.java b/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultMessageHeaderValidator.java index f6bcc30068..fed3d9171b 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultMessageHeaderValidator.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/DefaultMessageHeaderValidator.java @@ -16,15 +16,6 @@ package org.citrusframework.validation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - import org.citrusframework.context.TestContext; import org.citrusframework.endpoint.resolver.EndpointUriResolver; import org.citrusframework.exceptions.CitrusRuntimeException; @@ -36,6 +27,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + /** * Basic header message validator provides message header validation. Subclasses only have to add * specific logic for message payload validation. This validator is based on a control message. @@ -112,7 +112,7 @@ public void validateMessage(Message receivedMessage, Message controlMessage, Tes /** * Combines header validators from multiple sources. First the manual added validators in this class are added. Then * validators coming from reference resolver and resource path lookup are added. - * + *

    * At the end a distinct combination of all validators is returned. * @param context * @return diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/DelegatingPayloadVariableExtractor.java b/core/citrus-base/src/main/java/org/citrusframework/validation/DelegatingPayloadVariableExtractor.java index a7d59ab176..d86d7d3b61 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/DelegatingPayloadVariableExtractor.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/DelegatingPayloadVariableExtractor.java @@ -60,9 +60,7 @@ public void extractVariables(Message message, TestContext context) { return; } - if (logger.isDebugEnabled()) { - logger.debug("Reading path elements."); - } + logger.debug("Reading path elements."); Map jsonPathExpressions = new LinkedHashMap<>(); Map xpathExpressions = new LinkedHashMap<>(); diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/ValidationUtils.java b/core/citrus-base/src/main/java/org/citrusframework/validation/ValidationUtils.java index d18083c144..600f8a29cd 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/ValidationUtils.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/ValidationUtils.java @@ -16,18 +16,18 @@ package org.citrusframework.validation; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - import org.apache.commons.codec.binary.Base64; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.exceptions.ValidationException; import org.citrusframework.validation.matcher.ValidationMatcherUtils; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + /** * Utility class provides helper methods for validation work in Citrus. * @@ -155,7 +155,7 @@ public static void validateValues(Object actualValue, Object expectedValue, Stri /** * Combines value matchers from multiple sources. Includes validators coming from reference resolver * and resource path lookup are added. - * + *

    * Then pick matcher that explicitly supports the given expected value type. * @param expectedValue * @param context diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/json/JsonMessageValidationContext.java b/core/citrus-base/src/main/java/org/citrusframework/validation/json/JsonMessageValidationContext.java index 3c4faaaec0..39d1e09768 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/json/JsonMessageValidationContext.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/json/JsonMessageValidationContext.java @@ -16,14 +16,14 @@ package org.citrusframework.validation.json; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.citrusframework.validation.context.DefaultValidationContext; import org.citrusframework.validation.context.SchemaValidationContext; import org.citrusframework.validation.context.ValidationContext; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** * Validation context holding JSON specific validation information. * @since 2.3 @@ -35,7 +35,7 @@ public class JsonMessageValidationContext extends DefaultValidationContext imple /** * Should message be validated with its schema definition - * + *

    * This is currently disabled by default, because old json tests would fail with a validation exception * as soon as a json schema repository is specified and the schema validation is activated. */ diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/DefaultValidationMatcherLibrary.java b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/DefaultValidationMatcherLibrary.java index ad87db3edd..d4dea2294f 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/DefaultValidationMatcherLibrary.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/DefaultValidationMatcherLibrary.java @@ -84,9 +84,7 @@ public DefaultValidationMatcherLibrary() { private void lookupValidationMatchers() { ValidationMatcher.lookup().forEach((k, m) -> { getMembers().put(k, m); - if (logger.isDebugEnabled()) { - logger.debug(String.format("Register message matcher '%s' as %s", k, m.getClass())); - } + logger.debug("Register message matcher '{}' as {}", k, m.getClass()); }); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/CreateVariableValidationMatcher.java b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/CreateVariableValidationMatcher.java index a55813f0b1..fe51f77e92 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/CreateVariableValidationMatcher.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/CreateVariableValidationMatcher.java @@ -16,14 +16,14 @@ package org.citrusframework.validation.matcher.core; -import java.util.List; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.ValidationException; import org.citrusframework.validation.matcher.ValidationMatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + /** * Creates new variables from given field. Either uses field name or control value as variable name. * @@ -42,7 +42,7 @@ public void validate(String fieldName, String value, List controlParamet name = controlParameters.get(0); } - logger.debug("Setting variable: " + name + " to value: " + value); + logger.debug("Setting variable: {} to value: {}", name, value); context.setVariable(name, value); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/DateRangeValidationMatcher.java b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/DateRangeValidationMatcher.java index 658fc84cfd..94e790ce12 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/DateRangeValidationMatcher.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/DateRangeValidationMatcher.java @@ -47,10 +47,7 @@ public class DateRangeValidationMatcher implements ValidationMatcher { @Override public void validate(String fieldName, String value, List params, TestContext context) throws ValidationException { - logger.debug(String.format( - "Validating date range for date '%s' using control data: %s", - value, - ValidationMatcherUtils.getParameterListAsString(params))); + logger.debug("Validating date range for date '{}' using control data: {}", value, ValidationMatcherUtils.getParameterListAsString(params)); try { String dateFromParam = params.get(0); diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/IgnoreValidationMatcher.java b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/IgnoreValidationMatcher.java index b5deaa66af..568892eca2 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/IgnoreValidationMatcher.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/IgnoreValidationMatcher.java @@ -34,8 +34,6 @@ public class IgnoreValidationMatcher implements ValidationMatcher { @Override public void validate(String fieldName, String value, List controlParameters, TestContext context) throws ValidationException { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Ignoring value for field '%s'", fieldName)); - } + logger.debug("Ignoring value for field '{}'", fieldName); } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/WeekdayValidationMatcher.java b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/WeekdayValidationMatcher.java index e896d42255..6f181c537c 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/WeekdayValidationMatcher.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/matcher/core/WeekdayValidationMatcher.java @@ -107,7 +107,7 @@ private enum Weekday { SATURDAY(Calendar.SATURDAY), SUNDAY(Calendar.SUNDAY); - private int constantValue; + private final int constantValue; Weekday(int constant) { this.constantValue = constant; diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/script/TemplateBasedScriptBuilder.java b/core/citrus-base/src/main/java/org/citrusframework/validation/script/TemplateBasedScriptBuilder.java index b9c7c1ba66..38fefeca30 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/script/TemplateBasedScriptBuilder.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/script/TemplateBasedScriptBuilder.java @@ -16,14 +16,14 @@ package org.citrusframework.validation.script; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; - import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.spi.Resource; import org.citrusframework.util.FileUtils; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; + /** * Script builder builds a script with custom code body. Script header and tail come from static * script template. @@ -71,7 +71,7 @@ public String build() { scriptBuilder.append(line); scriptBuilder.append("\n"); } else { - scriptBody.append((scriptBody.length() == 0 ? "" : "\n")); + scriptBody.append((scriptBody.isEmpty() ? "" : "\n")); scriptBody.append(line); } } @@ -83,7 +83,7 @@ public String build() { } scriptBuilder.append(scriptHead); - scriptBuilder.append(scriptBody.toString()); + scriptBuilder.append(scriptBody); scriptBuilder.append(scriptTail); return scriptBuilder.toString(); diff --git a/core/citrus-base/src/main/java/org/citrusframework/validation/script/sql/SqlResultSetScriptValidator.java b/core/citrus-base/src/main/java/org/citrusframework/validation/script/sql/SqlResultSetScriptValidator.java index 65ac950ec6..da62d2c682 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/validation/script/sql/SqlResultSetScriptValidator.java +++ b/core/citrus-base/src/main/java/org/citrusframework/validation/script/sql/SqlResultSetScriptValidator.java @@ -16,9 +16,6 @@ package org.citrusframework.validation.script.sql; -import java.util.List; -import java.util.Map; - import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.ValidationException; import org.citrusframework.spi.ResourcePathTypeResolver; @@ -27,6 +24,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.Map; + /** * Validator working on SQL result sets. Scripts get the actual test context * and a SQL result set representation for validation. @@ -52,7 +52,7 @@ static Map lookup() { Map validators = TYPE_RESOLVER.resolveAll("", TypeResolver.DEFAULT_TYPE_PROPERTY, "name"); if (logger.isDebugEnabled()) { - validators.forEach((k, v) -> logger.debug(String.format("Found SQL result set validator '%s' as %s", k, v.getClass()))); + validators.forEach((k, v) -> logger.debug("Found SQL result set validator '{}' as {}", k, v.getClass())); } return validators; } diff --git a/core/citrus-base/src/main/java/org/citrusframework/xml/Jaxb2Marshaller.java b/core/citrus-base/src/main/java/org/citrusframework/xml/Jaxb2Marshaller.java index 9baf24fa25..bbc8e9f76a 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/xml/Jaxb2Marshaller.java +++ b/core/citrus-base/src/main/java/org/citrusframework/xml/Jaxb2Marshaller.java @@ -16,21 +16,6 @@ package org.citrusframework.xml; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.xml.XMLConstants; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.sax.SAXSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; - import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.PropertyException; @@ -43,6 +28,21 @@ import org.xml.sax.SAXException; import org.xml.sax.XMLReader; +import javax.xml.XMLConstants; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.sax.SAXSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + /** * Marshaller uses Jaxb to marshal/unmarshal data. */ @@ -119,7 +119,7 @@ private jakarta.xml.bind.Marshaller createMarshaller() throws JAXBException { try { marshaller.setProperty(k, v); } catch (PropertyException e) { - logger.warn(String.format("Unable to set marshaller property %s=%s", k, v)); + logger.warn("Unable to set marshaller property {}={}", k, v); } }); @@ -139,9 +139,7 @@ private jakarta.xml.bind.Unmarshaller createUnmarshaller() throws JAXBException private JAXBContext getOrCreateContext() throws JAXBException { if (jaxbContext == null) { synchronized (this) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Creating JAXBContext with bound classes %s", Arrays.toString(classesToBeBound))); - } + logger.debug("Creating JAXBContext with bound classes {}", Arrays.toString(classesToBeBound)); if (classesToBeBound != null) { jaxbContext = JAXBContext.newInstance(classesToBeBound); @@ -161,10 +159,7 @@ public void setProperty(String key, Object value) { } private Schema loadSchema(Resource... schemas) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Using marshaller validation schemas '%s'", - Stream.of(schemas).map(Object::toString).collect(Collectors.joining(",")))); - } + logger.debug("Using marshaller validation schemas '{}'", Stream.of(schemas).map(Object::toString).collect(Collectors.joining(","))); try { List schemaSources = new ArrayList<>(); diff --git a/core/citrus-base/src/test/java/org/citrusframework/TestCaseTest.java b/core/citrus-base/src/test/java/org/citrusframework/TestCaseTest.java index 638474f31c..fcfec80b37 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/TestCaseTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/TestCaseTest.java @@ -16,13 +16,6 @@ package org.citrusframework; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; - import org.citrusframework.actions.AbstractAsyncTestAction; import org.citrusframework.actions.EchoAction; import org.citrusframework.container.Async; @@ -35,6 +28,13 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + import static org.citrusframework.DefaultTestActionBuilder.action; public class TestCaseTest extends UnitTestSupport { @@ -121,7 +121,7 @@ public void doExecuteAsync(final TestContext context) { .findAny(); waitingThread.ifPresent(thread -> LoggerFactory.getLogger("TestWaitForFinishAsync").warn(Arrays.toString(threads.get(thread)))); - waitingThread.ifPresent(thread -> Assert.fail(String.format("Waiting thread still alive: %s", thread.toString()))); + waitingThread.ifPresent(thread -> Assert.fail(String.format("Waiting thread still alive: %s", thread))); } @Test @@ -220,6 +220,6 @@ public void testThreadLeak() { .filter(Thread::isAlive) .findAny(); - waitingThread.ifPresent(thread -> Assert.fail(String.format("Waiting thread still alive: %s", thread.toString()))); + waitingThread.ifPresent(thread -> Assert.fail(String.format("Waiting thread still alive: %s", thread))); } } diff --git a/core/citrus-base/src/test/java/org/citrusframework/actions/PurgeEndpointActionTest.java b/core/citrus-base/src/test/java/org/citrusframework/actions/PurgeEndpointActionTest.java index b77472e1e5..24c7981518 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/actions/PurgeEndpointActionTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/actions/PurgeEndpointActionTest.java @@ -16,8 +16,6 @@ package org.citrusframework.actions; -import java.util.Collections; - import org.citrusframework.UnitTestSupport; import org.citrusframework.context.TestContextFactory; import org.citrusframework.endpoint.Endpoint; @@ -28,6 +26,8 @@ import org.mockito.Mockito; import org.testng.annotations.Test; +import java.util.Collections; + import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; @@ -85,7 +85,7 @@ public void testPurgeWithEndpointObjects() { } @Test - public void testPurgeWithMessageSelector() throws Exception { + public void testPurgeWithMessageSelector() { reset(mockEndpoint, consumer, selectiveConsumer); when(mockEndpoint.getName()).thenReturn("mockEndpoint"); @@ -102,7 +102,7 @@ public void testPurgeWithMessageSelector() throws Exception { } @Test - public void testPurgeWithMessageSelectorMap() throws Exception { + public void testPurgeWithMessageSelectorMap() { reset(mockEndpoint, consumer, selectiveConsumer); when(mockEndpoint.getName()).thenReturn("mockEndpoint"); diff --git a/core/citrus-base/src/test/java/org/citrusframework/actions/ReceiveMessageBuilderTest.java b/core/citrus-base/src/test/java/org/citrusframework/actions/ReceiveMessageBuilderTest.java index 9b19eeba19..60cc62070c 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/actions/ReceiveMessageBuilderTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/actions/ReceiveMessageBuilderTest.java @@ -16,14 +16,6 @@ package org.citrusframework.actions; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.citrusframework.context.TestContext; import org.citrusframework.context.TestContextFactory; import org.citrusframework.endpoint.Endpoint; @@ -52,11 +44,24 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static org.citrusframework.validation.json.JsonMessageValidationContext.Builder.json; import static org.citrusframework.validation.json.JsonPathMessageValidationContext.Builder.jsonPath; import static org.citrusframework.validation.xml.XmlMessageValidationContext.Builder.xml; import static org.citrusframework.validation.xml.XpathMessageValidationContext.Builder.xpath; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -206,7 +211,7 @@ void payload_asResourceWithCharset() { } @Test - void testSetPayloadWithResourceIoExceptionsIsWrapped() throws IOException { + void testSetPayloadWithResourceIoExceptionsIsWrapped() { //GIVEN final ReceiveMessageAction.Builder builder = new ReceiveMessageAction.Builder(); diff --git a/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/ReceiveMessageActionBuilderTest.java b/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/ReceiveMessageActionBuilderTest.java index cdba297247..1888eff21f 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/ReceiveMessageActionBuilderTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/ReceiveMessageActionBuilderTest.java @@ -16,12 +16,6 @@ package org.citrusframework.actions.dsl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - import org.citrusframework.DefaultTestCaseRunner; import org.citrusframework.TestCase; import org.citrusframework.UnitTestSupport; @@ -59,11 +53,22 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.io.ByteArrayInputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import static org.citrusframework.actions.ReceiveMessageAction.Builder.receive; import static org.citrusframework.dsl.MessageSupport.MessageHeaderSupport.fromHeaders; import static org.citrusframework.dsl.MessageSupport.message; import static org.citrusframework.validation.xml.XmlMessageValidationContext.Builder.xml; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class ReceiveMessageActionBuilderTest extends UnitTestSupport { @@ -220,7 +225,7 @@ public void testReceiveBuilderWithPayloadString() { } @Test - public void testReceiveBuilderWithPayloadResource() throws IOException { + public void testReceiveBuilderWithPayloadResource() { reset(resource, messageEndpoint, messageConsumer, configuration); when(messageEndpoint.createConsumer()).thenReturn(messageConsumer); when(messageEndpoint.getEndpointConfiguration()).thenReturn(configuration); @@ -523,7 +528,7 @@ public void testReceiveBuilderWithHeaderDataBuilder() { } @Test - public void testReceiveBuilderWithHeaderResource() throws IOException { + public void testReceiveBuilderWithHeaderResource() { reset(resource, messageEndpoint, messageConsumer, configuration); when(messageEndpoint.createConsumer()).thenReturn(messageConsumer); when(messageEndpoint.getEndpointConfiguration()).thenReturn(configuration); @@ -581,7 +586,7 @@ public void testReceiveBuilderWithHeaderResource() throws IOException { } @Test - public void testReceiveBuilderWithMultipleHeaderResource() throws IOException { + public void testReceiveBuilderWithMultipleHeaderResource() { reset(resource, messageEndpoint, messageConsumer, configuration); when(messageEndpoint.createConsumer()).thenReturn(messageConsumer); when(messageEndpoint.getEndpointConfiguration()).thenReturn(configuration); @@ -1051,7 +1056,7 @@ public void testReceiveBuilderWithValidationProcessor() { } @Test - public void testDeactivateSchemaValidation() throws IOException { + public void testDeactivateSchemaValidation() { reset(messageEndpoint, messageConsumer, configuration); when(messageEndpoint.createConsumer()).thenReturn(messageConsumer); diff --git a/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/SendMessageActionBuilderTest.java b/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/SendMessageActionBuilderTest.java index 7bfe51471f..d31b38669c 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/SendMessageActionBuilderTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/actions/dsl/SendMessageActionBuilderTest.java @@ -16,11 +16,6 @@ package org.citrusframework.actions.dsl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; - import org.citrusframework.DefaultTestCaseRunner; import org.citrusframework.TestCase; import org.citrusframework.UnitTestSupport; @@ -52,6 +47,10 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.io.ByteArrayInputStream; +import java.util.Collections; +import java.util.HashMap; + import static org.citrusframework.actions.SendMessageAction.Builder.send; import static org.citrusframework.dsl.MessageSupport.message; import static org.mockito.Mockito.any; @@ -273,7 +272,7 @@ public void testSendBuilderWithPayloadData() { } @Test - public void testSendBuilderWithPayloadResource() throws IOException { + public void testSendBuilderWithPayloadResource() { reset(resource, messageEndpoint, messageProducer); when(messageEndpoint.createProducer()).thenReturn(messageProducer); when(messageEndpoint.getActor()).thenReturn(null); @@ -497,7 +496,7 @@ public void testSendBuilderWithMultipleHeaderData() { } @Test - public void testSendBuilderWithHeaderDataResource() throws IOException { + public void testSendBuilderWithHeaderDataResource() { reset(resource, messageEndpoint, messageProducer); when(messageEndpoint.createProducer()).thenReturn(messageProducer); when(messageEndpoint.getActor()).thenReturn(null); diff --git a/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/HeaderMappingKeyExtractorTest.java b/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/HeaderMappingKeyExtractorTest.java index cf93cc2e75..806dda55fa 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/HeaderMappingKeyExtractorTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/HeaderMappingKeyExtractorTest.java @@ -24,7 +24,7 @@ public class HeaderMappingKeyExtractorTest { @Test - public void testExtractMappingKey() throws Exception { + public void testExtractMappingKey() { HeaderMappingKeyExtractor extractor = new HeaderMappingKeyExtractor(); extractor.setHeaderName("Foo"); @@ -34,7 +34,7 @@ public void testExtractMappingKey() throws Exception { } @Test - public void testExtractMappingKeyWithoutHeaderNameSet() throws Exception { + public void testExtractMappingKeyWithoutHeaderNameSet() { HeaderMappingKeyExtractor extractor = new HeaderMappingKeyExtractor(); try { @@ -48,7 +48,7 @@ public void testExtractMappingKeyWithoutHeaderNameSet() throws Exception { } @Test - public void testExtractMappingKeyWithUnknownHeaderName() throws Exception { + public void testExtractMappingKeyWithUnknownHeaderName() { HeaderMappingKeyExtractor extractor = new HeaderMappingKeyExtractor("UNKNOWN"); try { diff --git a/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/SoapActionMappingKeyExtractorTest.java b/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/SoapActionMappingKeyExtractorTest.java index 2285c3c752..f7ef07644d 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/SoapActionMappingKeyExtractorTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/endpoint/adapter/mapping/SoapActionMappingKeyExtractorTest.java @@ -24,7 +24,7 @@ public class SoapActionMappingKeyExtractorTest { @Test - public void testExtractMappingKey() throws Exception { + public void testExtractMappingKey() { SoapActionMappingKeyExtractor extractor = new SoapActionMappingKeyExtractor(); Assert.assertEquals(extractor.extractMappingKey(new DefaultMessage("Foo") @@ -33,7 +33,7 @@ public void testExtractMappingKey() throws Exception { } @Test - public void testExtractNoMappingFound() throws Exception { + public void testExtractNoMappingFound() { SoapActionMappingKeyExtractor extractor = new SoapActionMappingKeyExtractor(); try { diff --git a/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointComponentTest.java b/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointComponentTest.java index 04a94c6091..d28152e42b 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointComponentTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointComponentTest.java @@ -16,8 +16,6 @@ package org.citrusframework.endpoint.direct; -import java.util.Map; - import org.citrusframework.context.TestContext; import org.citrusframework.context.TestContextFactory; import org.citrusframework.endpoint.Endpoint; @@ -26,6 +24,8 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.util.Map; + public class DirectEndpointComponentTest { private TestContext context; @@ -36,7 +36,7 @@ public void setupMocks() { } @Test - public void testCreateDirectEndpoint() throws Exception { + public void testCreateDirectEndpoint() { DirectEndpointComponent component = new DirectEndpointComponent(); Assert.assertFalse(context.getReferenceResolver().isResolvable("queueName")); @@ -50,7 +50,7 @@ public void testCreateDirectEndpoint() throws Exception { } @Test - public void testCreateSyncDirectEndpoint() throws Exception { + public void testCreateSyncDirectEndpoint() { DirectEndpointComponent component = new DirectEndpointComponent(); Assert.assertFalse(context.getReferenceResolver().isResolvable("queueName")); @@ -63,7 +63,7 @@ public void testCreateSyncDirectEndpoint() throws Exception { } @Test - public void testCreateDirectEndpointWithParameters() throws Exception { + public void testCreateDirectEndpointWithParameters() { DirectEndpointComponent component = new DirectEndpointComponent(); Endpoint endpoint = component.createEndpoint("direct:queueName?timeout=10000", context); diff --git a/core/citrus-base/src/test/java/org/citrusframework/functions/FunctionsTest.java b/core/citrus-base/src/test/java/org/citrusframework/functions/FunctionsTest.java index 975946ca91..c4433e3ace 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/functions/FunctionsTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/functions/FunctionsTest.java @@ -16,15 +16,23 @@ package org.citrusframework.functions; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; - import org.citrusframework.UnitTestSupport; import org.citrusframework.functions.core.RandomStringFunction; import org.testng.Assert; import org.testng.annotations.Test; -import static org.citrusframework.functions.Functions.*; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; + +import static org.citrusframework.functions.Functions.changeDate; +import static org.citrusframework.functions.Functions.currentDate; +import static org.citrusframework.functions.Functions.decodeBase64; +import static org.citrusframework.functions.Functions.digestAuthHeader; +import static org.citrusframework.functions.Functions.encodeBase64; +import static org.citrusframework.functions.Functions.randomNumber; +import static org.citrusframework.functions.Functions.randomString; +import static org.citrusframework.functions.Functions.randomUUID; +import static org.citrusframework.functions.Functions.unixTimestamp; public class FunctionsTest extends UnitTestSupport { @@ -39,65 +47,65 @@ public void testCurrentDateFormat() throws Exception { } @Test - public void testChangeDate() throws Exception { + public void testChangeDate() { Assert.assertEquals(changeDate("01.01.2014", "+1y", context), "01.01.2015"); Assert.assertEquals(changeDate("2014-01-01T12:00:00", "+1y", "yyyy-MM-dd'T'HH:mm:ss", context), "2015-01-01T12:00:00"); } @Test - public void testEncodeBase64() throws Exception { + public void testEncodeBase64() { Assert.assertEquals(encodeBase64("Foo", context), "Rm9v"); } @Test - public void testEncodeBase64WithCharset() throws Exception { + public void testEncodeBase64WithCharset() { Assert.assertEquals(encodeBase64("Foo", StandardCharsets.UTF_8, context), "Rm9v"); } @Test - public void testDecodeBase64() throws Exception { + public void testDecodeBase64() { Assert.assertEquals(decodeBase64("Rm9v", context), "Foo"); } @Test - public void testDecodeBase64WithCharset() throws Exception { + public void testDecodeBase64WithCharset() { Assert.assertEquals(decodeBase64("Rm9v", StandardCharsets.UTF_8, context), "Foo"); } @Test - public void testDigestAuthHeader() throws Exception { + public void testDigestAuthHeader() { digestAuthHeader("username", "password", "authRealm", "acegi", "POST", "http://localhost:8080", "citrus", "md5", context); } @Test - public void testRandomUUID() throws Exception { + public void testRandomUUID() { Assert.assertNotNull(randomUUID(context)); } @Test - public void testRandomNumber() throws Exception { + public void testRandomNumber() { Assert.assertTrue(randomNumber(10L, context).length() > 9); } @Test - public void testRandomNumberWithParams() throws Exception { + public void testRandomNumberWithParams() { Assert.assertTrue(randomNumber(10L, true, context).length() > 9); } @Test - public void testRandomString() throws Exception { + public void testRandomString() { Assert.assertEquals(randomString(10L, context).length(), 10); } @Test - public void testRandomStringWithParams() throws Exception { + public void testRandomStringWithParams() { Assert.assertEquals(randomString(10L, false, context).length(), 10); Assert.assertEquals(randomString(10L, RandomStringFunction.LOWERCASE, context).length(), 10); Assert.assertEquals(randomString(10L, RandomStringFunction.UPPERCASE, false, context).length(), 10); } @Test - public void testUnixTimestamp() throws Exception { + public void testUnixTimestamp() { Assert.assertEquals(String.valueOf(System.currentTimeMillis() / 1000L), unixTimestamp(context)); } } diff --git a/core/citrus-base/src/test/java/org/citrusframework/functions/core/AdvancedRandomNumberFunctionTest.java b/core/citrus-base/src/test/java/org/citrusframework/functions/core/AdvancedRandomNumberFunctionTest.java index 82cf51cfa7..f849e55028 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/functions/core/AdvancedRandomNumberFunctionTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/functions/core/AdvancedRandomNumberFunctionTest.java @@ -169,8 +169,7 @@ public void testRandomDouble32MinEqualsMaxEdgeCase() { @Test public void testRandomInteger64EdgeCase() { - List params = List.of("0", "-9223372036854775808", "9223372036854775807", "false", - "false"); + List params = List.of("0", "-9223372036854775808", "9223372036854775807", "false", "false"); String result = function.execute(params, context); assertNotNull(result); double randomValue = Double.parseDouble(result); @@ -188,8 +187,7 @@ public void testRandomNumberFloatEdgeCase() { @Test public void testRandomNumberDoubleEdgeCase() { - List params = List.of("0", "-1.7976931348623157E308", "1.7976931348623157E308", - "false", "false"); + List params = List.of("0", "-1.7976931348623157E308", "1.7976931348623157E308", "false", "false"); String result = function.execute(params, context); assertNotNull(result); double randomValue = Double.parseDouble(result); @@ -244,7 +242,6 @@ public void testInvalidMaxValueFormat() { @DataProvider(name = "testRandomNumber") public static Object[][] testRandomNumber() { return new Object[][]{ - {0, 12, null, null, false, false}, {0, null, 0, 2, true, true}, {0, null, null, null, false, false}, @@ -337,7 +334,6 @@ public static Object[][] testRandomNumber() { {5, 19.123d, -21, 0, true, true}, {5, 20.123d, 0, null, false, false}, {5, 21.123d, 21.122d, 21.124d, false, false}, - }; } @@ -397,8 +393,8 @@ private String toString(Object obj) { if (obj == null) { return "null"; } - return obj.toString(); + return obj.toString(); } private T expectThrows(Class exceptionClass, Runnable runnable) { @@ -411,6 +407,7 @@ private T expectThrows(Class exceptionClass, Runnable r throw new AssertionError("Unexpected exception type", throwable); } } + throw new AssertionError("Expected exception not thrown"); } -} \ No newline at end of file +} diff --git a/core/citrus-base/src/test/java/org/citrusframework/functions/core/LoadMessageFunctionTest.java b/core/citrus-base/src/test/java/org/citrusframework/functions/core/LoadMessageFunctionTest.java index 9f1d341c5b..47ad8a9db0 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/functions/core/LoadMessageFunctionTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/functions/core/LoadMessageFunctionTest.java @@ -16,8 +16,6 @@ package org.citrusframework.functions.core; -import java.util.Collections; - import org.citrusframework.UnitTestSupport; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.message.DefaultMessage; @@ -25,6 +23,8 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.util.Collections; + /** * @since 2.6.2 */ @@ -36,27 +36,27 @@ public class LoadMessageFunctionTest extends UnitTestSupport { .setHeader("operation", "sampleOperation"); @Test - public void testLoadMessagePayload() throws Exception { + public void testLoadMessagePayload() { context.getMessageStore().storeMessage("request", message); Assert.assertEquals(function.execute(Collections.singletonList("request"), context), "This is a sample message"); Assert.assertEquals(function.execute(Collections.singletonList("request.body()"), context), "This is a sample message"); } @Test - public void testLoadMessageHeader() throws Exception { + public void testLoadMessageHeader() { context.getMessageStore().storeMessage("request", message); Assert.assertEquals(function.execute(Collections.singletonList("request.header(operation)"), context), "sampleOperation"); Assert.assertEquals(function.execute(Collections.singletonList("request.header('operation')"), context), "sampleOperation"); } @Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = "Missing header name.*") - public void testLoadMessageHeaderEmpty() throws Exception { + public void testLoadMessageHeaderEmpty() { context.getMessageStore().storeMessage("request", message); function.execute(Collections.singletonList("request.header()"), context); } @Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = "Failed to find header 'wrong'.*") - public void testLoadMessageHeaderUnknown() throws Exception { + public void testLoadMessageHeaderUnknown() { context.getMessageStore().storeMessage("request", message); function.execute(Collections.singletonList("request.header('wrong')"), context); } diff --git a/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomPatternFunctionTest.java b/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomPatternFunctionTest.java index dccbb4b0fc..ce1c67c8ac 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomPatternFunctionTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomPatternFunctionTest.java @@ -16,14 +16,15 @@ package org.citrusframework.functions.core; -import static org.testng.Assert.assertTrue; - -import java.util.List; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.util.List; + +import static org.testng.Assert.assertTrue; + public class RandomPatternFunctionTest { private final RandomPatternFunction function = new RandomPatternFunction(); @@ -48,18 +49,18 @@ public void testExecuteWithValidPattern() { @Test(expectedExceptions = IllegalArgumentException.class) public void testExecuteWithInvalidPattern() { - String pattern = "[0-3]([a-c]|[e-g]{1"; // Invalid regex pattern with "Character range is out of order" + String pattern = "[0-3]([a-c]|[e-g]{1"; // Invalid regex pattern with "Character range is out of order" function.execute(List.of(pattern), context); } @DataProvider(name = "patternProvider") public Object[][] patternProvider() { return new Object[][]{ - {"testExecuteWithComplexPattern", "(foo|bar)[0-9]{2,4}"}, - {"testIpv6", "(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))"}, - {"testIpv4", "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}"}, - {"testEmail", "[a-z]{5,15}\\.?[a-z]{5,15}\\@[a-z]{5,15}\\.[a-z]{2}"}, - {"testUri", "((http|https)://[a-zA-Z0-9-]+(\\.[a-zA-Z]{2,})+(/[a-zA-Z0-9-]+){1,6})|(file:///[a-zA-Z0-9-]+(/[a-zA-Z0-9-]+){1,6})"} + {"testExecuteWithComplexPattern", "(foo|bar)[0-9]{2,4}"}, + {"testIpv6", "(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))"}, + {"testIpv4", "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}"}, + {"testEmail", "[a-z]{5,15}\\.?[a-z]{5,15}\\@[a-z]{5,15}\\.[a-z]{2}"}, + {"testUri", "((http|https)://[a-zA-Z0-9-]+(\\.[a-zA-Z]{2,})+(/[a-zA-Z0-9-]+){1,6})|(file:///[a-zA-Z0-9-]+(/[a-zA-Z0-9-]+){1,6})"} }; } @@ -70,6 +71,4 @@ public void testPatterns(String description, String pattern) { assertTrue(result.matches(pattern), "Generated string does not match the pattern: " + description); } } - - } diff --git a/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomStringFunctionTest.java b/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomStringFunctionTest.java index 381adc2825..042b54f42d 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomStringFunctionTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/functions/core/RandomStringFunctionTest.java @@ -16,16 +16,16 @@ package org.citrusframework.functions.core; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import java.util.Set; import org.citrusframework.UnitTestSupport; import org.citrusframework.exceptions.InvalidFunctionUsageException; import org.testng.Assert; import org.testng.annotations.Test; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; @@ -138,6 +138,5 @@ public void testRandomSize() { Assert.assertTrue(sizes.contains(8)); Assert.assertTrue(sizes.contains(9)); Assert.assertTrue(sizes.contains(10)); - } -} \ No newline at end of file +} diff --git a/core/citrus-base/src/test/java/org/citrusframework/message/DefaultMessageStoreTest.java b/core/citrus-base/src/test/java/org/citrusframework/message/DefaultMessageStoreTest.java index b0faa45f93..3ffee9bf36 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/message/DefaultMessageStoreTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/message/DefaultMessageStoreTest.java @@ -31,14 +31,14 @@ public class DefaultMessageStoreTest extends UnitTestSupport { private final MessageStore messageStore = new DefaultMessageStore(); @Test - public void testStoreAndGetMessage() throws Exception { + public void testStoreAndGetMessage() { messageStore.storeMessage("request", new DefaultMessage("RequestMessage")); Assert.assertEquals(messageStore.getMessage("request").getPayload(String.class), "RequestMessage"); Assert.assertNull(messageStore.getMessage("unknown")); } @Test - public void testConstructMessageName() throws Exception { + public void testConstructMessageName() { Endpoint endpoint = new DirectEndpoint(); endpoint.setName("testEndpoint"); Assert.assertEquals(messageStore.constructMessageName(new SendMessageAction.Builder().build(), endpoint), "send(testEndpoint)"); diff --git a/core/citrus-base/src/test/java/org/citrusframework/message/correlation/PollingCorrelationManagerTest.java b/core/citrus-base/src/test/java/org/citrusframework/message/correlation/PollingCorrelationManagerTest.java index f816e321e6..d0d10e2e0a 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/message/correlation/PollingCorrelationManagerTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/message/correlation/PollingCorrelationManagerTest.java @@ -29,7 +29,7 @@ public class PollingCorrelationManagerTest { private ObjectStore objectStore = Mockito.mock(ObjectStore.class); @Test - public void testFind() throws Exception { + public void testFind() { DirectSyncEndpointConfiguration pollableEndpointConfiguration = new DirectSyncEndpointConfiguration(); pollableEndpointConfiguration.setPollingInterval(100L); pollableEndpointConfiguration.setTimeout(500L); diff --git a/core/citrus-base/src/test/java/org/citrusframework/report/LoggingReporterTest.java b/core/citrus-base/src/test/java/org/citrusframework/report/LoggingReporterTest.java index ba0454c366..1776f373b0 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/report/LoggingReporterTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/report/LoggingReporterTest.java @@ -16,9 +16,6 @@ package org.citrusframework.report; -import java.time.Duration; -import java.util.Locale; - import org.citrusframework.DefaultTestCase; import org.citrusframework.actions.EchoAction; import org.citrusframework.exceptions.CitrusRuntimeException; @@ -29,6 +26,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.time.Duration; +import java.util.Locale; + import static java.lang.String.format; import static org.citrusframework.TestResult.failed; import static org.citrusframework.TestResult.skipped; diff --git a/core/citrus-base/src/test/java/org/citrusframework/report/MessageTracingTestListenerTest.java b/core/citrus-base/src/test/java/org/citrusframework/report/MessageTracingTestListenerTest.java index 9239cc659a..798aba387d 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/report/MessageTracingTestListenerTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/report/MessageTracingTestListenerTest.java @@ -16,10 +16,6 @@ package org.citrusframework.report; -import java.io.File; -import java.io.IOException; -import java.util.Scanner; - import org.citrusframework.TestCase; import org.citrusframework.UnitTestSupport; import org.citrusframework.message.RawMessage; @@ -27,6 +23,10 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.io.File; +import java.io.IOException; +import java.util.Scanner; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -43,13 +43,13 @@ public void setupTestling() { } @Test - public void shouldReturnTheSameTraceFile() throws Exception { + public void shouldReturnTheSameTraceFile() { String testname = "SomeDummyTest"; Assert.assertEquals(testling.getTraceFile(testname).getAbsolutePath(), testling.getTraceFile(testname).getAbsolutePath()); } @Test - public void shouldContainMessages() throws Exception { + public void shouldContainMessages() { String testname = "SomeDummyTest"; String inboundPayload = "Inbound Message"; String outboundPayload = "Outbound Message"; diff --git a/core/citrus-base/src/test/java/org/citrusframework/util/FileUtilsTest.java b/core/citrus-base/src/test/java/org/citrusframework/util/FileUtilsTest.java index 2b4da6f619..6c52d67422 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/util/FileUtilsTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/util/FileUtilsTest.java @@ -16,20 +16,20 @@ package org.citrusframework.util; -import java.nio.charset.StandardCharsets; - import org.citrusframework.CitrusSettings; import org.citrusframework.UnitTestSupport; import org.citrusframework.spi.Resource; import org.testng.Assert; import org.testng.annotations.Test; +import java.nio.charset.StandardCharsets; + /** * @since 2.7 */ public class FileUtilsTest extends UnitTestSupport { @Test - public void testGetFileResource() throws Exception { + public void testGetFileResource() { Resource resource = FileUtils.getFileResource("classpath:citrus-context.xml", context); Assert.assertNotNull(resource); @@ -37,7 +37,7 @@ public void testGetFileResource() throws Exception { } @Test - public void testGetFileResourceExplicitCharset() throws Exception { + public void testGetFileResourceExplicitCharset() { Resource resource = FileUtils.getFileResource("classpath:citrus-context.xml" + FileUtils.FILE_PATH_CHARSET_PARAMETER + "ISO-8859-1", context); Assert.assertNotNull(resource); @@ -45,13 +45,13 @@ public void testGetFileResourceExplicitCharset() throws Exception { } @Test - public void testGetCharset() throws Exception { + public void testGetCharset() { Assert.assertEquals(FileUtils.getCharset("/path/to/some/file.txt").displayName(), CitrusSettings.CITRUS_FILE_ENCODING); Assert.assertEquals(FileUtils.getCharset("/path/to/some/file.txt" + FileUtils.FILE_PATH_CHARSET_PARAMETER + "ISO-8859-1"), StandardCharsets.ISO_8859_1); } @Test - public void testGetBaseName() throws Exception { + public void testGetBaseName() { Assert.assertNull(FileUtils.getBaseName(null)); Assert.assertEquals(FileUtils.getBaseName(""), ""); Assert.assertEquals(FileUtils.getBaseName("foo"), "foo"); @@ -61,7 +61,7 @@ public void testGetBaseName() throws Exception { } @Test - public void testGetFileName() throws Exception { + public void testGetFileName() { Assert.assertEquals(FileUtils.getFileName(null), ""); Assert.assertEquals(FileUtils.getFileName(""), ""); Assert.assertEquals(FileUtils.getFileName("foo"), "foo"); diff --git a/core/citrus-base/src/test/java/org/citrusframework/util/InvocationDummy.java b/core/citrus-base/src/test/java/org/citrusframework/util/InvocationDummy.java index 8cf2d5e467..be758c3205 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/util/InvocationDummy.java +++ b/core/citrus-base/src/test/java/org/citrusframework/util/InvocationDummy.java @@ -27,44 +27,34 @@ public class InvocationDummy { private static final Logger logger = LoggerFactory.getLogger(InvocationDummy.class); public InvocationDummy() { - if (logger.isDebugEnabled()) { - logger.debug("Constructor without argument"); - } + logger.debug("Constructor without argument"); } public InvocationDummy(String arg) { - if (logger.isDebugEnabled()) { - logger.debug("Constructor with argument: " + arg); - } + logger.debug("Constructor with argument: {}", arg); } public InvocationDummy(Integer arg1, String arg2, Boolean arg3) { if (logger.isDebugEnabled()) { - if (logger.isDebugEnabled()) { - logger.debug("Constructor with arguments:"); - logger.debug("arg1: " + arg1); - logger.debug("arg2: " + arg2); - logger.debug("arg3: " + arg3); - } + logger.debug("Constructor with arguments:"); + logger.debug("arg1: {}", arg1); + logger.debug("arg2: {}", arg2); + logger.debug("arg3: {}", arg3); } } public void invoke() { - if (logger.isDebugEnabled()) { - logger.debug("Methode invoke no arguments"); - } + logger.debug("Methode invoke no arguments"); } public void invoke(String text) { - if (logger.isDebugEnabled()) { - logger.debug("Methode invoke with string argument: '" + text + "'"); - } + logger.debug("Methode invoke with string argument: '{}'", text); } public void invoke(String[] args) { - for (var arg : args) { - if (logger.isDebugEnabled()) { - logger.debug("Methode invoke with argument: " + arg); + if (logger.isDebugEnabled()) { + for (var arg : args) { + logger.debug("Methode invoke with argument: {}", arg); } } } @@ -72,16 +62,16 @@ public void invoke(String[] args) { public void invoke(Integer arg1, String arg2, Boolean arg3) { if (logger.isDebugEnabled()) { logger.debug("Method invoke with arguments:"); - logger.debug("arg1: " + arg1); - logger.debug("arg2: " + arg2); - logger.debug("arg3: " + arg3); + logger.debug("arg1: {}", arg1); + logger.debug("arg2: {}", arg2); + logger.debug("arg3: {}", arg3); } } public static void main(String[] args) { - for (int i = 0; i < args.length; i++) { - if (logger.isDebugEnabled()) { - logger.debug("arg" + i + ": " + args[i]); + if (logger.isDebugEnabled()) { + for (String arg : args) { + logger.debug("arg{}: ", arg); } } } diff --git a/core/citrus-base/src/test/java/org/citrusframework/util/StringUtilsTest.java b/core/citrus-base/src/test/java/org/citrusframework/util/StringUtilsTest.java index 4d0e99f494..1fa884bb54 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/util/StringUtilsTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/util/StringUtilsTest.java @@ -1,5 +1,8 @@ package org.citrusframework.util; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + import static org.citrusframework.util.StringUtils.hasText; import static org.citrusframework.util.StringUtils.isEmpty; import static org.citrusframework.util.StringUtils.quote; @@ -9,9 +12,6 @@ import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - public class StringUtilsTest { @DataProvider @@ -38,6 +38,7 @@ public void hasText_returnsTrue(String str) { public void hasText_returnsFalse_forBlankText(String str) { assertFalse(hasText(str)); } + @Test(dataProvider = "emptyText") public void hasText_returnsFalse_forEmptyText(String str) { assertFalse(hasText(str)); @@ -124,13 +125,13 @@ public void testQuoteNullStringFalse() { @DataProvider(name = "trimTrailingCommaDataProvider") public Object[][] trimTrailingCommaDataProvider() { return new Object[][]{ - {new StringBuilder("Example text, "), "Example text"}, - {new StringBuilder("No trailing comma "), "No trailing comma"}, - {new StringBuilder("No trailing comma,\n\t\n "), "No trailing comma"}, - {new StringBuilder("Trailing comma,"), "Trailing comma"}, - {new StringBuilder("Multiple commas and spaces,,, "), "Multiple commas and spaces,,"}, - {new StringBuilder("No trim needed"), "No trim needed"}, - {new StringBuilder(), ""} + {new StringBuilder("Example text, "), "Example text"}, + {new StringBuilder("No trailing comma "), "No trailing comma"}, + {new StringBuilder("No trailing comma,\n\t\n "), "No trailing comma"}, + {new StringBuilder("Trailing comma,"), "Trailing comma"}, + {new StringBuilder("Multiple commas and spaces,,, "), "Multiple commas and spaces,,"}, + {new StringBuilder("No trim needed"), "No trim needed"}, + {new StringBuilder(), ""} }; } @@ -163,25 +164,24 @@ public void testTrimTrailingCommaWithNull() { } @DataProvider(name = "titleCaseData") - public Object[][] titleCaseData() { + public Object[][] convertFirstChartToUpperCaseData() { return new Object[][]{ - {"hello", "Hello"}, - {"h", "H"}, - {"Hello", "Hello"}, - {null, ""}, - {"", ""}, - {"hello world", "Hello world"}, - {" hello", " hello"}, - {"1test", "1test"}, - {"!special", "!special"} + {"hello", "Hello"}, + {"h", "H"}, + {"Hello", "Hello"}, + {null, ""}, + {"", ""}, + {"hello world", "Hello world"}, + {" hello", " hello"}, + {"1test", "1test"}, + {"!special", "!special"} }; } - @Test(dataProvider = "titleCaseData") - public void testTitleCase(String input, String expected) { - String actual = StringUtils.titleCase(input); + @Test(dataProvider = "convertFirstChartToUpperCaseData") + public void testConvertFirstChartToUpperCase(String input, String expected) { + String actual = StringUtils.convertFirstChartToUpperCase(input); assertEquals(actual, expected, - "The titleCase method did not return the expected result."); + "The titleCase method did not return the expected result."); } - } diff --git a/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultMessageHeaderValidatorTest.java b/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultMessageHeaderValidatorTest.java index a23f8f800c..234d9457a5 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultMessageHeaderValidatorTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultMessageHeaderValidatorTest.java @@ -32,7 +32,7 @@ public class DefaultMessageHeaderValidatorTest extends UnitTestSupport { private HeaderValidationContext validationContext = new HeaderValidationContext(); @Test - public void testValidateNoMessageHeaders() throws Exception { + public void testValidateNoMessageHeaders() { Message receivedMessage = new DefaultMessage("Hello World!"); Message controlMessage = new DefaultMessage("Hello World!"); @@ -40,7 +40,7 @@ public void testValidateNoMessageHeaders() throws Exception { } @Test - public void testValidateMessageHeaders() throws Exception { + public void testValidateMessageHeaders() { Message receivedMessage = new DefaultMessage("Hello World!") .setHeader("foo", "foo_test") .setHeader("additional", "additional") @@ -53,7 +53,7 @@ public void testValidateMessageHeaders() throws Exception { } @Test - public void testValidateMessageHeadersIgnoreCase() throws Exception { + public void testValidateMessageHeadersIgnoreCase() { try { Message receivedMessage = new DefaultMessage("Hello World!") .setHeader("X-Foo", "foo_test") @@ -71,7 +71,7 @@ public void testValidateMessageHeadersIgnoreCase() throws Exception { } @Test(expectedExceptions = ValidationException.class) - public void testValidateMessageHeadersIgnoreCaseError() throws Exception { + public void testValidateMessageHeadersIgnoreCaseError() { Message receivedMessage = new DefaultMessage("Hello World!") .setHeader("X-Foo", "foo_test") .setHeader("X-Additional", "additional") @@ -84,7 +84,7 @@ public void testValidateMessageHeadersIgnoreCaseError() throws Exception { } @Test - public void testValidateMessageHeadersVariableSupport() throws Exception { + public void testValidateMessageHeadersVariableSupport() { Message receivedMessage = new DefaultMessage("Hello World!") .setHeader("foo", "foo_test") .setHeader("additional", "additional") @@ -99,7 +99,7 @@ public void testValidateMessageHeadersVariableSupport() throws Exception { } @Test - public void testValidateMessageHeadersMatcherSupport() throws Exception { + public void testValidateMessageHeadersMatcherSupport() { Message receivedMessage = new DefaultMessage("Hello World!") .setHeader("foo", "foo_test") .setHeader("additional", "additional") @@ -112,7 +112,7 @@ public void testValidateMessageHeadersMatcherSupport() throws Exception { } @Test(expectedExceptions = ValidationException.class) - public void testValidateError() throws Exception { + public void testValidateError() { Message receivedMessage = new DefaultMessage("Hello World!") .setHeader("foo", "other_value") .setHeader("bar", "bar_test"); @@ -124,7 +124,7 @@ public void testValidateError() throws Exception { } @Test(expectedExceptions = ValidationException.class) - public void testValidateErrorMissingHeader() throws Exception { + public void testValidateErrorMissingHeader() { Message receivedMessage = new DefaultMessage("Hello World!") .setHeader("bar", "bar_test"); Message controlMessage = new DefaultMessage("Hello World!") diff --git a/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultTextEqualsMessageValidatorTest.java b/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultTextEqualsMessageValidatorTest.java index 30b947de8b..2102b7998c 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultTextEqualsMessageValidatorTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/validation/DefaultTextEqualsMessageValidatorTest.java @@ -16,8 +16,6 @@ package org.citrusframework.validation; -import java.nio.charset.StandardCharsets; - import org.citrusframework.UnitTestSupport; import org.citrusframework.exceptions.ValidationException; import org.citrusframework.message.DefaultMessage; @@ -27,6 +25,8 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.nio.charset.StandardCharsets; + public class DefaultTextEqualsMessageValidatorTest extends UnitTestSupport { private final DefaultTextEqualsMessageValidator validator = new DefaultTextEqualsMessageValidator(); @@ -41,7 +41,7 @@ public void testValidate(Object received, Object control) { } @Test(dataProvider = "errorTests", expectedExceptions = ValidationException.class) - public void testValidateError(Object received, Object control) throws Exception { + public void testValidateError(Object received, Object control) { Message receivedMessage = new DefaultMessage(received); Message controlMessage = new DefaultMessage(control); diff --git a/core/citrus-base/src/test/java/org/citrusframework/validation/MessageValidatorRegistryTest.java b/core/citrus-base/src/test/java/org/citrusframework/validation/MessageValidatorRegistryTest.java index a3edb691a2..cd5803a860 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/validation/MessageValidatorRegistryTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/validation/MessageValidatorRegistryTest.java @@ -16,11 +16,6 @@ package org.citrusframework.validation; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.message.DefaultMessage; import org.citrusframework.message.Message; @@ -34,6 +29,11 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -118,7 +118,7 @@ public void setupMocks() { } @Test - public void testFindMessageValidators() throws Exception { + public void testFindMessageValidators() { MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorRegistry(); Map> messageValidators = new HashMap<>(); @@ -161,7 +161,7 @@ public void testFindMessageValidators() throws Exception { } @Test - public void testMessageValidatorRegistryXmlConfig() throws Exception { + public void testMessageValidatorRegistryXmlConfig() { //non XML message type List> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage("")); @@ -193,7 +193,7 @@ public void testMessageValidatorRegistryXmlConfig() throws Exception { } @Test - public void testMessageValidatorRegistryJsonConfig() throws Exception { + public void testMessageValidatorRegistryJsonConfig() { //JSON message type and empty payload List> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage("")); @@ -216,7 +216,7 @@ public void testMessageValidatorRegistryJsonConfig() throws Exception { } @Test - public void testMessageValidatorRegistryPlaintextConfig() throws Exception { + public void testMessageValidatorRegistryPlaintextConfig() { //Plaintext message type and empty payload List> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage("")); @@ -237,7 +237,7 @@ public void testMessageValidatorRegistryPlaintextConfig() throws Exception { } @Test - public void testMessageValidatorRegistryFallback() throws Exception { + public void testMessageValidatorRegistryFallback() { List> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage("{ \"id\": 12345 }")); Assert.assertNotNull(matchingValidators); @@ -339,7 +339,7 @@ public void shouldAddDefaultEmptyMessagePayloadValidator() { } @Test - public void testSchemaValidators() throws Exception { + public void testSchemaValidators() { MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorRegistry(); Map> schemaValidators = new HashMap<>(); diff --git a/core/citrus-base/src/test/java/org/citrusframework/validation/ValidationUtilsTest.java b/core/citrus-base/src/test/java/org/citrusframework/validation/ValidationUtilsTest.java index 2d8fe154fe..0160f1dade 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/validation/ValidationUtilsTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/validation/ValidationUtilsTest.java @@ -16,10 +16,6 @@ package org.citrusframework.validation; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import org.citrusframework.UnitTestSupport; import org.citrusframework.context.TestContext; import org.citrusframework.context.TestContextFactory; @@ -29,6 +25,10 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import static org.citrusframework.validation.ValidationUtils.buildValueToBeInCollectionErrorMessage; import static org.testng.Assert.assertEquals; @@ -45,17 +45,17 @@ protected TestContextFactory createTestContextFactory() { } @Test(dataProvider = "testData") - public void testValidateValues(Object actualValue, Object expectedValue, String path) throws Exception { + public void testValidateValues(Object actualValue, Object expectedValue, String path) { ValidationUtils.validateValues(actualValue, expectedValue, path, context); } @Test(dataProvider = "testDataFailed", expectedExceptions = ValidationException.class) - public void testValidateValuesFailure(Object actualValue, Object expectedValue, String path) throws Exception { + public void testValidateValuesFailure(Object actualValue, Object expectedValue, String path) { ValidationUtils.validateValues(actualValue, expectedValue, path, context); } @Test(dataProvider = "testDataTypeFailed", expectedExceptions = ValidationException.class) - public void testValidateValuesTypeFailure(String actualValue, Object expectedValue, String path) throws Exception { + public void testValidateValuesTypeFailure(String actualValue, Object expectedValue, String path) { ValidationUtils.validateValues(actualValue, expectedValue, path, context); } diff --git a/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/BinaryMessageProcessorTest.java b/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/BinaryMessageProcessorTest.java index 701b897f53..bf99d1fb68 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/BinaryMessageProcessorTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/BinaryMessageProcessorTest.java @@ -16,9 +16,6 @@ package org.citrusframework.validation.interceptor; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - import org.citrusframework.UnitTestSupport; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.message.DefaultMessage; @@ -28,6 +25,8 @@ import org.citrusframework.util.FileUtils; import org.testng.annotations.Test; +import java.nio.charset.StandardCharsets; + import static org.testng.Assert.assertEquals; public class BinaryMessageProcessorTest extends UnitTestSupport { @@ -64,7 +63,7 @@ public void testTextMessageIsIntercepted(){ } @Test - public void testResourceMessageWithIsIntercepted() throws IOException { + public void testResourceMessageWithIsIntercepted() { //GIVEN final DefaultMessage message = new DefaultMessage(getTestFile()); diff --git a/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/GzipMessageProcessorTest.java b/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/GzipMessageProcessorTest.java index 0a9092bf0b..fa5fb4a058 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/GzipMessageProcessorTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/validation/interceptor/GzipMessageProcessorTest.java @@ -16,13 +16,6 @@ package org.citrusframework.validation.interceptor; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - import org.citrusframework.UnitTestSupport; import org.citrusframework.exceptions.CitrusRuntimeException; import org.citrusframework.message.DefaultMessage; @@ -33,6 +26,13 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + import static org.testng.Assert.assertEquals; public class GzipMessageProcessorTest extends UnitTestSupport { @@ -71,7 +71,7 @@ public void testTextMessageIsIntercepted() throws IOException { //THEN assertEquals(message.getType(), MessageType.GZIP.name()); try (ByteArrayOutputStream unzipped = new ByteArrayOutputStream(); - GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)));) { + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)))) { unzipped.write(gzipInputStream.readAllBytes()); Assert.assertEquals(unzipped.toByteArray(), "foo".getBytes(StandardCharsets.UTF_8)); } @@ -90,7 +90,7 @@ public void testBinaryMessageIsIntercepted() throws IOException { //THEN assertEquals(message.getType(), MessageType.GZIP.name()); try (ByteArrayOutputStream unzipped = new ByteArrayOutputStream(); - GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)));) { + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)))) { unzipped.write(gzipInputStream.readAllBytes()); Assert.assertEquals(unzipped.toByteArray(), "foo".getBytes(StandardCharsets.UTF_8)); } @@ -109,7 +109,7 @@ public void testInputStreamMessageIsIntercepted() throws IOException { //THEN assertEquals(message.getType(), MessageType.GZIP.name()); try (ByteArrayOutputStream unzipped = new ByteArrayOutputStream(); - GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)));) { + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)))) { unzipped.write(gzipInputStream.readAllBytes()); Assert.assertEquals(unzipped.toByteArray(), "foo".getBytes(StandardCharsets.UTF_8)); } @@ -128,7 +128,7 @@ public void testResourceMessageIsIntercepted() throws IOException { //THEN assertEquals(message.getType(), MessageType.GZIP.name()); try (ByteArrayOutputStream unzipped = new ByteArrayOutputStream(); - GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)));) { + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(message.getPayload(byte[].class)))) { unzipped.write(gzipInputStream.readAllBytes()); Assert.assertEquals(unzipped.toByteArray(), FileUtils.copyToByteArray(getTestFile().getInputStream())); } diff --git a/test-api-generator/citrus-test-api-generator-core/src/main/java/org/citrusframework/openapi/generator/CitrusJavaCodegen.java b/test-api-generator/citrus-test-api-generator-core/src/main/java/org/citrusframework/openapi/generator/CitrusJavaCodegen.java index f3f685ca46..024ac58f44 100644 --- a/test-api-generator/citrus-test-api-generator-core/src/main/java/org/citrusframework/openapi/generator/CitrusJavaCodegen.java +++ b/test-api-generator/citrus-test-api-generator-core/src/main/java/org/citrusframework/openapi/generator/CitrusJavaCodegen.java @@ -59,7 +59,7 @@ import static java.util.stream.Collectors.toMap; import static org.citrusframework.util.ReflectionHelper.copyFields; import static org.citrusframework.util.StringUtils.appendSegmentToUrlPath; -import static org.citrusframework.util.StringUtils.titleCase; +import static org.citrusframework.util.StringUtils.convertFirstChartToUpperCase; import static org.openapitools.codegen.CliOption.newString; import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER; import static org.openapitools.codegen.utils.StringUtils.camelize; @@ -377,7 +377,7 @@ private void addRestSupportingFiles(String springFolder, String schemaFolder) { supportingFiles.add(new SupportingFile("namespace_handler.mustache", springFolder, - titleCase(apiPrefix) + "NamespaceHandler.java")); + convertFirstChartToUpperCase(apiPrefix) + "NamespaceHandler.java")); supportingFiles.add(new SupportingFile("schema.mustache", schemaFolder, apiPrefix.toLowerCase() + "-api.xsd")); } @@ -388,16 +388,16 @@ private void addSoapSupportingFiles(String springFolder, String schemaFolder) { apiTemplateFiles().put("api_soap.mustache", ".java"); supportingFiles.add(new SupportingFile("namespace_handler_soap.mustache", springFolder, - titleCase(apiPrefix) + "NamespaceHandler.java")); + convertFirstChartToUpperCase(apiPrefix) + "NamespaceHandler.java")); supportingFiles.add(new SupportingFile("schema_soap.mustache", schemaFolder, apiPrefix.toLowerCase() + "-api.xsd")); } private void addDefaultSupportingFiles() { supportingFiles.add(new SupportingFile("api_locator.mustache", invokerFolder, - titleCase(apiPrefix) + ".java")); + convertFirstChartToUpperCase(apiPrefix) + ".java")); supportingFiles.add(new SupportingFile("bean_configuration.mustache", springFolder, - titleCase(apiPrefix) + "BeanConfiguration.java")); + convertFirstChartToUpperCase(apiPrefix) + "BeanConfiguration.java")); } @Override