Trying to use Apache Camel with Spring - spring

I am currently learning to use Apache Camel. To serve my needs I am trying a project I downloaded from the internet but the whole thing seemed to be stuck on an error that I can't debug. It's been a week, I would appreciate if anybody could explain to me what is going wrong or give me a lead in a specific direction. Thank you all.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="file://${input.dir}?fileName=input-message.csv"/>
<log message="Before SmooksComponent ${body}"/>
<to uri="smooks://smooks-config.xml"/>
<log message="After SmooksComponent ${body}"/>
</route>
</camelContext>
</beans>
private static final String camelConfig = "META-INF/spring/camel-context.xml";
public static void main(String... args) throws Exception
{
CamelContext camelContext = configureAndStartCamel(camelConfig);
// Give Camel time to process the file.
Thread.sleep(3000);
camelContext.stop();
printEndMessage();
}
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>3.10.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://camel.apache.org/schema/spring] Offending resource: class path resource [META-INF/spring/camel-context.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:72)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:119)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:111)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:281)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1388)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1371)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:179)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:149)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:96)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:511)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:338)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:224)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:195)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:257)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:128)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:671)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at org.smooks.examples.camel.csv2xml.Main.configureAndStartCamel(Main.java:87)
at org.smooks.examples.camel.csv2xml.Main.main(Main.java:64)

For anybody who might encounter the situation kindly note the imports were incomplete.
I did not import the camel-spring of course which should be same version as camel-core.
Regards all.

Related

Is using hibernate type property names when using spring boot a good approach

In my current codebase, I have a RestController, and I am using hibernate with it. As of now, I am using the same hibernate configuration which one would usually use
<?xml version="1.0" encoding="UTF-8" ?>
<hibernate-configuration xmlns="http://www.hibernate.org/xsd/orm/cfg">
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
Also, in my pom.xml, I have added:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
But to get this working I had to add the attribute exclude like this :
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
Otherwise, it was throwing some error. Another issue I noticed was even though
hbm2ddl.auto is set to true, which would have created the tables in a simple hibernate application. But it's not happening now. It throws an error if the table is not there but seems to be working fine if it's there.
I changed the MySQL dialect in the hibernate.cfg.xml to :
org.hibernate.dialect.MySQL8Dialect
And now it's automatically creating the table. That's weird when I was using the same hibernate code without spring boot the earlier Dialect was working
This is the main code that starts the application:
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SpringServerMain {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringServerMain.class, args);
}
}

Problems using Springboot autoconfiguration to connect to SQL-Server in a FUSE EAP environment

