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

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

Related

Creating a Junit test that tests conection to SQL Server

I am having a great deal of difficulty in either understanding what I am doing wrong or missing something fundamental. I have searched for my problem for a day or so and not understanding what I am missing.
So what I am trying to do is Create a JUnit test that connects to my SQL server and does a query to get the current time. My connection to the server works and I have tested my SQL code in the Query on the server and works perfectly. For some reason the test isn't sending my code and getting anything returned.. Not sure what Ive done wrong an if this is too extensive for this form(little new to this)
#Override
public Timestamp PCNow() throws PCSQLException {
//SQL Server uses GETDATAE
String strSQL = "SELECT GETDATE()";;
try {
//Get a result set with the timestamp field
Timestamp datTs = (Timestamp)jdbcTemplate.queryForObject( strSQL, Timestamp.class );
//Make sure there is a result
if ( datTs == null )
//Throw an exception indicating the server could not give a time
throw new PCSQLException( "UNABLE_SERVER_TIME" );
return datTs;
}
catch (Exception e) {
throw new PCSQLException( "This didn't work PCNow", e );
}
}
This is my Test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:applicationContext-sql.xml"} )
//instantiate TestExecutionListener class
#TestExecutionListeners
public class ConnectionAdapterSQLTest {
#Autowired
ConnectionAdapterImpl connectionAdapterPC;
private final Log log = LogFactory.getLog( getClass() );
#Before
public void setUp() throws Exception {
}
/**
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
}
#Test
public final void testPCNow() {
log.info("testPCNow()");
//fail("Not yet implemented");
}
applicationContext-sql.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- connection to Sql Server using JDBC sqljdbc4.2 -->
<bean id="dataSourcePC" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://******;databaseName=******" />
<property name="username" value="******" />
<property name="password" value="******" />
</bean>
<bean id="connectionAdapterPC"
class="com.*******.*******.connections.ConnectionAdapterSQL">
<property name="dataSource" ref="dataSourcePC" />
<property name="useConnectionPool" value="false" />
</bean>
<bean id="dxDateTimeFormatter" class="com.*******.*******.data.format.DateTimeFormatter">
<property name="dateFormat" value="dd-MMM-yyyy" />
</bean>
</beans>
Matt, you are logging the String "testPCNow()" not invoking the method PCNow().
So replace the test method:
#Test
public void testPCNow() {
log.info(new TheClassThatContainsTestPCNowMethod().PCNow());
}
Remember replacing TheClassThatContainsTestPCNowMethod with a valid constructor of the class that contains the method PCNow().

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 ?

Kundera No Entity metadata found for the class

I get an error "No Entity metadata found for the class" using Kundera a similiar
question is here,
No Entity metadata found for the class
but didn't find an answer (answer put META-INF into classes dir, didn't help me.
This is the error I get
3168 [main] WARN com.impetus.kundera.metadata.KunderaMetadataManager - No Entity metadata found for the class class kundega.rules.Rule. Any CRUD operation on this entity will fail.If your entity is for RDBMS, make sure you put fully qualified entity class name under <class></class> tag in persistence.xml for RDBMS persistence unit. Returning null value.
Exception in thread "main" com.impetus.kundera.KunderaException: java.lang.IllegalArgumentException: Entity object is invalid, operation failed. Please check previous log message for details
at com.impetus.kundera.persistence.EntityManagerImpl.persist(EntityManagerImpl.java:174)
at kundega.rules.AppMain.main(AppMain.java:27)
Caused by: java.lang.IllegalArgumentException: Entity object is invalid, operation failed. Please check previous log message for details
at com.impetus.kundera.graph.ObjectGraphBuilder.getNode(ObjectGraphBuilder.java:101)
at com.impetus.kundera.graph.ObjectGraphBuilder.getObjectGraph(ObjectGraphBuilder.java:75)
at com.impetus.kundera.persistence.PersistenceDelegator.persist(PersistenceDelegator.java:135)
at com.impetus.kundera.persistence.EntityManagerImpl.persist(EntityManagerImpl.java:168)
So here is my files.
Persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="UNIT">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<class>kundega.rules.Rule</class>
<properties>
<property name="kundera.client.lookup.class" value="com.impetus.client.rdbms.RDBMSClientFactory" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://130.230.141.228:3306/fastory" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="mysql" />
</properties>
</persistence-unit>
</persistence>
Start of Entity class
#Entity
#Table(name="eplrules", schema="fastory")
public class Rule {
#Id
//#GeneratedValue (strategy=GenerationType.AUTO)
#Column (name ="rule_id")
private long ruleId;
#Column (name ="rule")
private String rule;
Main class
public static void main(String[] args) {
System.out.println("start");
BasicConfigurator.configure();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("UNIT");
Rule r = new Rule();
r.setRuleId(103);
r.setRuleName("SomeRuleName");
r.setRule("SomeRule");
EntityManager em = emf.createEntityManager();
em.persist(r);
Query q = em.createQuery("select p from Rule p");
List<Rule> rules = q.getResultList();
em.close();
System.out.println(rules);
System.out.println("stop");
em.close();
emf.close();
}
When I got this I checked:
<class>package.name.DaoClass</class>
was defined in persistence.xml, this resolved the error. Also check
<property name="kundera.annotations.scan.package" value="package.name"/>
matches correctly to your package name.
"kundega.rules.Rule" package name is correct? Or is it "kundera.rules.Rule" ?

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.

How to Define Prototype Interceptors with DefaultAdvisorAutoProxyCreator in Spring.NET

I am new to Spring.NET and am just playing around trying different things out. As part of my testing, I created a simple object:
public interface ICommand {
void Execute(object context);
}
with one implementation:
public class ServiceCommand : ICommand {
public ServiceCommand() {
Console.WriteLine("########## {0} ##########", GetType().Name);
}
public void Execute(object context) {
Console.WriteLine("Service implementation: {0}.{1}", GetType().Name, MethodBase.GetCurrentMethod().Name);
}
}
Finally, I've a simple before advice as follows:
public class ConsoleLoggingBeforeAdvice : IMethodBeforeAdvice {
public ConsoleLoggingBeforeAdvice() {
Console.WriteLine("########## {0} ##########", GetType().Name);
}
public void Before(MethodInfo method, object[] args, object target) {
Console.WriteLine("Intercepted call to this method: {0}", method.Name);
Console.WriteLine(" The target is : {0}", target);
Console.WriteLine(" The arguments are : ");
if (args != null) {
foreach (object arg in args) {
Console.WriteLine("\t: {0}", arg);
}
}
}
}
As you can see, much of this stuff is from the Spring.NET quick start samples.
So, I configured the ServiceCommand to be wrapped in a ConsoleLoggingBeforeAdvice via ProxyFactoryObject and marked both the objects as prototype (see config below). This works as expected: each time we request a ServiceCommand, a new instance of both the object and associated interceptor is created:
<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net">
<object id="ConsoleLoggingBeforeAdvice" type="Spring.Aop.Support.DefaultPointcutAdvisor" singleton="false">
<property name="Advice">
<object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice"/>
</property>
</object>
<object id="ServiceCommandTarget" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>
<object id="ServiceCommand" type ="Spring.Aop.Framework.ProxyFactoryObject">
<property name="IsSingleton" value="false"/>
<property name="TargetName" value="ServiceCommandTarget"/>
<property name="InterceptorNames">
<list>
<value>ConsoleLoggingBeforeAdvice</value>
</list>
</property>
</object>
</objects>
However, when I try to achieve the same results via DefaultAdvisorAutoProxyCreator, everything works except that the interceptor is always created as Singleton (even though it's configured as singleton="false"). The config is as follows:
<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net">
<object id="ConsoleLoggingBeforeAdvice" type="Spring.Aop.Support.DefaultPointcutAdvisor" singleton="false">
<property name="Advice">
<object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice"/>
</property>
</object>
<object id="ServiceCommand" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>
<object type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator"/>
</objects>
Now, how can I ensure that both the object and associated interceptor are treated as prototypes by DefaultAdvisorAutoProxyCreator?
OK, I've figured out that setting InterceptorNames on DefaultAdvisorAutoProxyCreator will correctly instantiate interceptors as prototypes (if they're configured so). But this somehow feels incorrect as the DefaultAdvisorAutoProxyCreator should be able to pick interceptors from advisors and honor their configuration settings.
I am still not 100% clear on how to create prototype interceptors under different scenrarios. For example, all my attempts to create thread-scoped interceptors while using DefaultAdvisorAutoProxyCreator have failed.
Anyways, here's the xml config that works for me:
<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net" default-autowire="constructor">
<object id="ConsoleLoggingBeforeAdvice" type="Spring.Aop.Support.DefaultPointcutAdvisor" singleton="false">
<property name="Advice">
<object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice"/>
</property>
</object>
<object id="ServiceCommand" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>
<object type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator">
<property name="InterceptorNames" value="ConsoleLoggingBeforeAdvice"/>
</object>
</objects>
I am totally confused with the idea of creating prototype interceptors. Are interceptors supposed to be or recommended to be prototypes at all or should they always be singletons?