Fix latest Sonar fixes

* Some code style improvement for SMB classes
* Make an `SmbSessionTests` based on the `SmbTestSupport` for faster execution, but not blocking on fake URL connection attempt
* Remove `AbstractMqttMessageDrivenChannelAdapter.Topic` model in favor of `LinkedHashMap` handling
This commit is contained in:
Artem Bilan
2022-11-04 16:19:03 -04:00
parent d31f309752
commit 18fcd21137
14 changed files with 210 additions and 341 deletions

View File

@@ -49,9 +49,21 @@ import org.springframework.util.StringUtils;
*/
public class RouterAnnotationPostProcessor extends AbstractMethodAnnotationPostProcessor<Router> {
private static final String APPLY_SEQUENCE_ATTR = "applySequence";
private static final String IGNORE_SEND_FAILURES_ATTR = "ignoreSendFailures";
private static final String CHANNEL_MAPPINGS_ATTR = "channelMappings";
private static final String RESOLUTION_REQUIRED_ATTR = "resolutionRequired";
private static final String PREFIX_ATTR = "prefix";
private static final String SUFFIX_ATTR = "suffix";
public RouterAnnotationPostProcessor() {
this.messageHandlerAttributes.addAll(Arrays.asList("defaultOutputChannel", "applySequence",
"ignoreSendFailures", "resolutionRequired", "channelMappings", "prefix", "suffix"));
this.messageHandlerAttributes.addAll(Arrays.asList("defaultOutputChannel", APPLY_SEQUENCE_ATTR,
IGNORE_SEND_FAILURES_ATTR, RESOLUTION_REQUIRED_ATTR, CHANNEL_MAPPINGS_ATTR, PREFIX_ATTR, SUFFIX_ATTR));
}
@Override
@@ -76,13 +88,13 @@ public class RouterAnnotationPostProcessor extends AbstractMethodAnnotationPostP
.getBeanDefinition();
new BeanDefinitionPropertiesMapper(routerBeanDefinition, annotations)
.setPropertyValue("applySequence")
.setPropertyValue("ignoreSendFailures")
.setPropertyValue("resolutionRequired")
.setPropertyValue("prefix")
.setPropertyValue("suffix");
.setPropertyValue(APPLY_SEQUENCE_ATTR)
.setPropertyValue(IGNORE_SEND_FAILURES_ATTR)
.setPropertyValue(RESOLUTION_REQUIRED_ATTR)
.setPropertyValue(PREFIX_ATTR)
.setPropertyValue(SUFFIX_ATTR);
String[] channelMappings = MessagingAnnotationUtils.resolveAttribute(annotations, "channelMappings",
String[] channelMappings = MessagingAnnotationUtils.resolveAttribute(annotations, CHANNEL_MAPPINGS_ATTR,
String[].class);
if (!ObjectUtils.isEmpty(channelMappings)) {
Map<String, String> mappings =
@@ -94,7 +106,7 @@ public class RouterAnnotationPostProcessor extends AbstractMethodAnnotationPostP
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
routerBeanDefinition.getPropertyValues()
.addPropertyValue("channelMappings", mappings);
.addPropertyValue(CHANNEL_MAPPINGS_ATTR, mappings);
}
return routerBeanDefinition;
@@ -109,12 +121,12 @@ public class RouterAnnotationPostProcessor extends AbstractMethodAnnotationPostP
router.setDefaultOutputChannelName(defaultOutputChannelName);
}
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, "applySequence", String.class);
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, APPLY_SEQUENCE_ATTR, String.class);
if (StringUtils.hasText(applySequence)) {
router.setApplySequence(resolveAttributeToBoolean(applySequence));
}
String ignoreSendFailures = MessagingAnnotationUtils.resolveAttribute(annotations, "ignoreSendFailures",
String ignoreSendFailures = MessagingAnnotationUtils.resolveAttribute(annotations, IGNORE_SEND_FAILURES_ATTR,
String.class);
if (StringUtils.hasText(ignoreSendFailures)) {
router.setIgnoreSendFailures(resolveAttributeToBoolean(ignoreSendFailures));
@@ -130,7 +142,7 @@ public class RouterAnnotationPostProcessor extends AbstractMethodAnnotationPostP
MethodInvokingRouter methodInvokingRouter = (MethodInvokingRouter) router;
String resolutionRequired = MessagingAnnotationUtils.resolveAttribute(annotations, "resolutionRequired",
String resolutionRequired = MessagingAnnotationUtils.resolveAttribute(annotations, RESOLUTION_REQUIRED_ATTR,
String.class);
if (StringUtils.hasText(resolutionRequired)) {
methodInvokingRouter.setResolutionRequired(resolveAttributeToBoolean(resolutionRequired));
@@ -138,17 +150,17 @@ public class RouterAnnotationPostProcessor extends AbstractMethodAnnotationPostP
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
String prefix = MessagingAnnotationUtils.resolveAttribute(annotations, "prefix", String.class);
String prefix = MessagingAnnotationUtils.resolveAttribute(annotations, PREFIX_ATTR, String.class);
if (StringUtils.hasText(prefix)) {
methodInvokingRouter.setPrefix(beanFactory.resolveEmbeddedValue(prefix));
}
String suffix = MessagingAnnotationUtils.resolveAttribute(annotations, "suffix", String.class);
String suffix = MessagingAnnotationUtils.resolveAttribute(annotations, SUFFIX_ATTR, String.class);
if (StringUtils.hasText(suffix)) {
methodInvokingRouter.setSuffix(beanFactory.resolveEmbeddedValue(suffix));
}
String[] channelMappings = MessagingAnnotationUtils.resolveAttribute(annotations, "channelMappings",
String[] channelMappings = MessagingAnnotationUtils.resolveAttribute(annotations, CHANNEL_MAPPINGS_ATTR,
String[].class);
if (!ObjectUtils.isEmpty(channelMappings)) {
StringBuilder mappings = new StringBuilder();
@@ -166,14 +178,14 @@ public class RouterAnnotationPostProcessor extends AbstractMethodAnnotationPostP
private boolean routerAttributesProvided(List<Annotation> annotations) {
String defaultOutputChannel = MessagingAnnotationUtils.resolveAttribute(annotations, "defaultOutputChannel",
String.class);
String[] channelMappings = MessagingAnnotationUtils.resolveAttribute(annotations, "channelMappings",
String[] channelMappings = MessagingAnnotationUtils.resolveAttribute(annotations, CHANNEL_MAPPINGS_ATTR,
String[].class);
String prefix = MessagingAnnotationUtils.resolveAttribute(annotations, "prefix", String.class);
String suffix = MessagingAnnotationUtils.resolveAttribute(annotations, "suffix", String.class);
String resolutionRequired = MessagingAnnotationUtils.resolveAttribute(annotations, "resolutionRequired",
String prefix = MessagingAnnotationUtils.resolveAttribute(annotations, PREFIX_ATTR, String.class);
String suffix = MessagingAnnotationUtils.resolveAttribute(annotations, SUFFIX_ATTR, String.class);
String resolutionRequired = MessagingAnnotationUtils.resolveAttribute(annotations, RESOLUTION_REQUIRED_ATTR,
String.class);
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, "applySequence", String.class);
String ignoreSendFailures = MessagingAnnotationUtils.resolveAttribute(annotations, "ignoreSendFailures",
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, APPLY_SEQUENCE_ATTR, String.class);
String ignoreSendFailures = MessagingAnnotationUtils.resolveAttribute(annotations, IGNORE_SEND_FAILURES_ATTR,
String.class);
return StringUtils.hasText(defaultOutputChannel) || !ObjectUtils.isEmpty(channelMappings) // NOSONAR complexity
|| StringUtils.hasText(prefix) || StringUtils.hasText(suffix) || StringUtils.hasText(resolutionRequired)

View File

@@ -43,8 +43,10 @@ import org.springframework.util.StringUtils;
*/
public class SplitterAnnotationPostProcessor extends AbstractMethodAnnotationPostProcessor<Splitter> {
private static final String APPLY_SEQUENCE_ATTR = "applySequence";
public SplitterAnnotationPostProcessor() {
this.messageHandlerAttributes.addAll(Arrays.asList("outputChannel", "applySequence", "adviceChain"));
this.messageHandlerAttributes.addAll(Arrays.asList("outputChannel", APPLY_SEQUENCE_ATTR, "adviceChain"));
}
@Override
@@ -67,9 +69,9 @@ public class SplitterAnnotationPostProcessor extends AbstractMethodAnnotationPos
BeanDefinitionBuilder.genericBeanDefinition(SplitterFactoryBean.class)
.addPropertyValue("targetObject", targetObjectBeanDefinition);
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, "applySequence", String.class);
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, APPLY_SEQUENCE_ATTR, String.class);
if (StringUtils.hasText(applySequence)) {
splitterBeanDefinition.addPropertyValue("applySequence", applySequence);
splitterBeanDefinition.addPropertyValue(APPLY_SEQUENCE_ATTR, applySequence);
}
return splitterBeanDefinition.getBeanDefinition();
}
@@ -78,7 +80,7 @@ public class SplitterAnnotationPostProcessor extends AbstractMethodAnnotationPos
protected MessageHandler createHandler(Object bean, Method method, List<Annotation> annotations) {
AbstractMessageSplitter splitter = new MethodInvokingSplitter(bean, method);
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, "applySequence", String.class);
String applySequence = MessagingAnnotationUtils.resolveAttribute(annotations, APPLY_SEQUENCE_ATTR, String.class);
if (StringUtils.hasText(applySequence)) {
splitter.setApplySequence(resolveAttributeToBoolean(applySequence));
}

View File

@@ -126,9 +126,6 @@ public class LambdaMessageProcessor implements MessageProcessor<Object>, BeanFac
logClassCastException(ex);
throw ex;
}
catch (RuntimeException ex) {
throw ex;
}
catch (InvocationTargetException e) {
final Throwable cause = e.getCause();
if (e.getTargetException() instanceof ClassCastException classCastException) {
@@ -140,10 +137,13 @@ public class LambdaMessageProcessor implements MessageProcessor<Object>, BeanFac
throw new IllegalStateException(// NOSONAR lost stack trace
"Could not invoke the method '" + this.method + "'", cause);
}
catch (Exception e) {
catch (Exception ex) {
if (ex instanceof RuntimeException) { // NOSONAR
throw (RuntimeException) ex;
}
throw new IllegalStateException(
"error occurred during processing message in 'LambdaMessageProcessor' for method [" +
this.method + "]", e);
this.method + "]", ex);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,6 +33,8 @@ import org.springframework.util.StringUtils;
* {@code <int-hazelcast:cq-inbound-channel-adapter/>} configuration.
*
* @author Eren Avsarogullari
* @author Artem Bilan
*
* @since 6.0
*/
public class HazelcastContinuousQueryInboundChannelAdapterParser extends AbstractSingleBeanDefinitionParser {
@@ -82,22 +84,21 @@ public class HazelcastContinuousQueryInboundChannelAdapterParser extends Abstrac
}
if (!StringUtils.hasText(element.getAttribute(CACHE_ATTRIBUTE))) {
parserContext.getReaderContext().error("'" + CACHE_ATTRIBUTE + "' attribute is required.", element);
errorAttributeRequired(element, parserContext, CACHE_ATTRIBUTE);
}
else if (!StringUtils.hasText(element.getAttribute(CACHE_EVENTS_ATTRIBUTE))) {
parserContext.getReaderContext().error("'" + CACHE_EVENTS_ATTRIBUTE + "' attribute is required.", element);
errorAttributeRequired(element, parserContext, CACHE_EVENTS_ATTRIBUTE);
}
else if (!StringUtils.hasText(element.getAttribute(PREDICATE_ATTRIBUTE))) {
parserContext.getReaderContext().error("'" + PREDICATE_ATTRIBUTE + "' attribute is required.", element);
errorAttributeRequired(element, parserContext, PREDICATE_ATTRIBUTE);
}
else if (!StringUtils.hasText(element.getAttribute(CACHE_LISTENING_POLICY_ATTRIBUTE))) {
parserContext.getReaderContext().error("'" + CACHE_LISTENING_POLICY_ATTRIBUTE + "' attribute is required.",
element);
errorAttributeRequired(element, parserContext, CACHE_LISTENING_POLICY_ATTRIBUTE);
}
builder.addPropertyReference(OUTPUT_CHANNEL, channelName);
builder.addConstructorArgReference(element.getAttribute(CACHE_ATTRIBUTE));
builder.addConstructorArgValue(element.getAttribute(PREDICATE_ATTRIBUTE));
builder.addPropertyReference(OUTPUT_CHANNEL, channelName)
.addConstructorArgReference(element.getAttribute(CACHE_ATTRIBUTE))
.addConstructorArgValue(element.getAttribute(PREDICATE_ATTRIBUTE));
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, CACHE_EVENTS_ATTRIBUTE, CACHE_EVENT_TYPES);
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, INCLUDE_VALUE_ATTRIBUTE);
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, CACHE_LISTENING_POLICY_ATTRIBUTE);
@@ -105,4 +106,8 @@ public class HazelcastContinuousQueryInboundChannelAdapterParser extends Abstrac
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, IntegrationNamespaceUtils.PHASE);
}
private static void errorAttributeRequired(Element element, ParserContext parserContext, String attribute) {
parserContext.getReaderContext().error("'" + attribute + "' attribute is required.", element);
}
}

View File

@@ -16,11 +16,13 @@
package org.springframework.integration.mqtt.inbound;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
@@ -67,7 +69,7 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
private final String clientId;
private final Set<Topic> topics;
private final Map<String, Integer> topics;
private final ClientManager<T, C> clientManager;
@@ -95,15 +97,12 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
this.clientId = null;
}
private static Set<Topic> initTopics(String[] topic) {
private static Map<String, Integer> initTopics(String[] topic) {
Assert.notNull(topic, "'topics' cannot be null");
Assert.noNullElements(topic, "'topics' cannot have null elements");
final Set<Topic> initialTopics = new LinkedHashSet<>();
int defaultQos = 1;
for (String t : topic) {
initialTopics.add(new Topic(t, defaultQos));
}
return initialTopics;
return Arrays.stream(topic)
.collect(Collectors.toMap(Function.identity(), (key) -> 1, (x, y) -> y, LinkedHashMap::new));
}
public void setConverter(MqttMessageConverter converter) {
@@ -125,16 +124,16 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
public void setQos(int... qos) {
Assert.notNull(qos, "'qos' cannot be null");
if (qos.length == 1) {
for (Topic topic : this.topics) {
topic.setQos(qos[0]);
for (Map.Entry<String, Integer> topic : this.topics.entrySet()) {
topic.setValue(qos[0]);
}
}
else {
Assert.isTrue(qos.length == this.topics.size(),
"When setting qos, the array must be the same length as the topics");
int n = 0;
for (Topic topic : this.topics) {
topic.setQos(qos[n++]);
for (Map.Entry<String, Integer> topic : this.topics.entrySet()) {
topic.setValue(qos[n++]);
}
}
}
@@ -145,8 +144,8 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
try {
int[] topicQos = new int[this.topics.size()];
int n = 0;
for (Topic topic : this.topics) {
topicQos[n++] = topic.getQos();
for (int qos : this.topics.values()) {
topicQos[n++] = qos;
}
return topicQos;
}
@@ -173,12 +172,7 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
public String[] getTopic() {
this.topicLock.lock();
try {
String[] topicNames = new String[this.topics.size()];
int n = 0;
for (Topic topic : this.topics) {
topicNames[n++] = topic.getTopic();
}
return topicNames;
return this.topics.keySet().toArray(new String[0]);
}
finally {
this.topicLock.unlock();
@@ -253,11 +247,10 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
public void addTopic(String topic, int qos) {
this.topicLock.lock();
try {
Topic newTopic = new Topic(topic, qos);
if (this.topics.contains(newTopic)) {
if (this.topics.containsKey(topic)) {
throw new MessagingException("Topic '" + topic + "' is already subscribed.");
}
this.topics.add(newTopic);
this.topics.put(topic, qos);
logger.debug(LogMessage.format("Added '%s' to subscriptions.", topic));
}
finally {
@@ -300,7 +293,7 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
this.topicLock.lock();
try {
for (String newTopic : topic) {
if (this.topics.contains(new Topic(newTopic, 0))) {
if (this.topics.containsKey(newTopic)) {
throw new MessagingException("Topic '" + newTopic + "' is already subscribed.");
}
}
@@ -323,9 +316,9 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
public void removeTopic(String... topic) {
this.topicLock.lock();
try {
for (String t : topic) {
if (this.topics.remove(new Topic(t, 0))) {
logger.debug(LogMessage.format("Removed '%s' from subscriptions.", t));
for (String name : topic) {
if (this.topics.remove(name) != null) {
logger.debug(LogMessage.format("Removed '%s' from subscriptions.", name));
}
}
}
@@ -334,57 +327,4 @@ public abstract class AbstractMqttMessageDrivenChannelAdapter<T, C> extends Mess
}
}
/**
* @since 4.1
*/
private static final class Topic {
private final String topic;
private volatile int qos;
Topic(String topic, int qos) {
this.topic = topic;
this.qos = qos;
}
private int getQos() {
return this.qos;
}
private void setQos(int qos) {
this.qos = qos;
}
private String getTopic() {
return this.topic;
}
@Override
public int hashCode() {
return this.topic.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Topic other = (Topic) obj;
return Objects.equals(this.topic, other.topic);
}
@Override
public String toString() {
return "Topic [topic=" + this.topic + ", qos=" + this.qos + "]";
}
}
}

View File

@@ -18,8 +18,7 @@ package org.springframework.integration.mqtt.config.xml;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.junit.jupiter.api.Test;
@@ -71,35 +70,36 @@ public class MqttMessageDrivenChannelAdapterParserTests {
private MessageChannel errors;
@Test
public void testNoTopics() { // INT-3467 no longer required to have topics
@SuppressWarnings("unchecked")
public void testNoTopics() {
assertThat(TestUtils.getPropertyValue(noTopicsAdapter, "url")).isEqualTo("tcp://localhost:1883");
assertThat(TestUtils.getPropertyValue(noTopicsAdapter, "autoStartup", Boolean.class)).isFalse();
assertThat(TestUtils.getPropertyValue(noTopicsAdapter, "clientId")).isEqualTo("foo");
assertThat(TestUtils.getPropertyValue(noTopicsAdapter, "topics", Collection.class).size()).isEqualTo(0);
assertThat(TestUtils.getPropertyValue(noTopicsAdapter, "topics", Map.class)).hasSize(0);
assertThat(TestUtils.getPropertyValue(noTopicsAdapter, "outputChannel")).isSameAs(out);
assertThat(TestUtils.getPropertyValue(noTopicsAdapter, "clientFactory")).isSameAs(clientFactory);
assertThat(TestUtils.getPropertyValue(this.noTopicsAdapter, "manualAcks", Boolean.class)).isTrue();
}
@Test
public void testNoTopicsDefaultCF() { // INT-3598
@SuppressWarnings("unchecked")
public void testNoTopicsDefaultCF() {
assertThat(TestUtils.getPropertyValue(noTopicsAdapterDefaultCF, "url")).isEqualTo("tcp://localhost:1883");
assertThat(TestUtils.getPropertyValue(noTopicsAdapterDefaultCF, "autoStartup", Boolean.class)).isFalse();
assertThat(TestUtils.getPropertyValue(noTopicsAdapterDefaultCF, "clientId")).isEqualTo("foo");
assertThat(TestUtils.getPropertyValue(noTopicsAdapterDefaultCF, "topics", Collection.class).size())
.isEqualTo(0);
assertThat(TestUtils.getPropertyValue(noTopicsAdapterDefaultCF, "topics", Map.class)).hasSize(0);
assertThat(TestUtils.getPropertyValue(noTopicsAdapterDefaultCF, "outputChannel")).isSameAs(out);
assertThat(TestUtils.getPropertyValue(this.noTopicsAdapterDefaultCF, "manualAcks", Boolean.class)).isFalse();
}
@Test
@SuppressWarnings("unchecked")
public void testOneTopic() {
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "url")).isEqualTo("tcp://localhost:1883");
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "autoStartup", Boolean.class)).isFalse();
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "phase")).isEqualTo(25);
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "clientId")).isEqualTo("foo");
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "topics", Collection.class).iterator().next().toString())
.isEqualTo("Topic [topic=bar, qos=1]");
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "topics", Map.class)).containsEntry("bar", 1);
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "converter")).isSameAs(converter);
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "messagingTemplate.sendTimeout")).isEqualTo(123L);
assertThat(TestUtils.getPropertyValue(oneTopicAdapter, "outputChannel")).isSameAs(out);
@@ -108,14 +108,15 @@ public class MqttMessageDrivenChannelAdapterParserTests {
}
@Test
@SuppressWarnings("unchecked")
public void testTwoTopics() {
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "url")).isEqualTo("tcp://localhost:1883");
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "autoStartup", Boolean.class)).isFalse();
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "phase")).isEqualTo(25);
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "clientId")).isEqualTo("foo");
Iterator<?> iterator = TestUtils.getPropertyValue(twoTopicsAdapter, "topics", Collection.class).iterator();
assertThat(iterator.next().toString()).isEqualTo("Topic [topic=bar, qos=0]");
assertThat(iterator.next().toString()).isEqualTo("Topic [topic=baz, qos=2]");
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "topics", Map.class))
.containsEntry("bar", 0)
.containsEntry("baz", 2);
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "converter")).isSameAs(converter);
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "messagingTemplate.sendTimeout")).isEqualTo(123L);
assertThat(TestUtils.getPropertyValue(twoTopicsAdapter, "outputChannel")).isSameAs(out);
@@ -123,10 +124,11 @@ public class MqttMessageDrivenChannelAdapterParserTests {
}
@Test
@SuppressWarnings("unchecked")
public void testTwoTopicsSingleQos() {
Iterator<?> iterator = TestUtils.getPropertyValue(twoTopicsSingleQosAdapter, "topics", Collection.class).iterator();
assertThat(iterator.next().toString()).isEqualTo("Topic [topic=bar, qos=0]");
assertThat(iterator.next().toString()).isEqualTo("Topic [topic=baz, qos=0]");
assertThat(TestUtils.getPropertyValue(twoTopicsSingleQosAdapter, "topics", Map.class))
.containsEntry("bar", 0)
.containsEntry("baz", 0);
}
}