This is likely to be a misconception on my part when it comes to working with SpringBoot on FUSE EAP environments. I've been trying to deploy a service, which I've developed following the RedHat documentation and the archetypes/examples I've found online that mix Camel and SpringBoot, but to no avail.
From what I understand, when creating a connection to a JNDI datasource, which has been configured and tested in the EAP Fuse server, I can use the application.properties, or application.yml, to have the spring application autoconfigure the connection. In my case, it's required that I use #PersistenceContext to invoke the EntityManager, since the CRUD operations that the extending JpaRepository don't really cover the needs.
As per RedHat's documentation, FUSE 7.2 has been installed in EAP 7.1 and the POM is using the org.jboss.redhat-fuse.fuse-springboot-bom version 7.2.0.fuse-720020-redhat-00001.
I've tried using spring's autoconfiguration, a manual configuration declaring a #Configuration class, a manual configuration by declaring the database connection in the camel-context.xml file, and some other minor tests.
The errors vary depending on whether I try delpying the .jar or .jar.original, generated by having the spring-boot-maven-plugin with the repackage execution goal, errors obtained up to this point are:
NullPointer because EntityManager em is null (.jar.original)
java.lang.NoClassDefFoundError: org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder (.jar.original, when there's a manual configuration of the datasource, be it in a #Configuration annotated java class, or in the camel-context.xml using Spring DSL)
java.lang.ClassNotFoundException: com.example.dao.genericDAOImpl (.jar with all dependencies packaged)
Here are snippets of my program, which include the POM, Application.java and the component which is trying to get the EntityManager, will be happy to provide more snippets if it's not enough/unclear.
POM.xml
...
<properties>
<fuse.version>7.2.0.fuse-720020-redhat-00001</fuse.version>
...
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</dependencies>
...
<build>
<defaultGoal>spring-boot:run</defaultGoal>
<plugins>
...
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.16.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
...
application.properties
spring.datasource.jndi-name=jdbc:sqlserver://ip:1433;DatabaseName=dbname
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.generate-ddl=false
Application.java
#ImportResource({"classpath:spring/camel-context.xml"})
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
camel-context.xml
<beans ...>
...
<camelContext id="identidades_financieras" xmlns="http://camel.apache.org/schema/spring">
<onException>
<exception>java.lang.Exception</exception>
<handled>
<constant>true</constant>
</handled>
<setHeader headerName="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
<setBody>
<simple>${exception.message}</simple>
</setBody>
</onException>
<restConfiguration apiContextPath="/openapi.json"
bindingMode="json" component="undertow"
contextPath="/restservice/api_v1" enableCORS="true">
<dataFormatProperty key="prettyPrint" value="true"/>
</restConfiguration>
<rest enableCORS="true" id="rest-for-openapi-document" path="/openapi">
<get id="openapi.json" produces="application/json" uri="openapi.json">
<description>Gets the OpenAPI document for this service</description>
<route id="route-for-openapi-document">
<setHeader headerName="Exchange.CONTENT_TYPE" id="setHeader-for-openapi-document">
<constant>application/vnd.oai.openapi+json</constant>
</setHeader>
<setBody id="setBody-for-openapi-document">
<constant>resource:classpath:openapi.json</constant>
</setBody>
</route>
</get>
</rest>
<rest bindingMode="auto" enableCORS="true"
id="rest-b5d099c1-1996-458b-b5db-34aadc57a548" path="/">
<get id="customPaginatexxxVO" produces="application/json" uri="/xxx">
<to uri="direct:customPaginatexxxVO"/>
</get>
...
<route id="route-28f4489d-b354-401b-b774-6425bec1c120">
<from id="from-17c4205f-8d28-4d3d-a265-cb1c38c9bc32" uri="direct:customPaginatexxxVO"/>
<log id="customPaginatexxxVO-log-1" message="headers ====> pageSize: ${header.pageSize} - pageNumber: ${header.pageNumber}"/>
<bean id="to-ee6565efaf-de46-4941-b119-be7aaa07d892"
method="paginate" ref="genericService"/>
<log id="customPaginatexxxVO-log-2" message="${body}"/>
</route>
<beans/>
genericService.java
#Service
public class genericServiceImpl implements genericService {
#Autowired
private genericDAO dao;
...
#Override
public xxxVO paginate(Map<String, Object> reqHeaders) {
... pageProps are defined using reqHeaders ...
xxxVO paginated = dao.customPagination(pageProps);
return paginated;
}
...
}
genericDAOImpl.java, which errors out when anything regarding em is invoked.
#Repository
public class genericDAOImpl implements genericDAO {
#PersistenceContext //when manually configured, I've added the (unitName="") in reference to the persistence unit, from my understanding, since only one datasource was created, this should pick up by default
private EntityManager em;
...
#Override
public xxxVO customPagination(paginateProps pageProps) {
xxxVO result = null;
try {
CriteriaBuilder paginationBuilder = em.getCriteriaBuilder();
CriteriaQuery<T> paginationQuery = paginationBuilder.createQuery(entity.class);
Root<T> entityClass = paginationQuery.from(entity.class);
paginationQuery.select(entityClass);
... some settings with pageProps ...
TypedQuery<T> query = em.createQuery(paginationQuery);
entityList = query.getResultList();
... entityList is transformed to xxxVO ...
} catch (Exception e) {
LOG.error("caught something");
e.printStackTrace();
}
return result;
}
...
As stated before, I've been getting numerous different errors depending on the options I've tried, and most of them clearly come down to misconfiguration, or not deploying correctly, I'm still somewhat inexperienced when it comes to SpringBoot and Camel, and different things I've read on the internet have created some confusion. Just to make sure, the pagination method, while very snipped out, should be working, if it had a not nulled EntityManager.
Here are a couple of the logs:
When deplying .jar (fat jar with all dependencies), which from the tests I've made, deploys correctly using java -jar, but not in the fuse eap service
09:16:01,937 WARN [org.springframework.context.support.GenericApplicationContext] (MSC service thread 1-3) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.dao.genericDAOImpl] for bean with name 'genericDAO' defined in URL [vfs:/content/identidades_financieras-1.0-SNAPSHOT.jar/BOOT-INF/classes/spring/camel-context.xml]; nested exception is java.lang.ClassNotFoundException: com.example.dao.genericDAOImpl from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
09:16:01,940 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": org.jboss.msc.service.StartException in service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": Cannot create camel context: identidades_financieras-1.0-SNAPSHOT.jar
at org.wildfly.extension.camel.service.CamelContextActivationService.start(CamelContextActivationService.java:71)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.dao.genericDAOImpl] for bean with name 'genericDAO' defined in URL [vfs:/content/identidades_financieras-1.0-SNAPSHOT.jar/BOOT-INF/classes/spring/camel-context.xml]; nested exception is java.lang.ClassNotFoundException: com.example.dao.genericDAO from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
...
When deploying .jar.original (basically, just the java) with a manually configured DataSource and EntityManagerFactory. From what I understand, the service is expecting org.springframework.boot dependencies to exist on the server. After checking the modules, there is no org.springframework.boot module in the fuse layer. Is this intended?
09:50:17,265 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": org.jboss.msc.service.StartException in service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1978)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1490)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:96)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
at org.wildfly.extension.camel.SpringCamelContextBootstrap$1.run(SpringCamelContextBootstrap.java:90)
at org.wildfly.extension.camel.proxy.ProxyUtils$1.invoke(ProxyUtils.java:51)
at com.sun.proxy.$Proxy68.run(Unknown Source)
at org.wildfly.extension.camel.proxy.ProxyUtils.invokeProxied(ProxyUtils.java:55)
at org.wildfly.extension.camel.SpringCamelContextBootstrap.createSpringCamelContexts(SpringCamelContextBootstrap.java:87)
at org.wildfly.extension.camel.service.CamelContextActivationService.start(CamelContextActivationService.java:58)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
... 3 more
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:412)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:400)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
... 27 more
Finally, when uploading the .jar.original using only the Spring autoconfigure, the EM is null, using Postman I get a status 500 and "No response available" when I consume the REST
java.lang.NullPointerException
at com.example.dao.genericDAOImpl.customPagination(GenericDAOImpl.java:252)
The line makes reference to CriteriaBuilder paginationBuilder = em.getCriteriaBuilder(), or any other place where a EM method is invoked.
Thank you for your time! Any comment is appreciated...
There is no support for Spring Boot with Fuse EAP and the Camel subsystem. Hence why you do not see any org.springframework.boot dependencies in the Fuse module layer.
If you are going to deploy Camel Spring Boot applications into EAP, it's best you either disable the Camel subsystem for your deployment or avoid installing the subsystem entirely.
This is by no means a solution to the issue I was having, I believe this to be but a temporary patch on my code since the 7.4 version of Fuse will supposedly support SpringBoot 2.1.x or something of the like, but doing the following allowed me to create the database connection and move on with my life. I will not mark this as the acceptable answer, unless I'm told that this is the only way.
In the Application.java, I straight up disabled the SpringBootServletInitializer. Full disclosure, I straight up have no idea of the impact that doing this could have in an application, but the dependency was troubling while I was trying to deploy.
#ImportResource({"classpath:spring/camel-context.xml"})
#SpringBootApplication
public class Application {//extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I created a persistence.xml file where I configured the name of persistence unit and selected the package containing the entities (or listed them, both worked).
In the camel-context.xml I declared the following before the tag
<bean class="org.apache.camel.component.jpa.JpaComponent" id="jpa">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="transactionManager" ref="jpaTxManager"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="jpaTxManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="PERSISTENCE UNIT NAME IN PERSISTENCE.XML"/>
</bean>
<bean class="org.apache.camel.spring.spi.SpringTransactionPolicy" id="requiredPolicy">
<property name="transactionManager" ref="jpaTxManager"/>
<property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/>
</bean>
I created a java class responsible for the creation of the EntityManager, it is very important that the class is #Stateless (EJB), and that the connection to the persistence unit is made static.
#Stateless
public class persistenceUnitEntityManagerImpl implements IfEntityManager{
private static EntityManager em;
static {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PERSISTENCE UNIT NAME");
em = entityManagerFactory.createEntityManager();
}
public void setEntityManager( EntityManager em ) {
persistenceUnitEntityManagerImpl.em = em;
}
public EntityManager getEntityManager() {
return persistenceUnitEntityManagerImpl.em;
}
}
In the beans where the database connection was needed, in my case, an #Component (should work just as well in a #Repository), I added the following:
private IfEntityManagerImpl IfEntityManager;
#PostConstruct
public void init() {
this.persistenceUnitEntityManagerImpl = new persistenceUnitEntityManagerImpl();
}
And whenever the EntityManager needs to be called, I can use persistenceUnitEntityManagerImpl.getEntityManager()
Just to make sure that the component isn't creating a new connection/entity manager/whatever, you can add a LOG to the #PostConstruct init, if your bean is a singleton (should be by default, I believe) you will never get that LOG or printline.

Why spring aop can't find referenced pointcut

I configure the required but why error ocured. I checked few docs but no proper solution. I am using annotation based aop with autoproxy. Some code snippet is there below.
business class
package com.jlc.spring;
public class Business1 {
public void myBusiness() {
System.out.println("Business1-myBusiness");
}
public void doMyBusiness() {
System.out.println("Business1-doMyBusiness");
}
}
aop class
package com.jlc.spring.service;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class LogService {
/*
#Pointcut("execution(* com.jlc.spring.Business1.*Business(..))")
public void m1(){}
#Pointcut("execution(* com.jlc.spring.Business1.my*(..))")
public void m2(){}
#Pointcut("execution(* com.jlc.spring.Business1.do*(..))")
public void m3(){}
*/
#Pointcut("execution(* *.*Business1.my.(..))")
private void m2(){}
/*
#Before("m1()")
public void log1(){
System.out.println("LogService-log1");
}
#Before("m2()")
public void log2(){
System.out.println("LogService-log2");
}
#Before("m3()")
public void log3(){
System.out.println("LogService-log3");
}
*/
#Before("m2()")
public void log2(){
System.out.println("LogService-log2");
}
}
config file
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tool="http://www.springframework.org/schema/tool"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tx/spring-tool-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:annotation-config/>
<aop:aspectj-autoproxy/>
<bean id="ls" class="com.jlc.spring.service.LogService"/>
<bean id="b1" class="com.jlc.spring.Business1"/>
</beans>
and the error:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'b1' defined in class path resource [jlcindia.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut m2
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.jlc.spring.Main.main(Main.java:8)
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut m2
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:316)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:195)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:181)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:162)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:200)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:254)
at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:286)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:117)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:87)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 11 more
Try to fix your xml config file that way:
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config/>
<aop:aspectj-autoproxy/>
<bean id="ls" class="com.jlc.spring.service.LogService"/>
<bean id="b1" class="com.jlc.spring.Business1"/>
</beans>
Also you have error in pointcut syntax, try this:
#Pointcut("execution(* *.*Business1.my*(..))")
private void m2(){}
See examples of pointcut syntax here.
Make sure that you have these dependencies in your pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
My Spring version is 4.2.4.RELEASE

