Spring data repository #Autowiring is null when using #Transactional annotation on service bean - repository

I am studying spring framework and trying to use it in my project. But I have came across the following problem with spring data repository and #Transactional annotation used in my service. The problem is that there are no exceptions on the spring start up. Later on when I try to access spring data repository I get NullPointerException. Maybe you have some thoughts that could help me.
I am using spring data repository define as following:
package net.question.data.repository;
import net.question.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Then I have a service defined which contains autowired repository:
package net.question.data.service;
import net.question.data.repository.UserRepository;
import net.question.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class UserService {
#Autowired
public UserRepository userRepository;
public void doStuff(User usr) {
// login will be here
}
}
here is the test to show my problem:
package net.question.spring;
import static org.junit.Assert.assertNotNull;
import net.question.data.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/app-context.xml")
public class InjectionTestSuite {
#Autowired
UserService userService;
#Test
public void testRepositoryInjection() {
assertNotNull(userService);
assertNotNull(userService.userRepository);
}
}
The test fails on the follwowing line:
assertNotNull(userService.userRepository);
If I remove the #Transactional annotation on the service then the test passes.
here is my app-context.xml file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd ">
<jpa:repositories base-package="net.question.data.repository" />
<!-- For discovering entity services -->
<context:component-scan base-package="net.question.data.service" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="hibernate_mysql" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>
Maybe you have some ideas, how to find the error?

Related

Apache camel http4 with self signed SSL certificate

I'm really stuck configuring Apache camel https4 for self signed server certificates that does not match the hostname.
[Do. 2020 16 Juli 13:13:19] [DEBUG] org.apache.camel.processor.Pipeline () - Message exchange has failed: so breaking out of pipeline for exchange: Exchange[ID-lvm-cdbservice-01ct-1594888044674-0-15551] Exception: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
That's why I created a custom HttpClientConfigurer as stated in the apache camel http configuration. But this configurer does not seem to be used for my route?! Does anybody know why?
The configureHttpClient method is used at some point
[Do. 2020 16 Juli 10:27:25] [INFO ] com.test.SelfSignedHttpClientConfigurer () - Using SelfSignedHttpClientConfigurer...
[Do. 2020 16 Juli 10:27:25] [INFO ] com.test.SelfSignedHttpClientConfigurer () - ... HttpClient configured!
But the protocols didn't change. That's why I guess it is not used for my route.
available protocols [[TLSv1.3, TLSv1.2, TLSv1.1, TLSv1]],
currently enabled protocols [[TLSv1.3, TLSv1.2, TLSv1.1, TLSv1]],
and default protocol patterns [Patterns [includes=[.*], excludes=[SSL.*]]].
Resulting enabled protocols are [[TLSv1.3, TLSv1.2, TLSv1.1, TLSv1]].
pom.xml
<properties>
<camel.version>2.24.3</camel.version>
</properties>
<dependencies>
<!-- camel -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-http4</artifactId>
<version>${camel.version}</version>
</dependency>
</dependencies>
applicationContext.xml
<!-- Apache Camel -->
<camelContext
xmlns="http://camel.apache.org/schema/spring">
<!-- HTTP myTime -->
<route id="myTimeRoute">
<from uri="file:///tmp/test?consumer.delay=10000" />
<setHeader headerName="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<setHeader headerName="Content-Type">
<constant>application/json</constant>
</setHeader>
<to uri="https4://test.de/test?delay=60000&connectTimeout=20000&httpClientConfigurer=#selfSignedHttpClientConfigurer&sslContextParameters=#mySSLContextParameters&throwExceptionOnFailure=false" />
</route>
</camelContext>
<bean id="selfSignedHttpClientConfigurer"
class="com.test.SelfSignedHttpClientConfigurer" />
I tried it with and without # (httpClientConfigurer=#selfSignedHttpClientConfigurer and httpClientConfigurer=selfSignedHttpClientConfigurer)
SelfSignedHttpClientConfigurer.class
package com.test;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.camel.component.http4.HttpClientConfigurer;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SelfSignedHttpClientConfigurer implements HttpClientConfigurer {
/** the logger. */
private static final Logger LOG = LoggerFactory.getLogger(SelfSignedHttpClientConfigurer.class);
#Override
public void configureHttpClient(HttpClientBuilder clientBuilder) {
try {
LOG.info("Using SelfSignedHttpClientConfigurer...");
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
// Allow TLSv1.2 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2" },
null, NoopHostnameVerifier.INSTANCE);
clientBuilder.setSSLSocketFactory(sslsf);
LOG.info("... HttpClient configured!");
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
e.printStackTrace();
}
}
}
I tried with .build() and without.
I finally found a solution. All the tutorials and documentations are "deprecated", because the Apache HTTP API has changed with version 4.5. You will not get any errors in your code, but it is simply not working.
This post really helped me: https://stackoverflow.com/a/38509015
SelfSignedHttpClientConfigurer.class
package com.test;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.camel.component.http4.HttpClientConfigurer;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SelfSignedHttpClientConfigurer implements HttpClientConfigurer {
/** the logger. */
private static final Logger LOG = LoggerFactory.getLogger(SelfSignedHttpClientConfigurer.class);
#Override
public void configureHttpClient(HttpClientBuilder clientBuilder) {
try {
LOG.info("Using SelfSignedHttpClientConfigurer...");
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true).build();
clientBuilder.setSSLContext(sslContext)
.setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder
.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",
new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()));
LOG.info("... HttpClient configured!");
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
e.printStackTrace();
}
}
}
applicationContext.xml
<!-- Apache Camel -->
<camelContext
xmlns="http://camel.apache.org/schema/spring">
<!-- HTTP myTime -->
<route id="myTimeRoute">
<from uri="file:///tmp/test?consumer.delay=10000" />
<setHeader headerName="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<setHeader headerName="Content-Type">
<constant>application/json</constant>
</setHeader>
<to uri="https4://test.de/test?httpClientConfigurer=#selfSignedHttpClientConfigurer" />
</route>
</camelContext>
<bean id="selfSignedHttpClientConfigurer"
class="com.test.SelfSignedHttpClientConfigurer" />

