MongoDB change stream replica set recovery - spring

I implemented MongoDB change streams with Spring and it works fine when the replica set primary node is up.
#Service
public class ChangeEventService {
private static final Logger logger = LoggerFactory.getLogger(ChangeEventService.class);
private final MongoClient mongoClient;
public ChangeEventService(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
#PostConstruct
public void subscribe() {
MongoDatabase db = mongoClient.getDatabase("experiment");
MongoCollection<Document> collection = db.getCollection("debug");
Block<ChangeStreamDocument<Document>> printBlock = changeStreamDocument -> {
logger.info("Received: {}", changeStreamDocument.getFullDocument().toString());
BsonDocument resumeToken = changeStreamDocument.getResumeToken();
};
collection.watch().forEach(printBlock);
logger.info("Consumer is ready to process");
}
}
Then I shut down the primary node of the replica set. I was expecting the change stream to wait for the replica set to elect a new primary and continue to get the data changes. The actual behavior is an application crash.
From the logs I can see that the connection to the primary (27000) is closed which is expected, then it seems to try to open a connection to one of the secondary (27001) but can't because the pool has been closed.
From the documentation: "The change stream is bound to a collection and change stream documents are iterated with a cursor. This cursor remains open until it is explicitly closed, as long as a connection to the MongoDB deployment remains open and the collection exists."
2018-05-02 12:03:03.424 INFO 9560 --- [ main] c.e.m.service.ChangeEventService : Received: Document{{_id=5ae98cd7dcc8921c94d5f9e5, _class=com.mongodb.BasicDBObject, uuid=4f836d00-efc3-4d48-956a-af4dbfed90e7, now=Wed May 02 12:03:03 CEST 2018}}
2018-05-02 12:03:06.500 WARN 9560 --- [ main] org.mongodb.driver.connection : Got socket exception on connection [connectionId{localValue:4, serverValue:8}] to localhost:27000. All connections to localhost:27000 will be closed.
2018-05-02 12:03:06.501 INFO 9560 --- [ main] org.mongodb.driver.connection : Closed connection [connectionId{localValue:4, serverValue:8}] to localhost:27000 because there was a socket exception raised by this connection.
2018-05-02 12:03:07.502 INFO 9560 --- [ main] org.mongodb.driver.connection : Closed connection [connectionId{localValue:6}] to localhost:27000 because there was a socket exception raised by this connection.
2018-05-02 12:03:07.504 WARN 9560 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'changeEventService': Invocation of init method failed; nested exception is com.mongodb.MongoSocketOpenException: Exception opening socket
2018-05-02 12:03:07.505 INFO 9560 --- [localhost:27000] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27000
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128) ~[mongodb-driver-core-3.6.3.jar:na]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_161]
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_161]
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_161]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_161]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_161]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_161]
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_161]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_161]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_161]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongodb-driver-core-3.6.3.jar:na]
... 3 common frames omitted
2018-05-02 12:03:07.507 INFO 9560 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:7, serverValue:181}] to localhost:27001
2018-05-02 12:03:07.508 INFO 9560 --- [ main] org.mongodb.driver.connection : Closed connection [connectionId{localValue:7, serverValue:181}] to localhost:27001 because the pool has been closed.
2018-05-02 12:03:07.511 INFO 9560 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2

There are two things here:
at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongodb-driver-core-3.6.3.jar:na]
There is a bug with MongoDB Java driver v3.6.3, where change streams cursor does not resume when there's an attempt to kill the existing cursor fails. This is described in JAVA-2821, and fixed in version 3.7.0 onwards.
collection.watch().forEach(printBlock);
The watch() method does't actually contact the server, instead you should use an iterator method. For example:
MongoCursor<ChangeStreamDocument<Document>> cursor = collection.watch().iterator();
ChangeStreamDocument<Document> next = cursor.next();
while(cursor.hasNext()){
next = cursor.next();
System.out.println(next);
}
See also Spec: Resumable Error for the definition of error that is considered resumable.

Related

Setup of JMS message listener invoker failed for destination 'TESTQUEUE' - trying to recover. Cause: null

