I am trying to implement Spring integration with MQTT. I am using Mosquitto as MQTT broker. with the reference to docs provided in the following link. I have created a project and added all the required jar files. when i execute MQTTJavaApplication.
public class MqttJavaApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MqttJavaApplication.class)
.web(false)
.run(args);
}
#Bean
public MessageChannel mqttInputChannel() {
return new DirectChannel();
}
#Bean
public MqttPahoMessageDrivenChannelAdapter inbound() {
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883", "test",
"sample");
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannel());
return adapter;
}
#Bean
#ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler handler() {
return new MessageHandler() {
#Override
public void handleMessage(Message<?> message) {
System.out.println("Test##########"+message.getPayload());
}
};
}
}
I am getting following error when i publish a message via MQTT broker.
[2015-11-23 10:08:19.545] boot - 8100 INFO [main] --- AnnotationConfigApplicationContext: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#2d0e1c: startup date [Mon Nov 23 10:08:19 IST 2015]; root of context hierarchy
[2015-11-23 10:08:19.831] boot - 8100 INFO [main] --- PropertiesFactoryBean: Loading properties file from URL [jar:file:/D:/IoTWorkspace/MQTTTest/WebContent/WEB-INF/lib/spring-integration-core-4.2.1.RELEASE.jar!/META-INF/spring.integration.default.properties]
[2015-11-23 10:08:20.001] boot - 8100 INFO [main] --- DefaultLifecycleProcessor: Starting beans in phase 1073741823
[2015-11-23 10:08:20.104] boot - 8100 INFO [main] --- MqttPahoMessageDrivenChannelAdapter: started inbound
[2015-11-23 10:08:20.112] boot - 8100 INFO [main] --- MqttJavaApplication: Started MqttJavaApplication in 1.602 seconds (JVM running for 2.155)
[2015-11-23 10:13:04.564] boot - 8100 ERROR [MQTT Call: test] --- MqttPahoMessageDrivenChannelAdapter: Unhandled exception for GenericMessage [payload=Testing Subscription, headers={timestamp=1448253784563, id=cd5be974-3b19-8317-47eb-1c139725be24, mqtt_qos=0, mqtt_topic=sample, mqtt_retained=false, mqtt_duplicate=false}]
org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'unknown.channel.name'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:81)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:442)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:392)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:105)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.messageArrived(MqttPahoMessageDrivenChannelAdapter.java:262)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.handleMessage(CommsCallback.java:336)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:148)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:153)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:120)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
... 10 more
[2015-11-23 10:13:04.613] boot - 8100 ERROR [MQTT Call: test] --- MqttPahoMessageDrivenChannelAdapter: Lost connection:MqttException; retrying...
[2015-11-23 10:13:04.614] boot - 8100 ERROR [MQTT Call: test] --- MqttPahoMessageDrivenChannelAdapter: Failed to schedule reconnect
java.lang.NullPointerException
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.scheduleReconnect(MqttPahoMessageDrivenChannelAdapter.java:228)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.connectionLost(MqttPahoMessageDrivenChannelAdapter.java:255)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.connectionLost(CommsCallback.java:229)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.shutdownConnection(ClientComms.java:339)
at org.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:171)
at java.lang.Thread.run(Thread.java:722)
[2015-11-23 10:13:04.617] boot - 8100 INFO [Thread-0] --- AnnotationConfigApplicationContext: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#2d0e1c: startup date [Mon Nov 23 10:08:19 IST 2015]; root of context hierarchy
[2015-11-23 10:13:04.619] boot - 8100 INFO [Thread-0] --- DefaultLifecycleProcessor: Stopping beans in phase 1073741823
[2015-11-23 10:13:04.622] boot - 8100 ERROR [Thread-0] --- MqttPahoMessageDrivenChannelAdapter: Exception while unsubscribing
Client is not connected (32104)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:27)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.sendNoWait(ClientComms.java:132)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.unsubscribe(MqttAsyncClient.java:707)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.unsubscribe(MqttAsyncClient.java:682)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.doStop(MqttPahoMessageDrivenChannelAdapter.java:124)
at org.springframework.integration.endpoint.AbstractEndpoint.doStop(AbstractEndpoint.java:145)
at org.springframework.integration.endpoint.AbstractEndpoint.stop(AbstractEndpoint.java:128)
at org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:229)
at org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:51)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:363)
at org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:202)
at org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:118)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:966)
at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:893)
[2015-11-23 10:13:04.623] boot - 8100 ERROR [Thread-0] --- MqttPahoMessageDrivenChannelAdapter: Exception while disconnecting
Client is disconnected (32101)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:27)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.disconnect(ClientComms.java:405)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.disconnect(MqttAsyncClient.java:524)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.disconnect(MqttAsyncClient.java:493)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.disconnect(MqttAsyncClient.java:500)
at org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter.doStop(MqttPahoMessageDrivenChannelAdapter.java:131)
at org.springframework.integration.endpoint.AbstractEndpoint.doStop(AbstractEndpoint.java:145)
at org.springframework.integration.endpoint.AbstractEndpoint.stop(AbstractEndpoint.java:128)
at org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:229)
at org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:51)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:363)
at org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:202)
at org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:118)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:966)
at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:893)
[2015-11-23 10:13:04.624] boot - 8100 INFO [Thread-0] --- MqttPahoMessageDrivenChannelAdapter: stopped inbound
Please find below stack trace after adding #SpringBootApplication Annotation
[2015-11-26 10:55:46.571] boot - 5524 INFO [main] --- AnnotationConfigApplicationContext: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#562d4b: startup date [Thu Nov 26 10:55:46 IST 2015]; root of context hierarchy
[2015-11-26 10:55:46.572] boot - 5524 WARN [main] --- AnnotationConfigApplicationContext: Exception thrown from ApplicationListener handling ContextClosedEvent
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext#562d4b: startup date [Thu Nov 26 10:55:46 IST 2015]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:337)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:324)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1025)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
at com.igate.MqttJavaApplication.main(MqttJavaApplication.java:32)
[2015-11-26 10:55:46.594] boot - 5524 WARN [main] --- AnnotationConfigApplicationContext: Exception thrown from LifecycleProcessor on context close
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.context.annotation.AnnotationConfigApplicationContext#562d4b: startup date [Thu Nov 26 10:55:46 IST 2015]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:350)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1033)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:329)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
at com.igate.MqttJavaApplication.main(MqttJavaApplication.java:32)
Exception in thread "main" java.lang.IllegalStateException: At least one base package must be specified
at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:121)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:214)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:149)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:135)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:260)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:203)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:617)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130)
at com.igate.MqttJavaApplication.main(MqttJavaApplication.java:32)
Yep! That's true. Without #SpringBootApplication I have the same StackTrace.
The Spring Boot stuff includes IntegrationAutoConfiguration who is responsible for subscribers and TaskScheduler bean population.
Probably too late to answer but hope it might help some beginner.
Few Things:-
Declare #SpringBootApplication in your main class to let the project know its a spring boot application
For the 2nd Error, Define base package of the project where spring boot will refer for configuration files etc. To do so, add #ComponentScan({"package-name"}) at class level.
Sample Example:-
#SpringBootApplication
#ComponentScan({"package-name"})
public class Main {
...
}
I am trying to download a file from a Https url which requires Basic authentication. I am using HTTP4
I am trying to download from url - https://ebc.cybersource.com/ebc/DownloadReport/xxx.csv?authMethod=Basic&authUsername=scott&authPassword=tiger
After the file is downloaded I need to save it to a folder. Here's what my code looks like
from(xxx)
.to("http4://ebc.cybersource.com/ebc/DownloadReport/xxx.csv?authMethod=Basic&authUsername=scott&authPassword=tiger")
.to("file:target/messages/download");
Here's the error I get -
java.lang.UnsupportedOperationException: Cannot consume from http endpoint
at org.apache.camel.component.http4.HttpEndpoint.createConsumer(HttpEndpoint.java:120)
at org.apache.camel.impl.EventDrivenConsumerRoute.addServices(EventDrivenConsumerRoute.java:65)
at org.apache.camel.impl.DefaultRoute.onStartingServices(DefaultRoute.java:85)
at org.apache.camel.impl.RouteService.warmUp(RouteService.java:158)
at org.apache.camel.impl.DefaultCamelContext.doWarmUpRoutes(DefaultCamelContext.java:3090)
at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:3020)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRoutes(DefaultCamelContext.java:2797)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:2653)
at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:167)
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:2467)
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:2463)
at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:2486)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:2463)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:2432)
at com.dinesh.MainApp.main(MainApp.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Now the documentation says I need to use HttpContext,
public class HttpContextFactory {
private String httpHost = "localhost";
private String httpPort = 9001;
private BasicHttpContext httpContext = new BasicHttpContext();
private BasicAuthCache authCache = new BasicAuthCache();
private BasicScheme basicAuth = new BasicScheme();
public HttpContext getObject() {
authCache.put(new HttpHost(httpHost, httpPort), basicAuth);
httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
return httpContext;
}
// getter and setter
}
I tried that but I am still getting errors.
UPDATE
I am actually using a quartz scheduler to trigger
from("quartz2://foo?cron=0/2+*+*+?+*+MON-FRI").multicast().stopOnException().to("direct:downLoadFile");
from("direct:downLoadFile")
.to("http4://ebc.cybersource.com/ebc/DownloadReport/2015/04/16/us_voip/us_voip.au.response.ss.csv?authMethod=Basic&authUserName=xxxx&authPassword=yyyy")
.log("File Downloaded");
When I run this I get the below error.
[ main] QuartzComponent INFO Starting scheduler.
[ main] QuartzScheduler INFO Scheduler DefaultQuartzScheduler-camel-1_$_NON_CLUSTERED started.
[ main] DefaultCamelContext INFO Total 2 routes, of which 2 is started.
[ main] DefaultCamelContext INFO Apache Camel 2.15.1 (CamelContext: camel-1) started in 0.938 seconds
[artzScheduler-camel-1_Worker-1] RetryExec INFO I/O exception (java.net.SocketException) caught when processing request to {}->http://ebc.cybersource.com:80: Connection reset
[artzScheduler-camel-1_Worker-1] RetryExec INFO Retrying request to {}->http://ebc.cybersource.com:80
[artzScheduler-camel-1_Worker-1] RetryExec INFO I/O exception (java.net.SocketException) caught when processing request to {}->http://ebc.cybersource.com:80: Connection reset
[artzScheduler-camel-1_Worker-1] RetryExec INFO Retrying request to {}->http://ebc.cybersource.com:80
[artzScheduler-camel-1_Worker-1] RetryExec INFO I/O exception (java.net.SocketException) caught when processing request to {}->http://ebc.cybersource.com:80: Connection reset
[artzScheduler-camel-1_Worker-1] RetryExec INFO Retrying request to {}->http://ebc.cybersource.com:80
[artzScheduler-camel-1_Worker-1] DefaultErrorHandler ERROR Failed delivery for (MessageId: ID-CN-AHONNAVA-LP-49362-1430485742705-0-1 on ExchangeId: ID-CN-AHONNAVA-LP-49362-1430485742705-0-3). Exhausted after delivery attempt: 1 caught: java.net.SocketException: Connection reset
Message History
---------------------------------------------------------------------------------------------------------------------------------------
RouteId ProcessorId Processor Elapsed (ms)
[route1 ] [route1 ] [quartz2://foo?cron=0%2F2+*+*+%3F+*+MON-FRI ] [ 523]
[route1 ] [multicast1 ] [multicast ] [ 520]
[route1 ] [to1 ] [direct:downLoadFile ] [ 513]
[route2 ] [to2 ] [http4://ebc.cybersource.com/ebc:443/DownloadReport/2015/04/16/us_voip/us_voip.] [ 510]
Exchange
---------------------------------------------------------------------------------------------------------------------------------------
Exchange[
Id ID-CN-AHONNAVA-LP-49362-1430485742705-0-3
ExchangePattern InOnly
Headers {breadcrumbId=ID-CN-AHONNAVA-LP-49362-1430485742705-0-1, calendar=null, CamelRedelivered=false, CamelRedeliveryCounter=0, fireTime=Fri May 01 09:09:04 EDT 2015, jobDetail=JobDetail 'Camel_camel-1.foo': jobClass: 'org.apache.camel.component.quartz2.CamelJob concurrentExectionDisallowed: false persistJobDataAfterExecution: false isDurable: false requestsRecovers: false, jobInstance=org.apache.camel.component.quartz2.CamelJob#6e61a2e3, jobRunTime=-1, mergedJobDataMap=org.quartz.JobDataMap#2a207ff6, nextFireTime=Fri May 01 09:09:06 EDT 2015, previousFireTime=null, refireCount=0, result=null, scheduledFireTime=Fri May 01 09:09:04 EDT 2015, scheduler=org.quartz.impl.StdScheduler#1e79d438, trigger=Trigger 'Camel_camel-1.foo': triggerClass: 'org.quartz.impl.triggers.CronTriggerImpl calendar: 'null' misfireInstruction: 1 nextFireTime: Fri May 01 09:09:06 EDT 2015, triggerGroup=Camel_camel-1, triggerName=foo}
BodyType null
Body [Body is null]
]
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:136)
at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:152)
at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:270)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:140)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:161)
at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:153)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:271)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:254)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.apache.camel.component.http4.HttpProducer.executeMethod(HttpProducer.java:258)
at org.apache.camel.component.http4.HttpProducer.process(HttpProducer.java:158)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:129)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:448)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:51)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:129)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:448)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.MulticastProcessor.doProcessSequential(MulticastProcessor.java:590)
at org.apache.camel.processor.MulticastProcessor.doProcessSequential(MulticastProcessor.java:518)
at org.apache.camel.processor.MulticastProcessor.process(MulticastProcessor.java:227)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.loadbalancer.QueueLoadBalancer.process(QueueLoadBalancer.java:44)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109)
at org.apache.camel.processor.loadbalancer.LoadBalancerSupport.process(LoadBalancerSupport.java:87)
at org.apache.camel.component.quartz2.CamelJob.execute(CamelJob.java:56)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
[artzScheduler-camel-1_Worker-1] CamelJob ERROR Error processing exchange. Exchange[Message: [Body is null]]. Caused by: [org.quartz.JobExecutionException - org.apache.camel.CamelExchangeException: Sequential processing failed for number 0. Exchange[Message: [Body is null]]. Caused by: [java.net.SocketException - Connection reset]]
[artzScheduler-camel-1_Worker-1] JobRunShell INFO Job Camel_camel-1.foo threw a JobExecutionException:
org.quartz.JobExecutionException: org.apache.camel.CamelExchangeException: Sequential processing failed for number 0. Exchange[Message: [Body is null]]. Caused by: [java.net.SocketException - Connection reset] [See nested exception: org.apache.camel.CamelExchangeException: Sequential processing failed for number 0. Exchange[Message: [Body is null]]. Caused by: [java.net.SocketException - Connection reset]]
at org.apache.camel.component.quartz2.CamelJob.execute(CamelJob.java:59)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
FINAL UPDATE: SOLVED
Thanks to #Claus Ibsen who provided the correct component. All I had to was use use https4 instead of http. Note this information is missing in camel documentation. Here's the final code, that download the file from the website and saves in in target/download folder.
import org.apache.camel.builder.RouteBuilder;
import org.apache.commons.codec.binary.Base64;
/**
* Created by darora on 4/30/2015.
*/
public class SchedulerRoute extends RouteBuilder {
//TODO Move this to properties file
String userCredentials ="userName:Password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
#Override
public void configure() throws Exception {
//from("timer://foo?fixedRate=true&period=6000").to("bean:logBean?method=sayHello");
//from("scheduler://foo?delay=500").to("bean:logBean?method=sayHello");
from("quartz2://foo?cron=0/2+*+*+?+*+MON-FRI").multicast().stopOnException().to("direct:downLoadFile","direct:myBean");
from("direct:myBean").log("Scheduler Started one more time .....")
.to("bean:downLoadFileBean?method=updatedatabase");
from("direct:downLoadFile").log("Scheduler Started one more time .....")
.setHeader("Authorization",constant(basicAuth))
.to("https4://ebc.cybersource.com/ebc/DownloadReport/2015/04/16/us_voip/us_voip.au.response.ss.csv")
.to("file:target/download")
.log("file is downloaded ..........");
}
}
You cannot start from http4 as the exception tells you, you need a timer or something to trigger the route
from("timer:foo?period=5000")
.to("http4://ebc.cybersource.com/ebc/DownloadReport/xxx.csv?authMethod=Basic&authUsername=scott&authPassword=tiger")
.to("file:target/messages/download");
In this example the timer triggers every 5th second.
I have weired problem with a JMS Listener container. In case I disable the listener container, half of messages are delivered and processed by listener. Here is my Spring configuration:
<bean id="ConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="JmsXA" />
</bean>
<bean id="testQueue" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="queue/test" />
</bean>
<bean id="listener" class="eu.cuptech.jms.listener.ExampleListener" />
<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="ConnectionFactory" />
<property name="destination" ref="testQueue" />
<property name="messageListener" ref="listener" />
<property name="concurrency" value="1" />
</bean>
ExampleListener is here:
package eu.cuptech.jms.listener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class ExampleListener implements MessageListener {
public void onMessage(Message message) {
try {
String msg = ((TextMessage) message).getText();
System.out.println("MESSAGE TEXT: " + msg);
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
}
Client is Spring MVC Controller with following methods:
send10Messages method (common JMS client):
#Resource(name="ConnectionFactory")
private ConnectionFactory connectionFactory;
#Resource(name="testQueue")
private Queue testQueue;
#RequestMapping(value="send10", method = RequestMethod.GET)
public String send10Messages(ModelMap model, HttpSession session) throws Exception {
sendTextMessages(10, "Test message: ");
return "redirect:/info";
}
private void sendTextMessages(int count, final String prefix) throws Exception {
Connection connection = null;
Session session = null;
MessageProducer messageProducer = null;
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer = session.createProducer(testQueue);
connection.start();
TextMessage message = session.createTextMessage();
int i = 0;
while (i < count) {
message.setText(prefix + ++i);
messageProducer.send(message);
Thread.sleep(250);
System.out.println("Message " + prefix + i + " sent.");
}
} finally {
try {
if (messageProducer != null)
messageProducer.close();
if (connection != null)
connection.close();
if (session != null)
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
disableListener method:
#Resource(name="listenerContainer")
private DefaultMessageListenerContainer listenerContainer;
#RequestMapping(value="disableListener", method = RequestMethod.GET)
public String disableListener(ModelMap model, HttpSession session) {
listenerContainer.stop(new Runnable() {
public void run() {
System.out.println("JMS Listener stopped.");
}
});
return "redirect:/info";
}
enableListener method
#Resource(name="listenerContainer")
private DefaultMessageListenerContainer listenerContainer;
#RequestMapping(value="enableListener", method = RequestMethod.GET)
public String enableListener(ModelMap model, HttpSession session) {
listenerContainer.start();
return "redirect:/info";
}
When I start server and send messages I got this log (It is OK):
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 1
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 1 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 2
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 2 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 3
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 3 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 4
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 4 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 5
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 5 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 6
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 6 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 7
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 7 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 8
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 8 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 9
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 9 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 10
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 10 sent.
When I disable the listener container and send messages again I got this:
INFO [stdout] (listenerContainer-1) JMS Listener stopped.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 1
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 1 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 2 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 3
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 3 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 4 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 5
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 5 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 6 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 7
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 7 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 8 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 9
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 9 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 10 sent.
When I enable the listener container again I got this:
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 2
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 4
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 6
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 8
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 10
The problem is that every odd message is processed by listener even if listener is disabled. I expact that all messages will be delivered and processed by listener when I enable the listener container and no message will be processed when I disable it.
I'm using Spring 3.2.4.RELEASE (I was trying 3.2.3.RELEASE too), HornetQ 2.3.0.Final as remote JMS Server and JBoss 7.3.1.Final as App server.
My guess is that you are loading the container into both the web context (DispatcherServlet's context) and the root context (ContextLoaderListener's context). Which means you have 2 containers and you are only stopping the one in the servlet context.
Turn on DEBUG logging for org.springframework and examine the bean initialization logs.
It probably should be just in the root context.
In my application I am sending mail using spring. it works fine when I am sending mail from any gmail id, but when I am sending from another smtp server then mail is not sending.
My spring configuration for gmail:
<beans>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="diganta.XXXXX#gmail.com" />
<property name="password" value="******" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="requestToAcceptOrDeny" class="com.edfx.adb.mail.RequestToAcceptOrDeny">
<property name="mailSender" ref="mailSender" />
</bean>
</beans>
But when I change the configuration into :
<property name="host" value="mail.mycompany.co.in" />
<property name="port" value="25" />
<property name="username" value="XXX#mycompany.co.in" />
<property name="password" value="abc123" />
then no exception is generating, but mail is also not sending, password is also not checking, ie given password is right or not. I can't understand where I have done wrong.
Can anyone help me? Thanks
Update-1
16:29:23,524 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate: select user0_.ID as ID7_0_, user0_.CREATE_TIMESTAMP as CREATE2_7_0_, user0_.LAST_UPDATE_TIMESTAMP as LAST3_7_0_, user0_.VERSION as VERSION7_0_, user0_.ACTIVE as ACTIVE7_0_, user0_.DATE_OF_BIRTH as DATE6_7_0_, user0_.DATE_OF_JOINING as DATE7_7_0_, user0_.DATE_OF_RELEASE as DATE8_7_0_, user0_.FIRST_NAME as FIRST9_7_0_, user0_.FULL_NAME as FULL10_7_0_, user0_.HOME_PHONE as HOME11_7_0_, user0_.HOME_POSTAL_ADDRESS as HOME12_7_0_, user0_.LAST_NAME as LAST13_7_0_, user0_.MAIL as MAIL7_0_, user0_.MOBILE as MOBILE7_0_, user0_.ROLE as ROLE7_0_, user0_.USERNAME as USERNAME7_0_ from USER user0_ where user0_.ID=?
16:29:23,534 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: JavaMail version 1.4.4
16:29:23,534 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: Tables of loaded providers
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
16:29:23,594 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Sending email ....
16:29:23,594 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
16:29:23,604 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: useEhlo true, useAuth true
16:29:23,604 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: trying to connect to host "mail.mycompany.co.in", port 25, isSSL false
16:29:24,634 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 220 mail.mycompany.co.in ESMTP Postfix
16:29:24,644 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: connected to host "mail.mycompany.co.in", port: 25
16:29:24,644 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:24,644 INFO [stdout] (http-localhost-127.0.0.1-8080-1) EHLO EDFX-DESKTOP-28
16:29:24,865 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-mail.mycompany.co.in
16:29:24,865 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-PIPELINING
16:29:24,865 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-SIZE 10240000
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-VRFY
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-ETRN
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-ENHANCEDSTATUSCODES
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-8BITMIME
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 DSN
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "PIPELINING", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "SIZE", arg "10240000"
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "VRFY", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "ETRN", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "8BITMIME", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "DSN", arg ""
16:29:24,895 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: use8bit false
16:29:24,895 INFO [stdout] (http-localhost-127.0.0.1-8080-1) MAIL FROM:<Temp#EDFX-DESKTOP-28>
16:29:25,135 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 2.1.0 Ok
16:29:25,135 INFO [stdout] (http-localhost-127.0.0.1-8080-1) RCPT TO:<diganta.xxx#gmail.com>
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 2.1.5 Ok
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Verified Addresses
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: diganta.xxxx#gmail.com
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DATA
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 354 End data with <CR><LF>.<CR><LF>
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Date: Fri, 3 May 2013 16:29:24 +0530 (IST)
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) To: diganta.xxxx#gmail.com
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Message-ID: <628313650.2.1367578764895.JavaMail.Temp#EDFX-DESKTOP-28>
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Subject: Request to Remove Rounak Dey's Activity's Manager privilege from
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) activity EFXL13001
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) MIME-Version: 1.0
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Type: multipart/mixed;
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) boundary="----=_Part_0_263230409.1367578763564"
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_0_263230409.1367578763564
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Type: multipart/related;
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) boundary="----=_Part_1_1514490209.1367578763584"
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_1_1514490209.1367578763584
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Type: text/html; charset=us-ascii
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Transfer-Encoding: 7bit
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) <html><body><a href=http://localhost:8080/ActivityDatabase/req/AcceptOrDenyPermision.xhtml?activityId=EFXL13001&uniqueId=7fe18301-0bde-48da-a7d1-2bbe43b95e98&emailId=diganta.xxxx#gmail.com>Accept Or Deny request..</a></body></html>
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_1_1514490209.1367578763584--
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_0_263230409.1367578763564--
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) .
16:29:25,855 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 2.0.0 Ok: queued as 164B322AB7
16:29:25,855 INFO [stdout] (http-localhost-127.0.0.1-8080-1) QUIT
16:29:26,046 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 221 2.0.0 Bye
I also encountered same situation as OP. I use Spring mail to send mail and test with a gmail account work perfectly then when I apply my company mail, it didn't throw any exception but no mail received.
It took me several hours of googling, seeing debug log and trying many config but not work.
Then I write a java program using javax.mail to test and everything works. I realize the difference is in the java program I set From mail account (same as username property in spring config).
E.g. that is
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("XXX#mycompany.co.in"));
That solved the problem.
Your server doesn't support STARTTLS and won't let you authenticate unless you connect over SSL to begin with. Without authenticating, it won't deliver mail outside of your domain. Assuming you're using a new version of JavaMail, set the property "mail.smtp.ssl" to "true".
package com.karthik.spring;
import java.io.IOException;
import java.io.InputStream;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
#Controller
#RequestMapping("/sendEmail.do")
public class SendEmailAttachController {
#Autowired
private JavaMailSender mailSender;
#RequestMapping(method = RequestMethod.POST)
public String sendEmail(HttpServletRequest request,
final #RequestParam CommonsMultipartFile attachFile) {
// Input here
final String emailTo = request.getParameter("mailTo");
final String subject = request.getParameter("subject");
final String yourmailid = request.getParameter("yourmail");
final String message = request.getParameter("message");
// Logging
System.out.println("emailTo: " + emailTo);
System.out.println("subject: " + subject);
System.out.println("Your mail id is: "+yourmailid);
System.out.println("message: " + message);
System.out.println("attachFile: " + attachFile.getOriginalFilename());
mailSender.send(new MimeMessagePreparator() {
#Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper messageHelper = new MimeMessageHelper(
mimeMessage, true, "UTF-8");
messageHelper.setTo(emailTo);
messageHelper.setSubject(subject);
messageHelper.setReplyTo(yourmailid);
messageHelper.setText(message);
// Attachment with mail
String attachName = attachFile.getOriginalFilename();
if (!attachFile.equals("")) {
messageHelper.addAttachment(attachName, new InputStreamSource() {
#Override
public InputStream getInputStream() throws IOException {
return attachFile.getInputStream();
}
});
}
}
});
return "Result";
}
}
**spring-mvc.xml**
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.karthik.spring" />
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="xxxx#gmail.com" />
<property name="password" value="xxxx" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">Error</prop>
</props>
</property>
</bean>
</beans>