Skip to content

Commit

Permalink
#997: Replace Optional.orElse() with Optional.orElseGet() to evaluate…
Browse files Browse the repository at this point in the history
… non-static values lazily
  • Loading branch information
picimako committed Sep 25, 2023
1 parent fe79133 commit 40eb7fa
Show file tree
Hide file tree
Showing 39 changed files with 71 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ private Ports getPortBindings(String portSpecs, ExposedPort[] exposedPorts, Test
Integer hostPort = Integer.valueOf(binding[0]);
Integer port = Integer.valueOf(binding[1]);

portsBindings.bind(Stream.of(exposedPorts).filter(exposed -> port.equals(exposed.getPort())).findAny().orElse(ExposedPort.tcp(port)), Ports.Binding.bindPort(hostPort));
portsBindings.bind(Stream.of(exposedPorts).filter(exposed -> port.equals(exposed.getPort())).findAny().orElseGet(() -> ExposedPort.tcp(port)), Ports.Binding.bindPort(hostPort));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public final void doExecute(TestContext context) {
public boolean isDone(TestContext context) {
return Optional.ofNullable(finished)
.map(future -> future.isDone() || isDisabled(context))
.orElse(isDisabled(context));
.orElseGet(() -> isDisabled(context));
}

public abstract void doExecuteAsync(TestContext context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public InputAction(Builder builder) {
this.message = builder.message;
this.variable = builder.variable;
this.validAnswers = builder.validAnswers;
this.inputReader = Optional.ofNullable(builder.inputReader).orElse(new BufferedReader(new InputStreamReader(System.in)));
this.inputReader = Optional.ofNullable(builder.inputReader).orElseGet(() -> new BufferedReader(new InputStreamReader(System.in)));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public boolean isDisabled(TestContext context) {
public boolean isDone(TestContext context) {
return Optional.ofNullable(finished)
.map(future -> future.isDone() || isDisabled(context))
.orElse(isDisabled(context));
.orElseGet(() -> isDisabled(context));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public boolean isSatisfied(TestContext context) {
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)
.orElse(e.getClass().getName())));
.orElseGet(() -> e.getClass().getName())));
return false;
}

Expand All @@ -82,7 +82,7 @@ public String getErrorMessage(TestContext context) {
if (caughtException != null) {
return String.format("Failed to check test action condition - action '%s' did not perform as expected: %s", getActionName(), Optional.ofNullable(caughtException.getMessage())
.map(msg -> caughtException.getClass().getName() + ": " + msg)
.orElse(caughtException.getClass().getName()));
.orElseGet(() -> caughtException.getClass().getName()));
} else {
return String.format("Failed to check test action condition - action '%s' did not perform as expected", getActionName());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public boolean isDone(TestContext context) {
if (action instanceof Completable && !((Completable) action).isDone(context)) {
if (logger.isDebugEnabled()) {
logger.debug(Optional.ofNullable(action.getName()).filter(name -> name.trim().length() > 0)
.orElse(action.getClass().getName()) + " not completed yet");
.orElseGet(() -> action.getClass().getName()) + " not completed yet");
}
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ protected void onBuild() {
if (referenceResolver != null && templateName != null) {
Template rootTemplate = referenceResolver.resolve(templateName, Template.class);
globalContext(rootTemplate.isGlobalContext() && globalContext);
actor(Optional.ofNullable(getActor()).orElse(rootTemplate.getActor()));
actor(Optional.ofNullable(getActor()).orElseGet(rootTemplate::getActor));
Map<String, String> mergedParameters = new LinkedHashMap<>();
mergedParameters.putAll(rootTemplate.getParameter());
mergedParameters.putAll(parameter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public Entry(String name, File file) throws IOException {
this(name);

if (file.isDirectory()) {
for (File child : Optional.ofNullable(file.listFiles()).orElse(new File[] {})) {
for (File child : Optional.ofNullable(file.listFiles()).orElseGet(() -> new File[] {})) {
entries.add(new Entry(child));
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public boolean accept(Message message) {
.allMatch(entry -> factories.stream()
.filter(factory -> factory.supports(entry.getKey()))
.findAny()
.orElse(new HeaderMatchingMessageSelector.Factory())
.orElseGet(HeaderMatchingMessageSelector.Factory::new)
.create(entry.getKey(), entry.getValue(), context)
.accept(message));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public String getReportContent(TestResults testResults) {
final String emptyString = "";

testResults.doWithResults(result -> {
ResultDetail detail = Optional.ofNullable(details.get(result.getTestName())).orElse(new ResultDetail());
ResultDetail detail = Optional.ofNullable(details.get(result.getTestName())).orElseGet(ResultDetail::new);

Properties detailProps = new Properties();
detailProps.put("test.style.class", result.getResult().toLowerCase());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,13 @@ private String createReportContent(String suiteName, List<TestResult> results, R
detailProps.put("test.duration", "0.0");

if (result.isFailed()) {
detailProps.put("test.error.cause", Optional.ofNullable(result.getCause()).map(Object::getClass).map(Class::getName).orElse(Objects.toString(result.getFailureType(), "")));
detailProps.put("test.error.cause", Optional.ofNullable(result.getCause()).map(Object::getClass).map(Class::getName).orElseGet(() -> Objects.toString(result.getFailureType(), "")));
detailProps.put("test.error.msg", StringEscapeUtils.escapeXml(result.getErrorMessage()));
detailProps.put("test.error.stackTrace", Optional.ofNullable(result.getCause()).map(cause -> {
StringWriter writer = new StringWriter();
cause.printStackTrace(new PrintWriter(writer));
return writer.toString();
}).orElse(Objects.toString(result.getFailureType(), "")));
}).orElseGet(() -> Objects.toString(result.getFailureType(), "")));
reportDetails.append(System.lineSeparator())
.append(" ")
.append(PropertyUtils.replacePropertiesInString(templates.getFailedTemplate(), detailProps));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public static List<File> findFiles(final String startDir, final Set<String> file
return accepted && !name.startsWith("CVS") && !name.startsWith(".svn") && !name.startsWith(".git");
});

for (File found : Optional.ofNullable(foundFiles).orElse(new File[] {})) {
for (File found : Optional.ofNullable(foundFiles).orElseGet(() -> new File[] {})) {
/* Subfolder support */
if (found.isDirectory()) {
dirs.push(found);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public void validateMessage(Message receivedMessage, Message controlMessage, Tes
.stream()
.filter(validator -> validator.supports(headerName, Optional.ofNullable(controlValue).map(Object::getClass).orElse(null)))
.findFirst()
.orElse(
.orElseGet(() ->
validationContext.getValidatorNames()
.stream()
.map(beanName -> {
Expand All @@ -97,11 +97,11 @@ public void validateMessage(Message receivedMessage, Message controlMessage, Tes
.filter(Objects::nonNull)
.filter(validator -> validator.supports(headerName, Optional.ofNullable(controlValue).map(Object::getClass).orElse(null)))
.findFirst()
.orElse(
.orElseGet(() ->
getHeaderValidators(context).stream()
.filter(validator -> validator.supports(headerName, Optional.ofNullable(controlValue).map(Object::getClass).orElse(null)))
.findFirst()
.orElse(new DefaultHeaderValidator())
.orElseGet(DefaultHeaderValidator::new)
)
).validateHeader(headerName, receivedHeaders.get(headerName), controlValue, context, validationContext);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ protected FtpMessage storeFile(PutCommand command, TestContext context) {
String localFilePath = context.replaceDynamicContentInString(command.getFile().getPath());
String remoteFilePath = addFileNameToTargetPath(localFilePath, context.replaceDynamicContentInString(command.getTarget().getPath()));

String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElse(DataType.BINARY.name()));
String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElseGet(() -> DataType.BINARY.name()));
try (InputStream localFileInputStream = getLocalFileInputStream(command.getFile().getPath(), dataType, context)) {
ftpClient.setFileType(getFileType(dataType));

Expand Down Expand Up @@ -330,7 +330,7 @@ protected FtpMessage retrieveFile(GetCommand command, TestContext context) {
Files.createDirectories(Paths.get(localFilePath).getParent());
}

String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElse(DataType.BINARY.name()));
String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElseGet(() -> DataType.BINARY.name()));
try (FileOutputStream localFileOutputStream = new FileOutputStream(localFilePath)) {
ftpClient.setFileType(getFileType(dataType));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ protected FtpMessage storeFile(PutCommand command, TestContext context) {
String localFilePath = context.replaceDynamicContentInString(command.getFile().getPath());
String remoteFilePath = addFileNameToTargetPath(localFilePath, context.replaceDynamicContentInString(command.getTarget().getPath()));

String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElse(DataType.BINARY.name()));
String dataType = context.replaceDynamicContentInString(Optional.ofNullable(command.getFile().getType()).orElseGet(() -> DataType.BINARY.name()));
try (InputStream localFileInputStream = getLocalFileInputStream(command.getFile().getPath(), dataType, context)) {
sftp.put(localFileInputStream, remoteFilePath);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public FtpMessage handleMessage(FtpMessage request) {
return new FtpMessage(response);
}
})
.orElse(FtpMessage.success());
.orElseGet(FtpMessage::success);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public FtpMessage handleMessage(FtpMessage request) {
return new FtpMessage(response);
}
})
.orElse(FtpMessage.success());
.orElseGet(FtpMessage::success);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public HttpMessage queryParams(final String queryParamString) {
header(EndpointUriResolver.QUERY_PARAM_HEADER_NAME, queryParamString);

Stream.of(queryParamString.split(","))
.map(keyValue -> Optional.ofNullable(StringUtils.split(keyValue, "=")).orElse(new String[]{keyValue, ""}))
.map(keyValue -> Optional.ofNullable(StringUtils.split(keyValue, "=")).orElseGet(() -> new String[]{keyValue, ""}))
.filter(keyValue -> StringUtils.hasText(keyValue[0]))
.forEach(keyValue -> this.addQueryParam(keyValue[0], keyValue[1]));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ private Map<String, String> convertToMap(Object expression) {
.map(Object::toString)
.orElse("")
.split(","))
.map(keyValue -> Optional.ofNullable(StringUtils.split(keyValue, "=")).orElse(new String[] {keyValue, ""}))
.map(keyValue -> Optional.ofNullable(StringUtils.split(keyValue, "=")).orElseGet(() -> new String[] {keyValue, ""}))
.collect(Collectors.toMap(keyValue -> keyValue[0], keyValue -> keyValue[1]));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public JmsTopicSubscriber(String name, JmsEndpointConfiguration endpointConfigur
*/
public void run() {
ConnectionFactory connectionFactory = Optional.ofNullable(endpointConfiguration.getConnectionFactory())
.orElse(endpointConfiguration.getJmsTemplate().getConnectionFactory());
.orElseGet(() -> endpointConfiguration.getJmsTemplate().getConnectionFactory());

TopicConnection connection = null;
try {
Expand Down Expand Up @@ -118,8 +118,8 @@ public void run() {

TopicSubscriber subscriber;
if (endpointConfiguration.isDurableSubscription()) {
logger.debug(String.format("Create JMS topic durable subscription '%s'", Optional.ofNullable(endpointConfiguration.getDurableSubscriberName()).orElse(getName())));
subscriber = session.createDurableSubscriber(topic, Optional.ofNullable(endpointConfiguration.getDurableSubscriberName()).orElse(getName()));
logger.debug(String.format("Create JMS topic durable subscription '%s'", Optional.ofNullable(endpointConfiguration.getDurableSubscriberName()).orElseGet(this::getName)));
subscriber = session.createDurableSubscriber(topic, Optional.ofNullable(endpointConfiguration.getDurableSubscriberName()).orElseGet(this::getName));
} else {
logger.debug("Create JMS topic subscription");
subscriber = session.createSubscriber(topic);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ protected File createLogDir() {
File logDir = Optional.ofNullable(logDirPath)
.map(Paths::get)
.map(Path::toFile)
.orElse(new File(System.getProperty("java.io.tmpdir")));
.orElseGet(() -> new File(System.getProperty("java.io.tmpdir")));

if (!logDir.exists()) {
if (!logDir.mkdirs()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public void stop() {
*/
private org.apache.kafka.clients.consumer.KafkaConsumer<Object, Object> createConsumer() {
Map<String, Object> consumerProps = new HashMap<>();
consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, Optional.ofNullable(endpointConfiguration.getClientId()).orElse(KafkaMessageHeaders.KAFKA_PREFIX + "consumer_" + UUID.randomUUID().toString()));
consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, Optional.ofNullable(endpointConfiguration.getClientId()).orElseGet(() -> KafkaMessageHeaders.KAFKA_PREFIX + "consumer_" + UUID.randomUUID().toString()));
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, endpointConfiguration.getConsumerGroup());
consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Optional.ofNullable(endpointConfiguration.getServer()).orElse("localhost:9092"));
consumerProps.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void send(final Message message, final TestContext context) {
String topic = Optional.ofNullable(message.getHeader(KafkaMessageHeaders.TOPIC))
.map(Object::toString)
.map(context::replaceDynamicContentInString)
.orElse(context.replaceDynamicContentInString(endpointConfiguration.getTopic()));
.orElseGet(() -> context.replaceDynamicContentInString(endpointConfiguration.getTopic()));

if (!StringUtils.hasText(topic)) {
throw new CitrusRuntimeException(String.format("Invalid Kafka stream topic header %s - must not be empty or null", KafkaMessageHeaders.TOPIC));
Expand Down Expand Up @@ -105,7 +105,7 @@ private org.apache.kafka.clients.producer.KafkaProducer<Object, Object> createKa
producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, endpointConfiguration.getKeySerializer());
producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, endpointConfiguration.getValueSerializer());

producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, Optional.ofNullable(endpointConfiguration.getClientId()).orElse(KafkaMessageHeaders.KAFKA_PREFIX + "producer_" + UUID.randomUUID().toString()));
producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, Optional.ofNullable(endpointConfiguration.getClientId()).orElseGet(() -> KafkaMessageHeaders.KAFKA_PREFIX + "producer_" + UUID.randomUUID().toString()));

producerProps.putAll(endpointConfiguration.getProducerProperties());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ public ProducerRecord<Object, Object> convertOutbound(Message internalMessage, K
kafkaMessage = new KafkaMessage(internalMessage.getPayload(), internalMessage.getHeaders());
}

return new ProducerRecord<>(Optional.ofNullable(kafkaMessage.getTopic()).map(context::replaceDynamicContentInString).orElse(context.replaceDynamicContentInString(endpointConfiguration.getTopic())),
Optional.ofNullable(kafkaMessage.getPartition()).orElse(endpointConfiguration.getPartition()),
return new ProducerRecord<>(Optional.ofNullable(kafkaMessage.getTopic()).map(context::replaceDynamicContentInString).orElseGet(() -> context.replaceDynamicContentInString(endpointConfiguration.getTopic())),
Optional.ofNullable(kafkaMessage.getPartition()).orElseGet(endpointConfiguration::getPartition),
kafkaMessage.getMessageKey(),
payload,
endpointConfiguration.getHeaderMapper().toHeaders(kafkaMessage.getHeaders(), context));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public boolean accept(Message<?> message) {
.allMatch(entry -> factories.stream()
.filter(factory -> factory.supports(entry.getKey()))
.findAny()
.orElse(new HeaderMatchingMessageSelector.Factory())
.orElseGet(HeaderMatchingMessageSelector.Factory::new)
.create(entry.getKey(), entry.getValue(), context)
.accept(message));
}
Expand Down
Loading

0 comments on commit 40eb7fa

Please sign in to comment.