My application run well in my local machine and i am able to connect to IBM MQ and poll message. I am facing below issue in polling after i deploy my application on open shift.
Error:
2022-05-03 02:02:24.418 DEBUG 7 --- [ main] o.s.j.c.CachingConnectionFactory : Established shared JMS Connection: com.ibm.mq.jms.MQConnection#397a10df
2022-05-03 02:02:24.422 DEBUG 7 --- [ main] o.s.j.l.DefaultMessageListenerContainer : Established shared JMS Connection
2022-05-03 02:02:24.423 DEBUG 7 --- [ main] o.s.j.l.DefaultMessageListenerContainer : Resumed paused task: org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker#55c46ec1
2022-05-03 02:02:24.623 INFO 7 --- [ main] c.c.com.poc.ibmmq.DemoApplication : Started DemoApplication in 84.7 seconds (JVM running for 103.063)
2022-05-03 02:02:30.922 WARN 7 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Setup of JMS message listener invoker failed for destination 'TESTQUEUE' - trying to recover. Cause: null
java.lang.NullPointerException: null
at com.ibm.mq.jms.MQSession.getTransacted(MQSession.java:876) ~[com.ibm.mq.allclient-9.1.5.0.jar!/:9.1.5.0 - p915-L200316]
at com.ibm.mq.jms.MQSession.<init>(MQSession.java:262) ~[com.ibm.mq.allclient-9.1.5.0.jar!/:9.1.5.0 - p915-L200316]
at com.ibm.mq.jms.MQConnection.createSession(MQConnection.java:336) ~[com.ibm.mq.allclient-9.1.5.0.jar!/:9.1.5.0 - p915-L200316]
at org.springframework.jms.connection.SingleConnectionFactory.createSession(SingleConnectionFactory.java:482) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.jms.connection.CachingConnectionFactory.getSession(CachingConnectionFactory.java:233) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.jms.connection.SingleConnectionFactory$SharedConnectionInvocationHandler.invoke(SingleConnectionFactory.java:649) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at com.sun.proxy.$Proxy148.createSession(Unknown Source) ~[na:na]
at org.springframework.jms.support.JmsAccessor.createSession(JmsAccessor.java:208) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer.access$1500(DefaultMessageListenerContainer.java:126) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.initResourcesIfNecessary(DefaultMessageListenerContainer.java:1213) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1188) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1179) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1076) ~[spring-jms-5.2.8.RELEASE.jar!/:5.2.8.RELEASE]
at java.base/java.lang.Thread.run(Unknown Source) ~[na:na]
Code:
My configuration:
#Bean
public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
setSSLProperties();
configurer.configure(factory,connectionFactory);
return factory;
}
Receiver:
#JmsListener(destination = "${response.queue}", containerFactory = "myFactory")
public void receiveMessage(JmsMessage test) throws JMSException {
logger.info("Response Sent {}", test.toString());
}

IntegrationFlow Exception Handling