Moving Camel Spring XML to Spring Boot

I would like to move several of our camel application to Spring Boot. Most of the examples I find are using the java dsl. The application we currently support are all based on Spring XML.
What steps should I take to migrate these application to Spring Boot. If I use FatJarRouter it is my understanding that a camel context is auto-cofigured already, so it seems to me I should be able to just define routes in spring xml.
#SpringBootApplication
#ImportResource("classpath:camel-context.xml")
public class CamelApplication extends FatJarRouter {
public static void main(String[] args) {
SpringApplication.run(CamelApplication.class, args);
}
#Bean
String myBean() {
return "I'm Spring bean!";
}
}
camel-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<routes xmlns="http://camel.apache.org/schema/spring">
<route id="test">
<from uri="timer://trigger"/>
<transform>
<simple>ref:myBean</simple>
</transform>
<to uri="log:out"/>
</route>
</routes>
</beans>
Exception
2015-11-13 15:59:13.734 WARN 2156 --- [on(5)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Cannot locate BeanDefinitionParser for element [routes]
Offending resource: class path resource [camel-context.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.fatal(FailFastProblemReporter.java:60) ~[spring-beans-4.2.2.RELEASE.jar:na]
at org.springframework.beans.factory.parsing.ReaderContext.fatal(ReaderContext.java:68) ~[spring-beans-4.2.2.RELEASE.jar:na]
See the bottom of this page how to include XML routes:
https://cwiki.apache.org/confluence/display/CAMEL/Spring+Boot

ActiveMQ JMS Broker and Spring configuration

I'm pretty new to using Camel and ActiveMQ. I'm trying to run a simple code from Eclipse, without using Maven. But, it fails during Bean initialization. From the error, it seems its due to the JAR version differences, but i m failing to locate it. Kindly help me resolve this .
import org.apache.camel.CamelContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestingBroker {
private TestingBroker() {
// Helper class
}
public static void main(final String[] args) throws Exception {
AbstractApplicationContext aContext = new ClassPathXmlApplicationContext(
"classpath:META-INF/spring/camel-config-client.xml");
CamelContext ctx = (CamelContext) aContext.getBean("mycamelTemplate", CamelContext.class);
ctx.addRoutes(new BuildTwitterComponent());
ctx.start();
}
}
Here's the camel-config-client.xml file contents-
<?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:camel="http://camel.apache.org/schema/spring"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring-2.11.1.xsd">
<camel:camelContext id="my-camel-client">
<camel:template id="mycamelTemplate"/>
</camel:camelContext>
<bean id="jms" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="brokerURL" value="tcp://135.207.178.237:61616" />
</bean>
</beans>
------------------------------
I have spring.jar.2.5.6 and camel-spring-2.11.1 JAR in the classpath. Pls suggest what am i missing here.
Thanks!
GR
Camel 2.11.1 uses Spring 3.2.3.RELEASE
Also, you'll need to have ActiveMQ 5.8.0 jars (activemq-camel, etc) in your path as well to find the org.apache.activemq.camel.component.ActiveMQComponent class

Resources