Red5 Live Streaming using Air to IOS client

Hi i have a Red5 Application Server running and a NetConnection using Air to IOS to connect to the Red5 Application Server.
But the problem is that i get an error like:
2014-07-01 04:43:04,475 [NioProcessor-6] ERROR o.r.server.service.ServiceInvoker - Method addSomething with parameters [2, 3] not found in org.red5.server.CoreHandler#ebf5a1
I understand that the Method is not being called for some reason but can understand why, can anyone help please?
CODE
SERVERSIDE
package com;
import java.util.HashMap;
import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.Red5;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.service.*;
import static java.lang.System.*;
import java.util.Stack;
public class Application extends ApplicationAdapter{
//private static final Log log = LogFactory.getLog( Application.class );
public boolean appStart(IScope scope){
out.println("Adding: ");
return true;
}
public void appStop(){
out.println("Adding: ");
// This function fires when the app is closing
}
public double addSomething(double a, double b){
// This is a method we will call from our flash client
out.println("Adding: "+a+" + "+b);
return a+b;
}
public boolean connect(IConnection conn, IScope scope, Object[] params) {
// This is the master connection method called every time someone connects
// to the server.
out.println("Adding: ");
//ServiceUtils.invokeOnAllConnections(scope, "joinuser", null);
return true;
}
/*
* (non-Javadoc)
* #see org.red5.server.adapter.ApplicationAdapter#disconnect(org.red5.server.api.IConnection, org.red5.server.api.IScope)
* disconnect an user form the chat and notify all others users
*/
public void disconnect(IConnection conn, IScope scope) {
// Function called every time someone disconnects from the server.
//ServiceUtils.invokeOnAllConnections(scope, "removeuser",null );
super.disconnect(conn, scope);
}
}
CLIENT
------
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.Responder;
var nc:NetConnection;
var good:Boolean;
var netOut:NetStream;
var netIn:NetStream;
var cam:Camera;
var mic:Microphone;
var responder:Responder;
var r:Responder;
var vidOut:Video;
var vidIn:Video;
var outStream:String;
var inStream:String;
trace("hello");
var rtmpNow:String="rtmp://localhost/Test1";
nc=new NetConnection;
nc.client = this;
nc.connect(rtmpNow,"trik");
nc.addEventListener(NetStatusEvent.NET_STATUS,getStream);
function getStream(e:NetStatusEvent):void
{
good=e.info.code == "NetConnection.Connect.Success";
if(good)
{
trace("hello");
// Here we call functions in our Java Application
//responder=new Responder(streamNow);
r = new Responder(adder);
nc.call("addSomething",r,2,3);
//nc.call("streamer",responder,"test");
}
}
function adder (obj:Object):void{
trace("Total = ",obj.toString());
}
function streamNow(streamSelect:Object):void
{
setCam();
setMic();
setVid();
trace("We've got our object",streamSelect.toString());
switch(streamSelect.toString())
{
case "left" :
outStream="left";
inStream="right";
break;
case "right" :
outStream="right";
inStream="left";
break;
}
//Publish local video
netOut=new NetStream(nc);
netOut.attachAudio(mic);
netOut.attachCamera(cam);
vidOut.attachCamera(cam);
netOut.publish(outStream, "live");
//Play streamed video
netIn=new NetStream(nc);
vidIn.attachNetStream(netIn);
netIn.play(inStream);
}
function setCam():void
{
cam=Camera.getCamera();
cam.setMode(240,180,15);
cam.setQuality(0,85);
}
function setMic():void
{
mic=Microphone.getMicrophone();
mic.rate=11;
mic.setSilenceLevel(12,2000);
}
function setVid():void
{
vidOut=new Video(240,180);
addChild(vidOut);
vidOut.x=25;
vidOut.y=110;
vidIn=new Video(240,180);
addChild(vidIn);
vidIn.x=vidOut.x+260;
vidIn.y=110;
}
RED5 PROPERTIES FILE
--------------------
webapp.contextPath=/Test1
webapp.virtualHosts=localhost, localhost:5080
RED5 WEB XML 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:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/red5-web.properties" />
</bean>
<bean id="web.context" class="org.red5.server.Context" autowire="byType" />
<bean id="web.handler" class="com.Application" />
<bean id="web.scope" class="org.red5.server.scope.WebScope" init-method="register">
<property name="server" ref="red5.server" />
<property name="parent" ref="global.scope" />
<property name="context" ref="web.context" />
<property name="handler" ref="global.handler" />
<property name="contextPath" value="${webapp.contextPath}" />
<property name="virtualHosts" value="${webapp.virtualHosts}" />
</bean>
</beans>
RED5 WEB XML FILE
-----------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns
/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Test1</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>/Test1</param-value>
</context-param>
<listener>
<listener-class>org.red5.logging.ContextLoggingListener</listener-class>
</listener>
<filter>
<filter-name>LoggerContextFilter</filter-name>
<filter-class>org.red5.logging.LoggerContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggerContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Forbidden</web-resource-name>
<url-pattern>/streams/*</url-pattern>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
</web-app>
The issues is that the "numbers" are not coming to the server as the expected type of "double". There are several solutions to this:
Change the parameter type on your addSomething method to int.
Send your parameters from the client with a decimal point (2.0 vs 2)

Title changed to: Issues with Mule JPA module

I am trying to integrate Hibernate with Mule. Does Mule support Hibernate Transport ?
Hi #David,
I have tried to work with Mule JPA module. But I am facing Below issues. Kindly help me.
Here is my applicationContect.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
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://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- Connection Pool -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- JPA EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${jdbc.database}"/>
<property name="showSql" value="${jdbc.showSql}"/>
</bean>
</property>
</bean>
<!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<!-- Activates various annotations to be detected in bean classes for eg #Autowired-->
<context:annotation-config/>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Property Configurator -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="jdbc.properties"/>
</bean>
<context:component-scan base-package="com.test.dao"/>
<bean id="contactService" class="com.test.service.ContactServiceImpl"/>
</beans>
and this is my mflow file
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.mulesoft.org/schema/mule/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/jpa http://www.mulesoft.org/schema/mule/jpa/current/mule-jpa.xsd">
<spring:beans>
<spring:import resource="classpath:applicationContext.xml" />
</spring:beans>
<jpa:config name="Java_Persistence_API" entityManagerFactory-ref="entityManagerFactory" doc:name="Java Persistence API"/>
<flow name="jpa-exampleFlow1" doc:name="jpa-exampleFlow1">
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" doc:name="HTTP"/>
<!-- code to be written -->
<logger level="INFO" doc:name="Logger"/>
</flow>
</mule>
this is my entity class
package com.test.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.*;
import com.test.vo.Contact;
import com.test.vo.ContactVO;
#Entity
#Table(name="contact")
public class ContactEO implements Contact{
#Transient
Contact contact;
#Transient
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public ContactEO(){
contact = new ContactVO();
}
public ContactEO(Contact contact){
this.contact = contact;
}
#Column(name="FIRSTNAME")
public String getFirstName() {
return contact.getFirstName();
}
public void setFirstName(String firstName) {
contact.setFirstName(firstName);
}
#Column(name="LASTNAME")
public String getLastName() {
return contact.getLastName();
}
public void setLastName(String lastName) {
contact.setLastName(lastName);
}
#Column(name="EMAIL")
public String getEmail() {
return contact.getEmail();
}
public void setEmail(String email) {
contact.setEmail(email);
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="ID")
public long getId() {
return contact.getId();
}
public void setId(long id) {
contact.setId(id);
}
}
Getting below Exception Please let me know the solution.
Exception in thread "main"
org.mule.module.launcher.DeploymentInitException: IllegalAccessError:
tried to access method org.hibernate.engine.CascadeStyle.()V
from class org.hibernate.engine.EJB3CascadeStyle$1 at
org.mule.module.launcher.application.DefaultMuleApplication.init(DefaultMuleApplication.java:219)
at
org.mule.module.launcher.application.ApplicationWrapper.init(ApplicationWrapper.java:64)
at
org.mule.module.launcher.DefaultMuleDeployer.deploy(DefaultMuleDeployer.java:47)
at
org.mule.tooling.server.application.ApplicationDeployer.main(ApplicationDeployer.java:127)
Caused by: org.mule.api.config.ConfigurationException: Error creating
bean with name 'entityManagerFactory' defined in class path resource
[applicationContext.xml]: Invocation of init method failed; nested
exception is java.lang.IllegalAccessError: tried to access method
org.hibernate.engine.CascadeStyle.()V from class
org.hibernate.engine.EJB3CascadeStyle$1
(org.mule.api.lifecycle.InitialisationException)
(org.mule.api.config.ConfigurationException) at
org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:52)
at
org.mule.config.builders.AbstractResourceConfigurationBuilder.configure(AbstractResourceConfigurationBuilder.java:78)
at
org.mule.context.DefaultMuleContextFactory.createMuleContext(DefaultMuleContextFactory.java:84)
at
org.mule.module.launcher.application.DefaultMuleApplication.init(DefaultMuleApplication.java:207)
... 3 more Caused by: org.mule.api.config.ConfigurationException:
Error creating bean with name 'entityManagerFactory' defined in class
path resource [applicationContext.xml]: Invocation of init method
failed; nested exception is java.lang.IllegalAccessError: tried to
access method org.hibernate.engine.CascadeStyle.()V from class
org.hibernate.engine.EJB3CascadeStyle$1
(org.mule.api.lifecycle.InitialisationException) at
org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:52)
at
org.mule.config.builders.AbstractResourceConfigurationBuilder.configure(AbstractResourceConfigurationBuilder.java:78)
at
org.mule.config.builders.AutoConfigurationBuilder.autoConfigure(AutoConfigurationBuilder.java:101)
at
org.mule.config.builders.AutoConfigurationBuilder.doConfigure(AutoConfigurationBuilder.java:57)
at
org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:46)
... 6 more Caused by: org.mule.api.lifecycle.InitialisationException:
Error creating bean with name 'entityManagerFactory' defined in class
path resource [applicationContext.xml]: Invocation of init method
failed; nested exception is java.lang.IllegalAccessError: tried to
access method org.hibernate.engine.CascadeStyle.()V from class
org.hibernate.engine.EJB3CascadeStyle$1 at
org.mule.registry.AbstractRegistry.initialise(AbstractRegistry.java:117)
at
org.mule.config.spring.SpringXmlConfigurationBuilder.createSpringRegistry(SpringXmlConfigurationBuilder.java:119)
at
org.mule.config.spring.SpringXmlConfigurationBuilder.doConfigure(SpringXmlConfigurationBuilder.java:73)
at
org.mule.config.builders.AbstractConfigurationBuilder.configure(AbstractConfigurationBuilder.java:46)
... 10 more Caused by:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource [applicationContext.xml]: Invocation of init method failed;
nested exception is java.lang.IllegalAccessError: tried to access
method org.hibernate.engine.CascadeStyle.()V from class
org.hibernate.engine.EJB3CascadeStyle$1 at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:922)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at
org.mule.config.spring.SpringRegistry.doInitialise(SpringRegistry.java:89)
at
org.mule.registry.AbstractRegistry.initialise(AbstractRegistry.java:109)
... 13 more Caused by: java.lang.IllegalAccessError: tried to access
method org.hibernate.engine.CascadeStyle.()V from class
org.hibernate.engine.EJB3CascadeStyle$1 at
org.hibernate.engine.EJB3CascadeStyle$1.(EJB3CascadeStyle.java:24)
at
org.hibernate.engine.EJB3CascadeStyle.(EJB3CascadeStyle.java:19)
at
org.hibernate.ejb.event.EJB3PersistEventListener.(EJB3PersistEventListener.java:19)
at
org.hibernate.ejb.EventListenerConfigurator.(EventListenerConfigurator.java:81)
at
org.hibernate.ejb.Ejb3Configuration.(Ejb3Configuration.java:136)
at
org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:130)
at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
... 24 more
What about the JPA connector: http://www.mulesoft.org/connectors/jpa-connector ?

EJB #PersistenceContext EntityManager Throws NullPointerException

I'm having a problem with injecting EntityManager by using #PersistenceContext. I try to inject EntityManager in EJB class with #PersistenceContext and I always get NullPointerException.
Here is EJB class:
#Stateless
public class BookEJB {
public BookEJB(){
}
#PersistenceContext(unitName = "BookWebStorePU")
private EntityManager em;
public Book createBook(Book book) throws Exception {
System.out.println("EM: " + em);
em.persist(book);
return book;
}
public Book findBookByIsbn10(String isbn10){
Book book = new Book();
em.find(Book.class, isbn10);
return book;
}
//Other methods here
}
Here's Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="BookWebStorePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/BookWebStoreDB"/>
<property name="javax.persistence.jdbc.user" value="bookwebstoreadmin"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<!-- Let EclipseLink create database schemas automatically -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database"/>
</properties>
Here's my test file:
public class BookDaoTests {
private BookEJB bookDao;
private Book newBook;
#Before
public void init() {
newBook = new Book();
newBook.setName("Flying Cow");
newBook.setDescription("Super cool story about flying cow");
newBook.setAuthor("Me");
newBook.setIsbn10("0123456789");
newBook.setIllustrations(true);
newBook.setPublishYear(2013);
newBook.setNumberOfPages(1567);
newBook.setQuantity(58);
bookDao = new BookEJB();
}
#Test
public void createBook() throws Exception{
bookDao.createBook(newBook);
Assert.assertEquals("Book was created!", bookDao.findBookByIsbn10("0123456789"), newBook);
}
}
So when I run that test file I get following error:
Testcase: createBook(com.mysite.bookstore.tests.BookDaoTests): Caused an ERROR
null
java.lang.NullPointerException
at com.mysite.bookwebstore.beans.BookEJB.createBook(BookEJB.java:27)
at com.mysite.bookstore.tests.BookDaoTests.createBook(BookDaoTests.java:46)
EM: null
I use following technologies:
Glassfish 4
JavaEE 7
JSF
EclipseLink 2.1
Java DB
I hope we can find some solution for this problem. I have been tackling now 3 days of this problem and searched and tested solutions from Google and from Stackoverflow but none of the solutions helped/worked. To make sure that the EntityManager was really null, I debugged test file and saw that indeed it gives null. So how can I solve this problem?
The EntityManager instance, is injected when the EJB is deployed in the Container.
If you take a look at the lifecycle of enterprise bean, you will see clearly when dependency injection occurs.
When the Container sees the #Persistencecontext annotation it will inject a container-managed EntityManager.
The problem is that the code executed in this test is not managed by the Container, therefore, no one inject the necessary dependencies.
bookDao = new BookEJB();
When you run the test, the BookEJB class is just a simple POJO, the #Stateless and #PersistenceContext annotations are simply ignored.
You have several alternatives in order to test your EJB, take a look at this link.

arquillian-glassfish-embedded-3.1 1.0.0.CR3 configuring JDBC datasource

I was trying to use arquillian-glassfish-embedded-3.1 container to test and EJB3 application. I was trying to figure out how to set up a simple JDBC datasource that could be injected as a resource to a Stateless ejb.
Here is what I have :
#Stateless
public class HelloEJBBean implements HelloEJB {
#Resource(name="myDataSource")
private DataSource datasource;
public String sayHelloEJB(String name) {
return "Hello " + name;
}
}
also have arquillian.xml with the following content:
<?xml version="1.0"?>
<arquillian xmlns="http://jboss.com/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:glassfish="urn:arq:org.jboss.arquillian.container.glassfish.embedded_3">
<glassfish:container>
<glassfish:bindHttpPort>9090</glassfish:bindHttpPort>
<glassfish:instanceRoot>src/test/resources</glassfish:instanceRoot>
<glassfish:autoDelete>false</glassfish:autoDelete>
</glassfish:container>
</arquillian>
and a domain.xml with
<domain>
<applications />
<resources>
<jdbc-resource pool-name="ArquillianEmbeddedOraclePool" jndi-name="myDataSource"
object-type="user" enabled="true"/>
<jdbc-connection-pool name="ArquillianEmbeddedOraclePool" res-type="javax.sql.DataSource"
datasource-classname="oracle.jdbc.driver.OracleDriver">
<property name="user" value="user"/>
<property name="password" value="password"/>
<property name="serverName" value="servername"/>
<property name="DatabaseName" value="dbname"/>
<property name="url" value="jdbc:oracle:thin:#servername:1521/dbname"/>
</jdbc-connection-pool>
</resources>
</domain>
and the simple test looks like this:
#RunWith(Arquillian.class)
public class HelloEJBTest {
#Deployment
public static JavaArchive createTestArchive() {
return ShrinkWrap.create(JavaArchive.class, "helloEJB.jar")
.addClasses(HelloEJB.class, HelloEJBBean.class);
}
#EJB
private HelloEJB helloEJB;
#Test
public void testHelloEJB() {
String result = helloEJB.sayHelloEJB("Michael");
assertEquals("Hello Michael", result);
}
}
I get the following error:
... 108 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Res-Ref-Env-Property: myDataSource#javax.sql.DataSource# resolved as: jndi: myDataSource#res principal: null#mail: null
No Runtime properties
... 108 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Res-Ref-Env-Property: myDataSource#javax.sql.DataSource# resolved as: jndi: myDataSource#res principal: null#mail: null
No Runtime properties
Any help is appreciated.
Thanks