I am trying to create a Flow for message as follow:
TCPinboundAdapter ----> Message Brocker(ActiveMQ)
Flow:
This flow is created in the following way
The message is received via TCP connection to TCP Adapter which may be client or server.
The message received to TCP adapter is send to JMS Adapter(ActiveMQ Broker).
The code is as follow:
#EventListener
public void handleTcpConnectionClientEvent(TcpConnectionFailedEvent event){
TcpNioClientConnectionFactory tcp = (TcpNioClientConnectionFactory)event.getSource();
System.out.println(tcp);
System.out.println("connection exception client :::"+event.getSource());
this.status = event.toString();
}
#EventListener
public void handleTcpConnectionServerExceptionEvent(TcpConnectionServerExceptionEvent event){
System.out.println("connection exception server :::");
this.status = event.toString();
}
// this method is invoked when the connection with the sever got disconnected
#EventListener
public void handleTcpConnectionServerEvent(TcpConnectionExceptionEvent event){
System.out.println("connection exception serversssss :::"+event.getConnectionFactoryName());
this.status = event.toString();
}
//when the connection got established (not for first time)
#EventListener
public void handleTcpConnectionCloseEvent(TcpConnectionOpenEvent event){
System.out.println("connection opened :::"+event.getConnectionFactoryName());
// status = event.toString();
}
// create a server connection and flow to JMS
private void createServerConnection(HostConnection hostConnection) throws Throwable{
this.status = "success";
// IntegrationFlow flow;
IntegrationFlowRegistration theFlow;
IntegrationFlow flow =
IntegrationFlows.from(Tcp.inboundAdapter(Tcp.netServer(1234)
.serializer(customSerializer)
.deserializer(customSerializer)
.id(hostConnection.getConnectionNumber()).soTimeout(10000)))
.enrichHeaders(f->f.header("abc","abc")))
.channel(directChannel())
.handle(Jms.outboundAdapter(ConnectionFactory())
.destination("jmsInbound"))
.get();
theFlow = this.flowContext.registration(flow).id("test.flow").register();
if(this.status.equals("success"))
createInboundFlow(hostConnection);
// startConnection(hostConnection.getConnectionNumber());
}
Issue:
This flow is created successfully and get registered to Application Context when there is no Exception.
But in case When there is an exception i.e (BindException)
When creating server to a particular port and the Port is already used
then it raise BindException then also the flow got registered
So, we want that the flow should not be registered when there is exception in any of the flow component below.
IntegrationFlowRegistration theFlow;
IntegrationFlow flow =
IntegrationFlows.from(Tcp.inboundAdapter(Tcp.netServer(1234)
.serializer(customSerializer)
.deserializer(customSerializer)
.id("server").soTimeout(10000)))
.enrichHeaders(f->f.header("abc","abc")))
.channel(directChannel())
.handle(Jms.outboundAdapter(ConnectionFactory())
.destination("jmsInbound"))
.get();
theFlow =this.flowContext.registration(flow).id("test.flow").register();
There are various Listener implemented to check exception in TCP connection try{}catch() block don't raise any exception.
Please provide a suitable approach to handle Exceptions for adapters currently I am using Listeners for various event to know there is something wrong with the tcp adapters.
After applying this approach provided by Mr. Artem Bilan
#EventListener
public void handleTcpConnectionServerExceptionEvent(TcpConnectionServerExceptionEvent event){
System.out.println("connection exception server :::"+event);
this.status = event.getCause().getMessage();
AbstractConnectionFactory server = (AbstractConnectionFactory)event.getSource();
System.out.println(server.getComponentName());
this.flowContext.remove(server.getComponentName()+"out.flow");
}
I am able to remove the flow using FlowId but I am not able to catch the Exception
The Exception below is printing on the console and can't be handled Even I have changed method to
private void createServerConnection(HostConnection hostConnection) throws Throwable{}
and handled these Exception with try{}catch(Throwable t){} in calling function
Exception in thread "pool-4-thread-1" java.lang.NullPointerException
Exception is described in more elaborated form in the logs provided below:
2018-05-17 21:01:40.850 INFO 18332 --- [nio-8080-exec-4]
.s.i.i.t.c.TcpNetServerConnectionFactory : started Co123, port=1234
2018-05-17 21:01:40.850 INFO 18332 --- [nio-8080-exec-4] o.s.i.ip.tcp.TcpReceivingChannelAdapter : started org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter#3
2018-05-17 21:01:40.851 ERROR 18332 --- [pool-5-thread-1] .s.i.i.t.c.TcpNetServerConnectionFactory : Error on ServerSocket; port = 1234
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method) ~[na:1.8.0_111]
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source) ~[na:1.8.0_111]
at java.net.AbstractPlainSocketImpl.bind(Unknown Source) ~[na:1.8.0_111]
at java.net.PlainSocketImpl.bind(Unknown Source) ~[na:1.8.0_111]
at java.net.ServerSocket.bind(Unknown Source) ~[na:1.8.0_111]
at java.net.ServerSocket.<init>(Unknown Source) ~[na:1.8.0_111]
at java.net.ServerSocket.<init>(Unknown Source) ~[na:1.8.0_111]
at javax.net.DefaultServerSocketFactory.createServerSocket(Unknown Source) ~[na:1.8.0_111]
at org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory.createServerSocket(TcpNetServerConnectionFactory.java:211) ~[spring-integration-ip-5.0.3.RELEASE.jar:5.0.3.RELEASE]
at org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory.run(TcpNetServerConnectionFactory.java:106) ~[spring-integration-ip-5.0.3.RELEASE.jar:5.0.3.RELEASE]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_111]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_111]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_111]
connection exception server :::TcpConnectionServerExceptionEvent [source=Co123, port=1234, cause=java.net.BindException: Address already in use: JVM_Bind]
Co123
2018-05-17 21:01:40.851 INFO 18332 --- [pool-5-thread-1] o.s.i.ip.tcp.TcpReceivingChannelAdapter : stopped org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter#3
2018-05-17 21:01:40.851 INFO 18332 --- [pool-5-thread-1] o.s.i.endpoint.EventDrivenConsumer : Removing {transformer} as a subscriber to the 'Co123out.flow.channel#0' channel
2018-05-17 21:01:40.852 INFO 18332 --- [pool-5-thread-1] o.s.integration.channel.DirectChannel : Channel 'application.Co123out.flow.channel#0' has 0 subscriber(s).
2018-05-17 21:01:40.852 INFO 18332 --- [pool-5-thread-1] o.s.i.endpoint.EventDrivenConsumer : stopped org.springframework.integration.config.ConsumerEndpointFactoryBean#11
2018-05-17 21:01:40.852 INFO 18332 --- [pool-5-thread-1] o.s.i.endpoint.EventDrivenConsumer : Removing {jms:outbound-channel-adapter} as a subscriber to the 'Co123out.flow.channel#1' channel
2018-05-17 21:01:40.852 INFO 18332 --- [pool-5-thread-1] o.s.integration.channel.DirectChannel : Channel 'application.Co123out.flow.channel#1' has 0 subscriber(s).
2018-05-17 21:01:40.852 INFO 18332 --- [pool-5-thread-1] o.s.i.endpoint.EventDrivenConsumer : stopped org.springframework.integration.config.ConsumerEndpointFactoryBean#12
Exception in thread "pool-4-thread-1" java.lang.NullPointerException
at org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory.run(TcpNetServerConnectionFactory.java:185)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception in thread "pool-5-thread-1" java.lang.NullPointerException
at org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory.run(TcpNetServerConnectionFactory.java:185)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)`
You register an IntegrationFlow via:
this.flowContext.registration(flow).id("test.flow").register();
The same his.flowContext bean and that id for the flow can be used to destroy the flow from any other place, e.g. an event listener, when you catch the mentioned BindException:
/**
* Destroy an {#link IntegrationFlow} bean (as well as all its dependant beans)
* for provided {#code flowId} and clean up all the local cache for it.
* #param flowId the bean name to destroy from
*/
void remove(String flowId);

spring-boot-starter-quartz jdbc example

Starting with spring-boot 2.x.x they started offering spring-boot-starter-quartz which is great! Out of the box it does an in-memory store. I want to change it to be a clustered environment but I'm having issues with the configuration I think mostly because I need to put the qrtz_ tables in a different schema than my default data source. Does anyone have an example of using an alternate datasource? I'm currently attempting to set the properties field (as you can see below) but its like they are not being picked up by the configuration bean. Any help is appreciated.
Configuration
spring:
quartz:
job-store-type: jdbc
jdbc:
initialize-schema: never
properties:
scheduler:
instanceName : MyClusteredScheduler
instanceId : AUTO
threadPool:
class : org.quartz.simpl.SimpleThreadPool
threadCount : 25
threadPriority : 5
jobStore:
misfireThreshold : 60000
class : org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass : org.quartz.impl.jdbcjobstore.StdJDBCDelegate
useProperties : false
dataSource : myDS
tablePrefix : QRTZ_
isClustered : true
clusterCheckinInterval : 20000
dataSource:
myDS:
driver : com.mysql.jdbc.Driver
URL : jdbc:mysql://127.0.0.1:3306/quartz
user : removed
password : removed
maxConnections : 5
validationQuery : select 0 from dual
Output from log
2017-11-06 13:33:02.853 INFO 7082 --- [ main] org.quartz.core.QuartzScheduler : Quartz Scheduler v.2.3.0 created.
2017-11-06 13:33:02.856 INFO 7082 --- [ main] o.s.s.quartz.LocalDataSourceJobStore : Using db table-based data access locking (synchronization).
2017-11-06 13:33:02.858 INFO 7082 --- [ main] o.s.s.quartz.LocalDataSourceJobStore : JobStoreCMT initialized.
2017-11-06 13:33:02.859 INFO 7082 --- [ main] org.quartz.core.QuartzScheduler : Scheduler meta-data: Quartz Scheduler (v2.3.0) 'quartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.springframework.scheduling.quartz.LocalDataSourceJobStore' - which supports persistence. and is not clustered.
2017-11-06 13:33:02.859 INFO 7082 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler 'quartzScheduler' initialized from an externally provided properties instance.
2017-11-06 13:33:02.860 INFO 7082 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler version: 2.3.0
2017-11-06 13:33:02.860 INFO 7082 --- [ main] org.quartz.core.QuartzScheduler : JobFactory set to: org.springframework.boot.autoconfigure.quartz.AutowireCapableBeanJobFactory#21132086
2017-11-06 13:33:03.214 INFO 7082 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-11-06 13:33:03.216 INFO 7082 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2017-11-06 13:33:03.223 INFO 7082 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2017-11-06 13:33:03.227 INFO 7082 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2017-11-06 13:33:03.227 INFO 7082 --- [ main] o.s.s.quartz.SchedulerFactoryBean : Starting Quartz Scheduler now
2017-11-06 13:33:05.250 WARN 7082 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'quartzScheduler'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
2017-11-06 13:33:05.250 INFO 7082 --- [ main] o.s.s.quartz.SchedulerFactoryBean : Shutting down Quartz Scheduler
2017-11-06 13:33:05.251 INFO 7082 --- [ main] org.quartz.core.QuartzScheduler : Scheduler quartzScheduler_$_NON_CLUSTERED shutting down.
2017-11-06 13:33:05.251 INFO 7082 --- [ main] org.quartz.core.QuartzScheduler : Scheduler quartzScheduler_$_NON_CLUSTERED paused.
2017-11-06 13:33:05.251 INFO 7082 --- [ main] org.quartz.core.QuartzScheduler : Scheduler quartzScheduler_$_NON_CLUSTERED shutdown complete.
2017-11-06 13:33:05.252 INFO 7082 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-11-06 13:33:05.253 INFO 7082 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans
2017-11-06 13:33:05.254 INFO 7082 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-11-06 13:33:05.255 INFO 7082 --- [ main] com.zaxxer.hikari.HikariDataSource : testdb - Shutdown initiated...
2017-11-06 13:33:05.264 INFO 7082 --- [ main] com.zaxxer.hikari.HikariDataSource : testdb - Shutdown completed.
2017-11-06 13:33:05.265 INFO 7082 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2017-11-06 13:33:05.283 INFO 7082 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-06 13:33:05.293 ERROR 7082 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.context.ApplicationContextException: Failed to start bean 'quartzScheduler'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:186) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:52) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:358) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:159) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:884) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.M5.jar:2.0.0.M5]
at com.tci.reader.incident.parser.IncidentParserApplication.main(IncidentParserApplication.java:18) [classes/:na]
Caused by: org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected [See nested exception: java.sql.SQLException: No database selected]]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:738) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:183) ~[spring-context-5.0.0.RELEASE.jar:5.0.0.RELEASE]
... 14 common frames omitted
Caused by: org.quartz.SchedulerConfigException: Failure occured during job recovery.
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:697) ~[quartz-2.3.0.jar:na]
at org.quartz.core.QuartzScheduler.start(QuartzScheduler.java:539) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.StdScheduler.start(StdScheduler.java:142) ~[quartz-2.3.0.jar:na]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.startScheduler(SchedulerFactoryBean.java:664) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.scheduling.quartz.SchedulerFactoryBean.start(SchedulerFactoryBean.java:735) ~[spring-context-support-5.0.0.RELEASE.jar:5.0.0.RELEASE]
... 15 common frames omitted
Caused by: org.quartz.impl.jdbcjobstore.LockException: Failure obtaining db row lock: No database selected
at org.quartz.impl.jdbcjobstore.StdRowLockSemaphore.executeSQL(StdRowLockSemaphore.java:157) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.DBSemaphore.obtainLock(DBSemaphore.java:113) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3842) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverJobs(JobStoreSupport.java:839) ~[quartz-2.3.0.jar:na]
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:695) ~[quartz-2.3.0.jar:na]
... 19 common frames omitted
Caused by: java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-2.7.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-2.7.2.jar:na]
at org.quartz.impl.jdbcjobstore.StdRowLockSemaphore.executeSQL(StdRowLockSemaphore.java:96) ~[quartz-2.3.0.jar:na]
... 23 common frames omitted
You have to use the correct properties for the quartz properties.
Your properties are missing ...org.quartz...
For the none-yml notation, try this for the threadCount:
spring.quartz.properties.org.quartz.threadPool.threadCount=25
For the yml notation:
Add two layers under the 'properties', e.g.
spring:
quartz:
properties:
org:
quartz:
threadPool:
threadCount : 25
Application.yml file:
spring:
jpa:
hibernate:
ddl-auto: none
datasource:
url: jdbc:mysql://127.0.0.1:3306/Quartz
username: Your Username
password: Your Password
quartz:
scheduler:
instanceName: Scheduler
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 3
context:
key:
QuartzTopic: QuartzPorperties
jobStore:
driver: com.mysql.jdbc.Driver
class: org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
misfireThreshold: 6000
tablePrefix: QRTZ_
Next create a Configuration class which reads these properties from the yml file and then creates a Scheduler Bean:
#Configuration
public class SchedulerConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#Value("${quartz.scheduler.instanceName}")
private String instanceName;
#Value("${quartz.threadPool.class}")
private String threadClass;
#Value("${quartz.threadPool.threadCount}")
private String threadCount;
#Value("${quartz.context.key.QuartzTopic}")
private String quartzTopic;
#Value("${quartz.jobStore.class}")
private String jobStoreClass;
#Value("${quartz.jobStore.driverDelegateClass}")
private String driverDelegateClass;
#Value("${quartz.jobStore.misfireThreshold}")
private String misfireThreshold;
#Value("${quartz.jobStore.tablePrefix}")
private String tablePrefix;
#Value("${quartz.jobStore.driver}")
private String dataSourceDriver;
#Value("${spring.datasource.url}")
private String dataSourceUrl;
#Value("${spring.datasource.username}")
private String dataSourceUsername;
#Value("${spring.datasource.password}")
private String databasePassword;
#Bean({"Scheduler"})
public Scheduler getScheduler() {
Scheduler scheduler = null;
try {
StdSchedulerFactory factory = new StdSchedulerFactory();
Properties props = new Properties();
props.put("org.quartz.scheduler.instanceName", instanceName);
props.put("org.quartz.threadPool.class", threadClass);
props.put("org.quartz.threadPool.threadCount", threadCount);
props.put("org.quartz.context.key.QuartzTopic", quartzTopic);
props.put("org.quartz.jobStore.class", jobStoreClass);
props.put("org.quartz.jobStore.driverDelegateClass", driverDelegateClass);
props.put("quartz.jobStore.misfireThreshold", misfireThreshold);
props.put("org.quartz.jobStore.tablePrefix", tablePrefix);
props.put("org.quartz.jobStore.dataSource", "myDS");
props.put("org.quartz.dataSource.myDS.driver", dataSourceDriver);
props.put("org.quartz.dataSource.myDS.URL", dataSourceUrl);
props.put("org.quartz.dataSource.myDS.user", dataSourceUsername);
props.put("org.quartz.dataSource.myDS.password", databasePassword);
props.put("org.quartz.dataSource.myDS.maxConnections", "10");
factory.initialize(props);
scheduler = factory.getScheduler();
scheduler.start();
scheduler.resumeAll(); // This is to resume the entire scheduler when a new build is deployed
} catch (Exception e) {
logger.error("{} - SchedulerConfig class - getScheduler() - Error creating Scheduler instance: {}",
appName, e);
}
return scheduler;
}
}
Finally, use the Bean as below in any class you want:
#Autowired
private Scheduler scheduler;

JHipster and mongodb : Error creating bean with name 'mongobee'

I am rather new to JHipster and I followed their instructions in order to create a new app.
The app was created, imported into STS as a Maven project and I updated it.
However as soon as I try to start it via the Boot Dashboard I get this output :
2016-12-07 16:43:14.887 INFO 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : Starting MdcApp on PC981 with PID 6396 (C:\Users\lvuillaume\Desktop\mdc\target\classes started by lvuillaume in C:\Users\lvuillaume\Desktop\mdc)
2016-12-07 16:43:14.890 DEBUG 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : Running with Spring Boot v1.4.2.RELEASE, Spring v4.3.4.RELEASE
2016-12-07 16:43:14.891 INFO 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : The following profiles are active: swagger,dev
2016-12-07 16:43:14.972 DEBUG 6396 --- [kground-preinit] org.jboss.logging : Logging Provider: org.jboss.logging.Slf4jLoggerProvider found via system property
2016-12-07 16:43:18.499 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.AsyncConfiguration : Creating Async Task Executor
2016-12-07 16:43:19.041 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.MetricsConfiguration : Registering JVM gauges
2016-12-07 16:43:19.059 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.MetricsConfiguration : Initializing Metrics JMX reporting
2016-12-07 16:43:19.960 WARN 6396 --- [ restartedMain] io.undertow.websockets.jsr : UT026009: XNIO worker was not set on WebSocketDeploymentInfo, the default worker will be used
2016-12-07 16:43:19.961 WARN 6396 --- [ restartedMain] io.undertow.websockets.jsr : UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used
2016-12-07 16:43:20.436 INFO 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Web application configuration, using profiles: [swagger, dev]
2016-12-07 16:43:20.437 DEBUG 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Initializing Metrics registries
2016-12-07 16:43:20.442 DEBUG 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Registering Metrics Filter
2016-12-07 16:43:20.442 DEBUG 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Registering Metrics Servlet
2016-12-07 16:43:20.445 INFO 6396 --- [ restartedMain] c.mycompany.myapp.config.WebConfigurer : Web application fully configured
2016-12-07 16:43:20.491 INFO 6396 --- [ restartedMain] com.mycompany.myapp.MdcApp : Running with Spring profile(s) : [swagger, dev]
2016-12-07 16:43:20.579 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.CacheConfiguration : No cache
2016-12-07 16:43:24.805 DEBUG 6396 --- [ restartedMain] c.m.m.c.apidoc.SwaggerConfiguration : Starting Swagger
2016-12-07 16:43:24.816 DEBUG 6396 --- [ restartedMain] c.m.m.c.apidoc.SwaggerConfiguration : Started Swagger in 10 ms
2016-12-07 16:43:24.849 DEBUG 6396 --- [ restartedMain] c.m.myapp.config.DatabaseConfiguration : Configuring Mongobee
2016-12-07 16:43:24.854 INFO 6396 --- [ restartedMain] com.github.mongobee.Mongobee : Mongobee has started the data migration sequence..
2016-12-07 16:43:54.876 WARN 6396 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongobee' defined in class path resource [com/mycompany/myapp/config/DatabaseConfiguration.class]: Invocation of init method failed; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
2016-12-07 16:43:54.883 INFO 6396 --- [ restartedMain] c.m.myapp.config.CacheConfiguration : Closing Cache Manager
2016-12-07 16:43:54.905 ERROR 6396 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongobee' defined in class path resource [com/mycompany/myapp/config/DatabaseConfiguration.class]: Invocation of init method failed; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at com.mycompany.myapp.MdcApp.main(MdcApp.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:210)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:482)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:79)
at com.mongodb.Mongo.execute(Mongo.java:772)
at com.mongodb.Mongo$2.execute(Mongo.java:759)
at com.mongodb.DBCollection.findOne(DBCollection.java:777)
at com.mongodb.DBCollection.findOne(DBCollection.java:747)
at com.mongodb.DBCollection.findOne(DBCollection.java:694)
at com.github.mongobee.dao.ChangeEntryIndexDao.findRequiredChangeAndAuthorIndex(ChangeEntryIndexDao.java:26)
at com.github.mongobee.dao.ChangeEntryDao.ensureChangeLogCollectionIndex(ChangeEntryDao.java:75)
at com.github.mongobee.dao.ChangeEntryDao.connectMongoDb(ChangeEntryDao.java:34)
at com.github.mongobee.Mongobee.execute(Mongobee.java:135)
at com.github.mongobee.Mongobee.afterPropertiesSet(Mongobee.java:117)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
... 19 common frames omitted
I tried to create a similar project but without a Mongodb and it worked.
This error means that there was an error connecting to your database, it confirms this in your stacktrace:
Timed out after 30000 ms while waiting for a server
Please double check your database configuration in the application-dev.properties or application-dev.yml file under src/main/resources/config/.
Depending on whether you use YAML or JSON as the property definition file, double check the database configuration:
YAML:
spring:
data:
mongodb:
host: <your_host_address>
port: <your_port>
database: <database_name>
JSON:
spring.data.mongodb.host=<your_host_address>
spring.data.mongodb.port=<your_port>
spring.data.mongodb.database=<database_name>
After creating a new JHipster project with MongoDb I had the same error.
Before running mvnw (on Windows) I forgot to run the MongoDb itself.
So running mongod.exe in the new command prompt, and then running mvnw solved the issue for me.
This was able to solve my problem:
"Answered my own question...removing the #Bean definition from public
Mongobee mongobee(...) in DatabaseConfiguration.java seems to do the
trick. Haven't done any thorough testing, but the apps starts and I
can create new users."
Link: https://github.com/jhipster/generator-jhipster/issues/8665

Camel http4 download file using Basic authentication over Https

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.

Resources