View File

@@ -26,7 +26,7 @@ import jcifs.DialectVersion;
/**
* Data holder class for a SMB share configuration.
*
*<p>
* SmbFile URLs syntax:
* smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?[param=value[param2=value2[...]]]
*
@@ -73,7 +73,7 @@ public class SmbConfig {
setShareAndDir(_shareAndDir);
}
public void setHost(String _host) {
public final void setHost(String _host) {
Assert.hasText(_host, "host must not be empty");
this.host = _host;
}
@@ -82,7 +82,7 @@ public class SmbConfig {
return this.host;
}
public void setPort(int _port) {
public final void setPort(int _port) {
Assert.isTrue(_port >= 0, "port must be >= 0");
this.port = _port;
}
@@ -91,7 +91,7 @@ public class SmbConfig {
return this.port;
}
public void setDomain(String _domain) {
public final void setDomain(String _domain) {
Assert.notNull(_domain, "_domain can't be null");
this.domain = _domain;
}
@@ -100,7 +100,7 @@ public class SmbConfig {
return this.domain;
}
public void setUsername(String _username) {
public final void setUsername(String _username) {
Assert.hasText(_username, "username should be a non-empty string");
this.username = _username;
}
@@ -109,7 +109,7 @@ public class SmbConfig {
return this.username;
}
public void setPassword(String _password) {
public final void setPassword(String _password) {
Assert.notNull(_password, "password should not be null");
this.password = _password;
}
@@ -118,7 +118,7 @@ public class SmbConfig {
return this.password;
}
public void setShareAndDir(String _shareAndDir) {
public final void setShareAndDir(String _shareAndDir) {
Assert.notNull(_shareAndDir, "shareAndDir should not be null");
this.shareAndDir = _shareAndDir;
}

View File

@@ -33,6 +33,7 @@ import jcifs.smb.SmbFile;
* SMB.
*
* @author Gregory Bragg
* @author Artem Bilan
*
* @since 6.0
*/
@@ -110,7 +111,7 @@ public class SmbFileInfo extends AbstractFileInfo<SmbFile> {
*/
@Override
public String getPermissions() {
ACE[] aces = null;
ACE[] aces;
try {
aces = this.smbFile.getSecurity(true);
}
@@ -125,24 +126,24 @@ public class SmbFileInfo extends AbstractFileInfo<SmbFile> {
sb.append(" - ");
if ((ace.getAccessMask() & ACE.FILE_READ_DATA) != 0) {
sb.append(ace.isAllow() ? "Allow " : "Deny ");
sb.append(aceToAllowFlag(ace));
sb.append("Read, ");
}
if ((ace.getAccessMask() & ACE.FILE_WRITE_DATA) != 0) {
sb.append(ace.isAllow() ? "Allow " : "Deny ");
sb.append(aceToAllowFlag(ace));
sb.append("Write, ");
}
if ((ace.getAccessMask() & ACE.FILE_APPEND_DATA) != 0) {
sb.append(ace.isAllow() ? "Allow " : "Deny ");
sb.append(aceToAllowFlag(ace));
sb.append("Modify, ");
}
if ((ace.getAccessMask() & ACE.FILE_EXECUTE) != 0) {
sb.append(ace.isAllow() ? "Allow " : "Deny ");
sb.append(aceToAllowFlag(ace));
sb.append("Execute, ");
}
if ((ace.getAccessMask() & ACE.FILE_DELETE) != 0
|| (ace.getAccessMask() & ACE.DELETE) != 0) {
sb.append(ace.isAllow() ? "Allow " : "Deny ");
sb.append(aceToAllowFlag(ace));
sb.append("Delete, ");
}
@@ -151,11 +152,15 @@ public class SmbFileInfo extends AbstractFileInfo<SmbFile> {
sb.append("\n");
}
logger.debug(this.getFilename());
logger.debug("\n" + sb.toString());
logger.debug(sb);
return sb.toString();
}
private static String aceToAllowFlag(ACE ace) {
return ace.isAllow() ? "Allow " : "Deny ";
}
@Override
public SmbFile getFileInfo() {
return this.smbFile;

View File

@@ -141,7 +141,7 @@ public class SmbSession implements Session<SmbFile> {
return files;
}
else if (!smbDir.isDirectory()) {
throw new IOException("Resource [" + _path + "] is not a directory. Cannot list resources.");
throw new IOException("[" + _path + "] is not a directory. Cannot list resources.");
}
files = smbDir.listFiles();
@@ -176,7 +176,7 @@ public class SmbSession implements Session<SmbFile> {
try {
SmbFile remoteFile = createSmbFileObject(_path);
if (!remoteFile.isFile()) {
throw new IOException("Resource [" + _path + "] is not a file.");
throw new IOException("[" + _path + "] is not a file.");
}
FileCopyUtils.copy(remoteFile.getInputStream(), _outputStream);
}
@@ -366,7 +366,7 @@ public class SmbSession implements Session<SmbFile> {
public InputStream readRaw(String source) throws IOException {
SmbFile remoteFile = createSmbFileObject(source);
if (!remoteFile.isFile()) {
throw new IOException("Resource [" + source + "] is not a file.");
throw new IOException("[" + source + "] is not a file.");
}
return remoteFile.getInputStream();
}
@@ -499,7 +499,7 @@ public class SmbSession implements Session<SmbFile> {
return fileNames;
}
else if (!smbDir.isDirectory()) {
throw new IOException("Resource [" + _path + "] is not a directory. Cannot list resources.");
throw new IOException("[" + _path + "] is not a directory. Cannot list resources.");
}
fileNames = smbDir.list();

View File

@@ -60,8 +60,8 @@ public class SmbShare extends SmbFile {
public SmbShare(SmbConfig _smbConfig) throws IOException {
super(StringUtils.cleanPath(_smbConfig.validate().getUrl()),
SingletonContext.getInstance().withCredentials(
new NtlmPasswordAuthenticator(
_smbConfig.getDomain(), _smbConfig.getUsername(), _smbConfig.getPassword())));
new NtlmPasswordAuthenticator(
_smbConfig.getDomain(), _smbConfig.getUsername(), _smbConfig.getPassword())));
}
/**
@@ -85,9 +85,9 @@ public class SmbShare extends SmbFile {
public SmbShare(SmbConfig _smbConfig, Properties _props) throws IOException {
super(StringUtils.cleanPath(_smbConfig.validate().getUrl()),
new BaseContext(
new PropertyConfiguration(_props)).withCredentials(
new PropertyConfiguration(_props)).withCredentials(
new NtlmPasswordAuthenticator(
_smbConfig.getDomain(), _smbConfig.getUsername(), _smbConfig.getPassword())));
_smbConfig.getDomain(), _smbConfig.getUsername(), _smbConfig.getPassword())));
this.closeContext.set(true);
}
@@ -139,8 +139,25 @@ public class SmbShare extends SmbFile {
super.close();
}
public String newTempFileSuffix() {
return "-" + Long.toHexString(Double.doubleToLongBits(Math.random())) + ".tmp";
/**
* Tests to see if two {@link SmbShare} objects are equal.
* Relies on a super implementation.
* @param other another {@link SmbShare} object to compare for equality.
* @return equality result.
*/
@Override
public boolean equals(Object other) {
return super.equals(other);
}
/**
* Return a cache code from the super class.
* @return A hashcode for this share
*/
@Override
public int hashCode() {
return super.hashCode();
}
}

View File

@@ -102,13 +102,9 @@ public abstract class AbstractBaseTests {
* @throws IOException in case of I/O errors
*/
public static void writeToFile(InputStream _inputStream, String _path) throws IOException {
FileOutputStream fos = new FileOutputStream(_path);
try {
try (FileOutputStream fos = new FileOutputStream(_path)) {
FileCopyUtils.copy(_inputStream, fos);
}
finally {
fos.close();
}
}
/**
@@ -216,18 +212,18 @@ public abstract class AbstractBaseTests {
* @param _file file object
* @return the file object
*/
public static final File assertFileExists(File _file) {
public static File assertFileExists(File _file) {
return assertFileExists(_file, true);
}
public static final File assertFileNotExists(File _file) {
public static File assertFileNotExists(File _file) {
return assertFileExists(_file, false);
}
/**
* Asserts that the specified file exists or does not exists.
* Asserts that the specified file exists or does not exist.
* @param _file file object
* @param _exists true if should exist, false otherwise
* @param _exists true if file should exist, false otherwise
* @return the file object
*/
private static File assertFileExists(File _file, boolean _exists) {
@@ -241,7 +237,7 @@ public abstract class AbstractBaseTests {
return _file;
}
public static final File assertFileExists(String _file) {
public static File assertFileExists(String _file) {
return assertFileExists(new File(_file));
}
@@ -256,18 +252,14 @@ public abstract class AbstractBaseTests {
throws Exception {
AbstractBaseTests test;
Method[] methods = new Method[_methodNames.length];
String methodName = null;
test = _testClass.newInstance();
for (int i = 0; i < _methodNames.length; i++) {
methodName = _methodNames[i];
String methodName = _methodNames[i];
methods[i] = _testClass.getMethod(methodName, (Class<?>[]) null);
}
Method method = null;
for (int i = 0; i < methods.length; i++) {
method = methods[i];
for (Method method : methods) {
method.invoke(test, (Object[]) null);
}

View File

@@ -80,10 +80,11 @@ public class SmbTestSupport extends RemoteFileTestSupport {
private static final GenericContainer<?> SMB_CONTAINER = new GenericContainer<>("elswork/samba:4.15.5")
.withTmpFs(Map.of(INNER_SHARE_DIR, "rw"))
.withCommand("-u", "1000:1000:" + USERNAME + ":" + USERNAME + ":" + PASSWORD, "-s", SHARE_AND_DIR + ":" + INNER_SHARE_DIR + ":rw:" + USERNAME)
.withCommand("-u", "1000:1000:" + USERNAME + ":" + USERNAME + ":" + PASSWORD,
"-s", SHARE_AND_DIR + ":" + INNER_SHARE_DIR + ":rw:" + USERNAME)
.withExposedPorts(445);
private static SmbSessionFactory smbSessionFactory;
protected static SmbSessionFactory smbSessionFactory;
@BeforeAll
public static void connectToSMBServer() throws IOException {
@@ -101,16 +102,24 @@ public class SmbTestSupport extends RemoteFileTestSupport {
try (Session<SmbFile> smbFileSession = smbSessionFactory.getSession()) {
smbFileSession.mkdir("smbTarget");
Charset charset = StandardCharsets.UTF_8;
smbFileSession.write(IOUtils.toInputStream("source1", charset), TestUtils.applySystemFileSeparator("smbSource/smbSource1.txt"));
smbFileSession.write(IOUtils.toInputStream("source2", charset), TestUtils.applySystemFileSeparator("smbSource/smbSource2.txt"));
smbFileSession.write(IOUtils.toInputStream("source1", charset),
TestUtils.applySystemFileSeparator("smbSource/smbSource1.txt"));
smbFileSession.write(IOUtils.toInputStream("source2", charset),
TestUtils.applySystemFileSeparator("smbSource/smbSource2.txt"));
smbFileSession.write(IOUtils.toInputStream("", charset), "SMBSOURCE1.TXT.a");
smbFileSession.write(IOUtils.toInputStream("", charset), "SMBSOURCE2.TXT.a");
smbFileSession.write(IOUtils.toInputStream("subSource1", charset), TestUtils.applySystemFileSeparator("smbSource/subSmbSource/subSmbSource1.txt"));
smbFileSession.write(IOUtils.toInputStream("subSource2", charset), TestUtils.applySystemFileSeparator("smbSource/subSmbSource/subSmbSource2.txt"));
smbFileSession.write(IOUtils.toInputStream("subSource1", charset),
TestUtils.applySystemFileSeparator("smbSource/subSmbSource/subSmbSource1.txt"));
smbFileSession.write(IOUtils.toInputStream("subSource2", charset),
TestUtils.applySystemFileSeparator("smbSource/subSmbSource/subSmbSource2.txt"));
}
}
public static String smbServerUrl() {
return smbSessionFactory.getUrl().replaceFirst('/' + SHARE_AND_DIR + '/', "");
}
public static SessionFactory<SmbFile> sessionFactory() {
return new CachingSessionFactory<>(smbSessionFactory);
}

View File

@@ -73,17 +73,17 @@ public class SmbInboundOutboundSample extends AbstractBaseTests {
smbSession.mkdir(testRemoteDir);
String[] fileNames = createTestFileNames(5);
for (int i = 0; i < fileNames.length; i++) {
smbSession.write(("File [" + fileNames[i] + "] written by test case [" + getMethodName() + "].").getBytes(),
testRemoteDir + fileNames[i]);
for (String fileName : fileNames) {
smbSession.write(("File [" + fileName + "] written by test case [" + getMethodName() + "].").getBytes(),
testRemoteDir + fileName);
}
// allow time for the files to arrive locally
Thread.sleep(5000);
// confirm the local presence of all test files
for (int i = 0; i < fileNames.length; i++) {
assertFileExists(testLocalDir + fileNames[i]).deleteOnExit();
for (String fileName : fileNames) {
assertFileExists(testLocalDir + fileName).deleteOnExit();
}
}
@@ -96,9 +96,9 @@ public class SmbInboundOutboundSample extends AbstractBaseTests {
new File(testLocalDir).mkdirs();
String[] fileNames = createTestFileNames(5);
for (int i = 0; i < fileNames.length; i++) {
writeToFile(("File [" + fileNames[i] + "] written by test case [" + getMethodName() + "].").getBytes(),
testLocalDir + fileNames[i]);
for (String fileName : fileNames) {
writeToFile(("File [" + fileName + "] written by test case [" + getMethodName() + "].").getBytes(),
testLocalDir + fileName);
}
ApplicationContext ac = new ClassPathXmlApplicationContext(OUTBOUND_APPLICATION_CONTEXT_XML, this.getClass());
@@ -110,8 +110,8 @@ public class SmbInboundOutboundSample extends AbstractBaseTests {
MessageChannel smbChannel = ac.getBean("smbOutboundChannel", MessageChannel.class);
for (int i = 0; i < fileNames.length; i++) {
smbChannel.send(new GenericMessage<File>(new File(testLocalDir + fileNames[i])));
for (String fileName : fileNames) {
smbChannel.send(new GenericMessage<>(new File(testLocalDir + fileName)));
}
Thread.sleep(3000);
@@ -120,14 +120,14 @@ public class SmbInboundOutboundSample extends AbstractBaseTests {
SmbSessionFactory smbSessionFactory = ac.getBean("smbSessionFactory", SmbSessionFactory.class);
SmbSession smbSession = smbSessionFactory.getSession();
for (int i = 0; i < fileNames.length; i++) {
String remoteFile = testRemoteDir + fileNames[i];
for (String fileName : fileNames) {
String remoteFile = testRemoteDir + fileName;
assertThat(smbSession.exists(remoteFile)).as("Remote file [" + remoteFile + "] does not exist.").isTrue();
}
}
private String[] createTestFileNames(int _nbTestFiles) {
private static String[] createTestFileNames(int _nbTestFiles) {
String[] fileNames = new String[_nbTestFiles];
for (int i = 0; i < fileNames.length; i++) {
fileNames[i] = "test-file-" + i + ".txt";

View File

@@ -19,186 +19,71 @@ package org.springframework.integration.smb.session;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.Properties;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.integration.smb.SmbTestSupport;
import jcifs.DialectVersion;
import jcifs.smb.SmbFile;
/**
*
* @author Gunnar Hillert
* @author Gregory Bragg
* @author Artem Bilan
*
*/
public class SmbSessionTests {
public class SmbSessionTests extends SmbTestSupport {
@Test
public void testCreateSmbFileObjectWithBackSlash1() throws IOException {
System.setProperty("file.separator", "\\");
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared/");
SmbShare smbShare = new SmbShare(config);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba\\");
assertThat("smb://myshare/blubba/").isEqualTo(smbFile.getPath());
smbSession.close();
try (SmbSession smbSession = smbSessionFactory.getSession()) {
SmbFile smbFile = smbSession.createSmbFileObject("smb://localhost\\blubba\\");
assertThat("smb://localhost/blubba/").isEqualTo(smbFile.getPath());
}
}
@Test
public void testCreateSmbFileObjectWithBackSlash2() throws IOException {
public void testCreateOtherSmbFileObject() throws IOException {
System.setProperty("file.separator", "\\");
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared\\");
SmbShare smbShare = new SmbShare(config);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba\\");
assertThat("smb://myshare/blubba/").isEqualTo(smbFile.getPath());
smbSession.close();
}
@Test
public void testCreateSmbFileObjectWithBackSlash3() throws IOException {
System.setProperty("file.separator", "\\");
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared\\");
SmbShare smbShare = new SmbShare(config);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("..\\another");
assertThat("smb://myshare:445/another").isEqualTo(smbFile.getPath());
smbSession.close();
try (SmbSession smbSession = smbSessionFactory.getSession()) {
SmbFile smbFile = smbSession.createSmbFileObject("..\\another");
assertThat(smbServerUrl() + "/another").isEqualTo(smbFile.getPath());
}
}
@Test
public void testCreateSmbFileObjectWithBackSlash4() throws IOException {
System.setProperty("file.separator", "/");
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared/");
SmbShare smbShare = new SmbShare(config);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba\\");
assertThat("smb://myshare/blubba/").isEqualTo(smbFile.getPath());
smbSession.close();
try (SmbSession smbSession = smbSessionFactory.getSession()) {
SmbFile smbFile = smbSession.createSmbFileObject("smb://localhost\\blubba\\");
assertThat("smb://localhost/blubba/").isEqualTo(smbFile.getPath());
}
}
@Test
public void testCreateSmbFileObjectWithMissingTrailingSlash1() throws IOException {
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared");
SmbShare smbShare = new SmbShare(config);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba");
assertThat("smb://myshare/blubba").isEqualTo(smbFile.getPath());
smbSession.close();
try (SmbSession smbSession = smbSessionFactory.getSession()) {
SmbFile smbFile = smbSession.createSmbFileObject("smb://localhost\\blubba");
assertThat("smb://localhost/blubba").isEqualTo(smbFile.getPath());
}
}
@Test
public void testCreateSmbFileObjectWithMissingTrailingSlash2() throws IOException {
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared/");
SmbShare smbShare = new SmbShare(config);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject(".");
assertThat("smb://myshare:445/shared/").isEqualTo(smbFile.getPath());
smbSession.close();
try (SmbSession smbSession = smbSessionFactory.getSession()) {
SmbFile smbFile = smbSession.createSmbFileObject(".");
assertThat(smbServerUrl() + '/' + SHARE_AND_DIR + '/').isEqualTo(smbFile.getPath());
}
}
@Test
public void testCreateSmbFileObjectWithMissingTrailingSlash3() throws IOException {
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared/");
SmbShare smbShare = new SmbShare(config);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("../anotherShare");
assertThat("smb://myshare:445/anotherShare").isEqualTo(smbFile.getPath());
smbSession.close();
try (SmbSession smbSession = smbSessionFactory.getSession()) {
SmbFile smbFile = smbSession.createSmbFileObject("..\\anotherShare");
assertThat(smbServerUrl() + "/anotherShare").isEqualTo(smbFile.getPath());
}
}
@Test
public void testCreateSmbFileObjectWithSmb3Versions1() throws IOException {
Properties props = new Properties();
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared/");
config.setSmbMinVersion(DialectVersion.SMB300);
config.setSmbMaxVersion(DialectVersion.SMB311);
props.setProperty("jcifs.smb.client.minVersion", config.getSmbMinVersion().name());
props.setProperty("jcifs.smb.client.maxVersion", config.getSmbMaxVersion().name());
SmbShare smbShare = new SmbShare(config, props);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba");
assertThat("smb://myshare/blubba").isEqualTo(smbFile.getPath());
smbSession.close();
}
@Test
public void testCreateSmbFileObjectWithSmb3Versions2() throws IOException {
Properties props = new Properties();
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared/");
config.setSmbMinVersion(DialectVersion.SMB302);
config.setSmbMaxVersion(DialectVersion.SMB311);
props.setProperty("jcifs.smb.client.minVersion", config.getSmbMinVersion().name());
props.setProperty("jcifs.smb.client.maxVersion", config.getSmbMaxVersion().name());
SmbShare smbShare = new SmbShare(config, props);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba");
assertThat("smb://myshare/blubba").isEqualTo(smbFile.getPath());
smbSession.close();
}
@Test
public void testCreateSmbFileObjectWithSmb3Versions3() throws IOException {
Properties props = new Properties();
SmbConfig config = new SmbConfig();
config.setHost("myshare");
config.setPort(445);
config.setShareAndDir("shared/");
config.setSmbMinVersion(DialectVersion.SMB311);
config.setSmbMaxVersion(DialectVersion.SMB311);
props.setProperty("jcifs.smb.client.minVersion", config.getSmbMinVersion().name());
props.setProperty("jcifs.smb.client.maxVersion", config.getSmbMaxVersion().name());
SmbShare smbShare = new SmbShare(config, props);
SmbSession smbSession = new SmbSession(smbShare);
SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba");
assertThat("smb://myshare/blubba").isEqualTo(smbFile.getPath());
smbSession.close();
}
}