0

I try to implement a simple example with camel, where I define routes to interact with a database using jdbc and sql. First, I write log4j.properties for the log:

log4j.rootLogger=INFO, out

log4j.appender.out=org.apache.log4j.ConsoleAppender
log4j.appender.out.layout=org.apache.log4j.PatternLayout
log4j.appender.out.layout.ConversionPattern=[%30.30t] %-30.30c{1} %-5p %m%n
#log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n

After I write in a file called sql.properties the queries:

sql.insertNewTopic=INSERT INTO newtopic(TopicId, TopicName, url, ModuleId, CreateDate) VALUES
(:#TopicId, :#TopicName, :#url, :#ModuleId, :#CreateDate)

## sql that select all unprocessed NewTopics
sql.selectNewTopic=select * from newtopic

## sql that update the NewTopic as being processed
sql.markNewTopic=update newtopic set TopicName = 'Apache Camel' where TopicId = :#TopicId

And a file called applicationContext.xml where i define bean to set database and route to interact with it:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:camel="http://camel.apache.org/schema/spring"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans.xsd          
    http://camel.apache.org/schema/spring 
    http://camel.apache.org/schema/spring/camel-spring.xsd">


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/javavill_forum" /> <!-- djdbc:mysql://localhost:3306/dbname -->
        <property name="username" value="" />
        <property name="password" value="" />
    </bean>

    <!-- configure the Camel SQL component to use the JDBC data source -->
    <bean id="sqlComponent" class="org.apache.camel.component.sql.SqlComponent">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="topicBean" class="com.mycompany.camelwithquartz.NewTopicBean" />

    <!-- here is Camel configured with a number of routes -->
    <camelContext xmlns="http://camel.apache.org/schema/spring">

        <!-- use Camel property placeholder loaded from the given file -->
        <propertyPlaceholder id="placeholder" location="classpath:data/sql.properties" />

        <!-- route that generate new orders and insert them in the database -->
        <route id="generateOrder-route">
            <from uri="timer:foo?period=5s" />
            <transform>
                <method ref="topicBean" method="generateNewTopic" />
            </transform>
            <to uri="sqlComponent:{{sql.insertNewTopic}}" />
            <log message="Inserted new NewTopic ${body[TopicId]}" />
        </route>

        <!--
            route that process the NewTopics by picking up new rows from the
            database and when done processing then update the row to mark it as
            processed
        -->
        <route id="processNewTopic-route">
            <from uri="sqlComponent:{{sql.selectNewTopic}}?
                consumer.onConsume={{sql.markNewTopic}}" />
                <to uri="bean:topicBean?method=processNewTopic" />
                <log message="${body}" />
                <log message="Updated new NewTopic "/>
            </route>

        </camelContext>
    </beans>

The class NewTopicBean.java deines method called in the applicationContext.xml above. The NewTopicBean.java is shown below:

package com.mycompany.camelwithquartz;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


public class NewTopicBean {

    private Random ran = new Random();


    public Map<String, Object> generateNewTopic() {
        Map<String, Object> answer = new HashMap<String, Object>();
        answer.put("TopicId", ran.nextInt());
        answer.put("TopicName", "Camel in Action");
        answer.put("url", "Camel in Action");
        answer.put("ModuleId", ran.nextInt());
        answer.put("CreateDate", new Date());
        return answer;
    }

    /**
     * Processes the NewTopic
     *
     * @param data the NewTopic as a {@link Map}
     * @return the transformed NewTopic
     */
    public String processNewTopic(Map<String, Object> data) {
        return "Processed NewTopic id " + data.get("TopicId") + " TopicName "
                + data.get("TopicName")
                + " of " + data.get("ModuleId") + " copies of " + data.get("url");
    }
}

Finally I write a class to test it called TestQuartz;

public class TestQuartz {

    static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(TestQuartz.class);
    static final String pathLogger = "C:\\Users\\milioli\\Documents\\NetBeansProjects\\CamelWithQuartz\\src\\main\\resources\\data\\log4j.properties";

    public static void main(String args[]) throws Exception {
     PropertyConfigurator.configure(pathLogger);
     logger.info("before to create app context with applicationContext.xml");
        //AbstractApplicationContext context = new ClassPathXmlApplicationContext("C:\\Users\\milioli\\Documents\\NetBeansProjects\\CamelWithQuartz\\data\\applicationContext.xml");
        AbstractApplicationContext context = new FileSystemXmlApplicationContext("src/main/resources/data/applicationContext.xml");
        logger.info("after to creat app context with applicationContext.xml");
        context.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Entered>>>>>");
        context.stop();
    }
}

The pom.xml file is correct, the project builds, but when I try to run it, I obtain this exception:

org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

The routes are read, but I can't to get a connection. In the applicationContext.xml I set //localhost:3306 that is the default port, but It seems don't work.

Can someone help me?

Milioli Luca
  • 309
  • 1
  • 8
  • 20

1 Answers1

1

This could be an issue with the Commons DBCP configuration. Try modifying the bean definition to the following:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
    <property name="url" value="jdbc:mysql://localhost:3306/mydb?autoReconnect=true" /> 
    <property name="username" value="username" /> 
    <property name="password" value="mypassword" /> 
    <property name="initialSize" value="5"/> 
    <property name="validationQuery" value="select 1" /> 
      <property name="defaultAutoCommit" value="false" /> 
      <property name="maxActive" value="10" /> 
      <property name="maxIdle" value="10" /> 
      <property name="maxWait" value="15000" /> 
      <property name="removeAbandoned" value="true" /> 
      <property name="removeAbandonedTimeout" value="300" /> 
      <property name="testOnBorrow" value="true" /> 
</bean> 
Richard Neish
  • 8,414
  • 4
  • 39
  • 69
Ashoka
  • 935
  • 7
  • 20