I'm using Spring version 2.1.18.RELEASE (I can't change this version)
I need to implement a crud repository for elasticsearch, for this I connect spring-data-elasticsearch (version 3.1.21.RELEASE is automatically pulled up) with elasticsearch 6.4.3
I tried a bunch of manuals, but elastic is so different from version to version that I can't find a solution. I need to connect to remote server via https with username and password.
pom:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</dependency>
Config:
#Configuration
#EnableElasticsearchRepositories(basePackages = "path.to.elastic")
#ComponentScan(basePackages = {"path.to.elastic"})
public class ElasticConfiguration {
private final int port = 1234;
#Bean
public Client client() throws Exception {
Settings settings = Settings.builder().put("cluster.name", "test")
.put("xpack.security.user", "login:pass")
.put("xpack.security.transport.ssl.enabled", "true")
.put("xpack.security.transport.ssl.enabled", "true")
.build();
return new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("bah.elk1.com"), port))
.addTransportAddress(new TransportAddress(InetAddress.getByName("bah.elk2.com"), port))
.addTransportAddress(new TransportAddress(InetAddress.getByName("bah.elk3.com"), port));
}
#Bean
public ElasticsearchOperations elasticsearchTemplate() throws Exception {
return new ElasticsearchTemplate(client());
}
}
Repository:
#Repository
public interface ElkThingRepository extends ElasticsearchRepository<Things, Long> {
List<Things> findByEarNameAndName(String earName, String thingName);
}
Service interface:
public interface ElkThingsService {
List<Things> simpleGet(String thingName);
}
Service impl:
#Service
public class ElkThingsServiceImpl implements ElkThingsService {
private final ElkThingsRepository elkThingsRepository;
#Autowired
public ElkThingsServiceImpl(ElkThingsRepository elkThingsRepository) {
this.elkThingsRepository = elkThingsRepository;
}
public List<Things> simpleGet(String thingsName) {
return elkThingsRepository.findByEarNameAndName(AppInfo.SUBSYSTEM_CODE, thingName);
}
}
Things:
#Data
#Document(indexName = "things-*", type = "things")
public class Things {
#Id
private Long id;
private String earName;
private String name;
}
Now im get exceprion:
java.lang.IllegalArgumentException: unknown setting [xpack.security.user] please check that any required plugins are installed, or check the breaking changes documentation for removed settings
When i add spring-data-elasticsearch 4.0.0 and try to use RestHighLevelClient i get NoClassDefFoundError error creating RestHighLevelClient bean
I am trying to send the websocket message larger than 65536 size and getting connection closed exception and error message.
**Connection closed: 1009 - Text message size [67000] exceeds maximum size [65536] **
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.websocketMaxTextClient</groupId>
<artifactId>websocketMaxTextClient</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>websocketMaxTextClient</name>
<description>Websocket response message limitation</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jmx</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-client</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Websocket server configuration
#Component
public class WebsocketEndPoint extends TextWebSocketHandler{
private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
#Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {
System.out.println("message : "+message.getPayload());
session.sendMessage(message);
}
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
session.setTextMessageSizeLimit(13900000);
System.out.println("textmessage limit : "+session.getTextMessageSizeLimit());
sessions.add(session);
super.afterConnectionEstablished(session);
}
#Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
super.afterConnectionClosed(session, status);
}
}
WebsocketConfig
#EnableWebSocket
#Configuration
public class WebsocketConfig implements WebSocketConfigurer {
#Autowired
private WebsocketEndPoint websocketEndPoint;
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(websocketEndPoint, "/web-socket").setHandshakeHandler(handshakeHandler());
}
public DefaultHandshakeHandler handshakeHandler() {
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
policy.setMaxTextMessageBufferSize(17981302);
policy.setMaxTextMessageSize(13800000);
policy.setMaxBinaryMessageBufferSize(18981302);
policy.setMaxBinaryMessageSize(15981302);
policy.setInputBufferSize( 15981302);
return new DefaultHandshakeHandler(
new JettyRequestUpgradeStrategy(new WebSocketServerFactory()));
}
#Bean
public ServletServerContainerFactoryBean createServletServerContainerFactoryBean() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(1024*1024);
// container.setMaxBinaryMessageBufferSize(32768);
return container;
}
}
`
Websocket clientt code
#SpringBootApplication
public class WebsocketMaxTextClientApplication {
/*
* WebSocket client connection
*/
public static void main(String[] args) throws URISyntaxException, IOException {
String url = "ws://127.0.0.1:8082/web-socket";
WebSocketClient client = new WebSocketClient();
try
{
client.setMaxTextMessageBufferSize(13300000);
client.getPolicy().setMaxTextMessageSize(1329705);
client.getPolicy().delegateAs(WebSocketBehavior.CLIENT);
client.start();
URI echoUri = new URI(url);
ClientUpgradeRequest request = new ClientUpgradeRequest();
client.connect(socket, echoUri, request);
// wait for closed socket connection.
socket.awaitClose(5, TimeUnit.SECONDS);
}
catch (Throwable t)
{
t.printStackTrace();
}
finally
{
try
{
client.stop();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
Websocketclient end point
#WebSocket
public class WebsocketMaxTextClientEndPoint {
private final CountDownLatch closeLatch;
#SuppressWarnings("unused")
private Session session;
public WebsocketMaxTextClientEndPoint()
{
this.closeLatch = new CountDownLatch(1);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException
{
return this.closeLatch.await(duration, unit);
}
#OnWebSocketClose
public void onClose(int statusCode, String reason)
{
System.out.printf("Connection closed: %d - %s%n", statusCode, reason);
this.session = null;
this.closeLatch.countDown(); // trigger latch
}
#OnWebSocketConnect
public void onConnect(Session session)
{
System.out.printf("Got connect: %s%n", session);
this.session = session;
try
{
session.getRemote().sendString("Thanks for the conversation.");
String json = randomString(67000);
System.out.println("default textmessage Length in websocket : "+session.getPolicy().getMaxTextMessageSize());
session.getRemote().sendString(json);
}
catch (Throwable t)
{
t.printStackTrace();
}
}
#OnWebSocketMessage
public void onMessage(String msg)
{
System.out.printf("Got msg: %s%n", msg);
}
#OnWebSocketError
public void onError(Throwable cause)
{
System.out.print("WebSocket Error: ");
cause.printStackTrace(System.out);
}
private String randomString(int size) {
return RandomStringUtils.random(size, true, true);
}
}
The log details are
Connection closed: 1009 - Text message size [67000] exceeds maximum size [65536]
10:12:19.175 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle - stopping WebSocketClient#29c17a75[httpClient=HttpClient#614c5515{STARTED},openSessions.size=1]
10:12:19.175 [main] DEBUG org.eclipse.jetty.websocket.client.WebSocketClient - Stopping WebSocketClient#29c17a75[httpClient=HttpClient#614c5515{STARTED},openSessions.size=1]
10:12:19.175 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle - stopping SessionTracker#548b7f67{STARTED}
10:12:19.175 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle - stopping WebSocketSession[websocket=JettyAnnotatedEventDriver[com.websocketMaxTextClient.websocketMaxTextClient.endPoint.WebsocketMaxTextClientEndPoint#17c1bced],behavior=CLIENT,connection=WebSocketClientConnection#66e7e62f::SocketChannelEndPoint#7f4cda1a{l=/127.0.0.1:64098,r=/127.0.0.1:8082,OPEN,fill=-,flush=-,to=3/300000}{io=0/0,kio=0,kro=1}->WebSocketClientConnection#66e7e62f[s=ConnectionState#44b79a43[CLOSING],f=Flusher#21d129b1[IDLE][queueSize=0,aggregateSize=-1,terminated=null],g=Generator[CLIENT,validating],p=Parser#42399352[ExtensionStack,s=START,c=0,len=56,f=CLOSE[len=56,fin=true,rsv=...,masked=false]]],remote=WebSocketRemoteEndpoint#55dc6bce[batching=true],incoming=JettyAnnotatedEventDriver[com.websocketMaxTextClient.websocketMaxTextClient.endPoint.WebsocketMaxTextClientEndPoint#17c1bced],outgoing=ExtensionStack[queueSize=0,extensions=[],incoming=org.eclipse.jetty.websocket.common.WebSocketSession,outgoing=org.eclipse.jetty.websocket.client.io.WebSocketClientConnection]]
10:12:19.176 [main] DEBUG org.eclipse.jetty.websocket.common.WebSocketSession - stopping - WebSocketSession[websocket=JettyAnnotatedEventDriver[com.websocketMaxTextClient.websocketMaxTextClient.endPoint.WebsocketMaxTextClientEndPoint#17c1bced],behavior=CLIENT,connection=WebSocketClientConnection#66e7e62f::SocketChannelEndPoint#7f4cda1a{l=/127.0.0.1:64098,r=/127.0.0.1:8082,OPEN,fill=-,flush=-,to=4/300000}{io=0/0,kio=0,kro=1}->WebSocketClientConnection#66e7e62f[s=ConnectionState#44b79a43[CLOSING],f=Flusher#21d129b1[IDLE][queueSize=0,aggregateSize=-1,terminated=null],g=Generator[CLIENT,validating],p=Parser#42399352[ExtensionStack,s=START,c=0,len=56,f=CLOSE[len=56,fin=true,rsv=...,masked=false]]],remote=WebSocketRemoteEndpoint#55dc6bce[batching=true],incoming=JettyAnnotatedEventDriver[com.websocketMaxTextClient.websocketMaxTextClient.endPoint.WebsocketMaxTextClientEndPoint#17c1bced],outgoing=ExtensionStack[queueSize=0,extensions=[],incoming=org.eclipse.jetty.websocket.common.WebSocketSession,outgoing=org.eclipse.jetty.websocket.client.io.WebSocketClientConnection]]
10:12:19.176 [WebSocketClient#1632392469-20] DEBUG org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection - outgoingFrame(CLOSE[len=56,fin=true,rsv=...,masked=true], org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection$CallbackBridge#7ce49efe)
10:12:19.176 [main] DEBUG org.eclipse.jetty.websocket.common.WebSocketSession - callApplicationOnClose(CloseInfo[code=1006,reason=Disconnected])
10:12:19.176 [main] DEBUG org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection - CLIENT disconnect()
10:12:19.176 [WebSocketClient#1632392469-20] DEBUG org.eclipse.jetty.websocket.common.io.FrameFlusher - Enqueued FrameEntry[CLOSE[len=56,fin=true,rsv=...,masked=true],org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection$CallbackBridge#7ce49efe,OFF,null] to Flusher#21d129b1[IDLE][queueSize=1,aggregateSize=-1,terminated=null]
10:12:19.176 [main] DEBUG org.eclipse.jetty.websocket.common.io.FrameFlusher - Terminating Flusher#21d129b1[PROCESSING][queueSize=1,aggregateSize=-1,terminated=java.io.EOFException: Disconnected]
10:12:19.176 [WebSocketClient#1632392469-20] DEBUG org.eclipse.jetty.websocket.common.io.FrameFlusher - Flushing Flusher#21d129b1[PROCESSING][queueSize=1,aggregateSize=-1,terminated=java.io.EOFException: Disconnected]
10:12:19.176 [main] DEBUG org.eclipse.jetty.io.AbstractEndPoint - shutdownOutput SocketChannelEndPoint#7f4cda1a{l=/127.0.0.1:64098,r=/127.0.0.1:8082,OPEN,fill=-,flush=-,to=4/300000}{io=0/0,kio=0,kro=1}->WebSocketClientConnection#66e7e62f[s=ConnectionState#44b79a43[DISCONNECTED],f=Flusher#21d129b1[FAILED][queueSize=1,aggregateSize=-1,terminated=java.io.EOFException: Disconnected],g=Generator[CLIENT,validating],p=Parser#42399352[ExtensionStack,s=START,c=0,len=56,f=CLOSE[len=56,fin=true,rsv=...,masked=false]]]
10:12:19.179 [WebSocketClient#1632392469-20] DEBUG org.eclipse.jetty.websocket.common.WebSocketSession - callApplicationOnError()
java.io.EOFException: Disconnected
I want to send more than 10 MB data from websocket client to server.
Please help me, Tried to resolve it but unable to find the exact root cause.
Unable to send websocket client message larger than 65536 to websocket server in spring boot 2.7 and want to send 10 mb websocket client response to websocket server.Please provide solution, Thanks
I am trying to run the publisher and subscriber, using spring binding.
made sure the destination(exchange) is created locally on the rabbit-mq.
publisher (app.yml)
spring:
cloud:
stream:
bindings:
output:
destination: HelloDestination
rabbitmq:
addresses: xxx.xxx.xx.xxx
Subscriber(app.yml)
spring:
cloud:
stream:
bindings:
input:
destination: HelloDestination
rabbitmq:
addresses: xxx.xxx.xx.xxx
server:
port: 8081
publisher (pom.yml)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
Subscriber (pom.yml)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
publisher (source java file)
#SpringBootApplication
#EnableBinding(Source.class)
public class Demo1Application {
//#Autowired
//private static MessageChannel output;
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
String sampleMessage = "Hello";
Message<String> message =
MessageBuilder.withPayload("Hello World").build();
MessageChannel output = new DirectChannel();
output.send(message);
}
}
//consumer (source file)
#SpringBootApplication
#EnableBinding(Sink.class)
public class Demo2Application {
public static void main(String[] args) {
SpringApplication.run(Demo2Application.class, args);
}
#StreamListener(Sink.INPUT)
public void listenerMethod(Message<String> message)
{
System.out.println("The Message is :"+message);
}
}
//----
After doing all, I see the exchange created and also the message on exchange. The consumer starts up just fine. but the producer chokes when trying to send the message with the error message
Exception in thread "main" org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'unknown.channel.name'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}], failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}]
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:461)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:401)
at com.example.demo.Demo1Application.main(Demo1Application.java:29)
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=Hello World, headers={id=ccf86001-5dba-6c64-bc76-e1f58782de42, timestamp=1558883876384}]
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:138)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:105)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscri
I expected the message to be read.
You need to get channel 'output' from the application context returned by the run() method instead of creating your own DirectChannel.
I am able to send and receive the message using code:
#EnableBinding(Processor.class)
public class KafkaStreamsConfiguration {
#StreamListener(Processor.INPUT)
#SendTo(Processor.OUTPUT)
public String processMessage(String message) {
System.out.println("message = " + message);
return message.replaceAll("my", "your");
}
}
#RunWith(SpringRunner.class)
#SpringBootTest
#DirtiesContext
public class StreamApplicationIT {
private static String topicToPublish = "eventUpdateFromEventModel";
#BeforeClass
public static void setup() {
System.setProperty("spring.kafka.bootstrap-servers", embeddedKafka.getBrokersAsString());
}
#Autowired
private KafkaMessageSender<String> kafkaMessageSenderToTestErrors;
#Autowired
private KafkaMessageSender<EventNotificationDto> kafkaMessageSender;
#ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, topicToPublish);
#Autowired
private Processor pipe;
#Autowired
private MessageCollector messageCollector;
#Rule
public OutputCapture outputCapture = new OutputCapture();
#Test
public void working() {
pipe.input()
.send(MessageBuilder.withPayload("This is my message")
.build());
Object payload = messageCollector.forChannel(pipe.output())
.poll()
.getPayload();
assertEquals("This is your message", payload.toString());
}
#Test
public void non_working() {
kafkaMessageSenderToTestErrors.send(topicToPublish, "This was my message");
assertTrue(isMessageReceived("This was your message", 50));
}
private boolean isMessageReceived(final String msg, final int maxAttempt) {
return IntStream.rangeClosed(0, maxAttempt)
.peek(a -> {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
fail();
}
}).anyMatch(i -> outputCapture.toString().contains(msg));
}
}
#Service
#Slf4j
public class KafkaMessageSender<T> {
private final KafkaTemplate<String, byte[]> kafkaTemplate;
private final ObjectWriter objectWriter;
public KafkaMessageSender(KafkaTemplate<String, byte[]> kafkaTemplate, ObjectMapper objectMapper) {
this.kafkaTemplate = kafkaTemplate;
this.objectWriter = objectMapper.writer();
}
public void send(String topicName, T payload) {
try {
kafkaTemplate.send(topicName, objectWriter.writeValueAsString(payload).getBytes());
} catch (JsonProcessingException e) {
log.info("error converting object into byte array {}", payload.toString().substring(0, 50));
}
log.info("sent payload to topic='{}'", topicName);
}
}
But when I send the message using kafkaTemplate to any topic, StreamListener doesn't receive the message.
spring.cloud.stream.bindings.input.group=test
spring.cloud.stream.bindings.input.destination=eventUpdateFromEventModel
my pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-test-support</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring boot version -->
<spring.boot.version>1.5.7.RELEASE</spring.boot.version>
<spring-cloud.version>Edgware.SR3</spring-cloud.version>
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
working
Object payload = messageCollector.forChannel(pipe.output())
.poll()
.getPayload();
...
not working
KafkaTemplate
This is because you are using the TestBinder in your test, not the real Kafka broker and kafka binder.
The message collector is simply fetching it from the channel. If you want to test with a real Kafka broker, see the test-embedded-kafka sample app.
EDIT
I just tested the Ditmars (boot 1.5.x) version of the sample and it works fine...
I am checking out how to send an email using Spring Boot.
Send an e-mail using standard Spring Boot modules and prepare HTML content for a message using Thymeleaf template engine.
This is the dependencies I use
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.icegreen</groupId>
<artifactId>greenmail</artifactId>
<version>1.5.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Here my MailClient
#Service
public class MailClient {
private JavaMailSender mailSender;
private MailContentBuilder mailContentBuilder;
#Autowired
public MailClient(JavaMailSender mailSender, MailContentBuilder mailContentBuilder) {
this.mailSender = mailSender;
this.mailContentBuilder = mailContentBuilder;
}
public void prepareAndSend(String recipient, String message) {
MimeMessagePreparator messagePreparator = mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
messageHelper.setFrom("amadeu.cabanilles#gmail.com");
messageHelper.setTo("amadeu.cabanilles#gmail.com");
messageHelper.setSubject("Sample mail subject");
String content = mailContentBuilder.build(message);
messageHelper.setText(content, true);
};
try {
mailSender.send(messagePreparator);
} catch (MailException e) {
e.printStackTrace();
}
}
}
This is my Test Class
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(Application.class)
public class MailClientTest {
#Autowired
private MailClient mailClient;
private GreenMail smtpServer;
#Before
public void setUp() throws Exception {
smtpServer = new GreenMail(new ServerSetup(25, null, "smtp"));
smtpServer.start();
}
#Test
public void shouldSendMail() throws Exception {
//given
String recipient = "amadeu.cabanilles#gmail.com";
String message = "Test message content";
//when
mailClient.prepareAndSend(recipient, message);
//then
String content = "<span>" + message + "</span>";
assertReceivedMessageContains(content);
}
private void assertReceivedMessageContains(String expected) throws IOException, MessagingException {
MimeMessage[] receivedMessages = smtpServer.getReceivedMessages();
assertEquals(1, receivedMessages.length);
String content = (String) receivedMessages[0].getContent();
System.out.println(content);
assertTrue(content.contains(expected));
}
#After
public void tearDown() throws Exception {
smtpServer.stop();
}
}
Executing the Test in my computer is OK, I pass the test but I don't receive any email.
You don't receive any email because this integration test uses local testing SMTP server stub - GreenMail. The test doesn't send real emails, only verifies if the mail is prepared and sent correctly if a real SMTP server is available in the production.
In order to send emails from your local environment, you need to setup some SMTP server, but then, automated verification if the mail is actually sent is a completely different story.