Skip to content

Commit

Permalink
Merge pull request #1001 from picimako/optional-fallback-lazy-evaluation
Browse files Browse the repository at this point in the history
#997: Replace Optional.orElse() with Optional.orElseGet()
  • Loading branch information
bbortt authored Oct 16, 2023
2 parents 7e53724 + 2825170 commit 9901320
Show file tree
Hide file tree
Showing 36 changed files with 68 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,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 @@ -77,7 +77,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 @@ -243,7 +243,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 @@ -341,7 +341,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 @@ -189,7 +189,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 @@ -71,7 +71,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 @@ -82,7 +82,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 @@ -232,7 +232,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 @@ -84,7 +84,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 @@ -98,11 +98,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 @@ -281,7 +281,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 @@ -329,7 +329,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 @@ -201,7 +201,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 @@ -90,7 +90,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 @@ -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 @@ -113,7 +113,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 @@ -73,7 +73,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 @@ -106,7 +106,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()));
producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, Optional.ofNullable(endpointConfiguration.getClientId()).orElseGet(() -> KafkaMessageHeaders.KAFKA_PREFIX + "producer_" + UUID.randomUUID()));

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
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ protected void startup() {
sshd.setPort(port);

VirtualFileSystemFactory fileSystemFactory = new VirtualFileSystemFactory();
Path userHomeDir = Optional.ofNullable(userHomePath).map(Paths::get).map(Path::toAbsolutePath).orElse(Paths.get(String.format("target/%s/home/%s", getName(), user)).toAbsolutePath());
Path userHomeDir = Optional.ofNullable(userHomePath).map(Paths::get).map(Path::toAbsolutePath).orElseGet(() -> Paths.get(String.format("target/%s/home/%s", getName(), user)).toAbsolutePath());

if (!Files.exists(userHomeDir)) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public WebServiceTemplate getWebServiceTemplate() {
* @param webServiceTemplate
*/
public void setWebServiceTemplate(WebServiceTemplate webServiceTemplate) {
interceptors.addAll(Optional.ofNullable(webServiceTemplate.getInterceptors()).map(Arrays::asList).orElse(Collections.emptyList()));
interceptors.addAll(Optional.ofNullable(webServiceTemplate.getInterceptors()).map(Arrays::asList).orElseGet(Collections::emptyList));
this.webServiceTemplate = webServiceTemplate;
webServiceTemplate.setInterceptors(interceptors.toArray(new ClientInterceptor[0]));
}
Expand Down
Loading

0 comments on commit 9901320

Please sign in to comment.