Kundera No Entity metadata found for the class - persistence.xml

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" ?

Related

error in creating EntityManager object

I am trying to create a EntityManager object for persistence and I am unable to create EntityManager object. Please find the sample code below:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Draco-PU");
EntityManager em = emf.createEntityManager();
I have defined the persistence unit name in persistence.xml file too.
<persistence-unit name="Draco-PU" >
The persistence xml is as defined below:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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_1_0.xsd">
<persistence-unit name="Draco-PU" >
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>DracoDataSource</jta-data-source>
<non-jta-data-source>DracoUnmanagedDataSource</non-jta-data-source>
<class>dk.tdc.soa.smo.draco.db.model.DslServiceEntity</class>
<class>dk.tdc.soa.smo.draco.db.model.DslServiceCatalogEntity</class>
<class>dk.tdc.soa.smo.draco.db.model.History</class>
<class>dk.tdc.soa.smo.draco.db.model.ConfigEntity</class>
<properties>
<property name="openjpa.Log" value="DefaultLevel=WARNING, Runtime=WARNING, Tool=WARNING, SQL=WARNING" />
<!-- <property name="openjpa.jdbc.DBDictionary" value="org.apache.openjpa.jdbc.sql.OracleDictionary" /> -->
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
</properties>
</persistence-unit>
</persistence>
The error faced is :
javax.persistence.PersistenceException: No Persistence provider for EntityManager
named Draco-PU: Provider named kodo.persistence.PersistenceProviderImpl threw
expected exception at create EntityManagerFactory:
org.apache.openjpa.persistence.PersistenceException<openjpa-1.1.1-SNAPSHOT-
r422266:891341 fatal general error>
org.apache.openjpa.persistence.PersistenceException: There was an error when invoking
the static newInstance method on the named factory class
"kodo.jdbc.kernel.KodoJDBCBrokerFactory".
Please help!
Did you declare a "provider" element within your "persistence-unit" element in persistence.xml? It should look something like this:
<persistence-unit name="Draco-PU">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
</persistence-unit>
Create the next structure inside your WEB-INF folder: classes/META-INF, put your persistence.xml file in and restart the server.
Weblogic looks for the file in the build directory.

Eclipselink & Spring Data

I am trying to implement a solution using a combination of eclipselink (2.4.0) and spring-data-jpa (1.1.0.RELEASE). However, every time I deploy the solution (Tomcat 7), I get the following exception:
Caused by: java.lang.IllegalArgumentException: No [ManagedType] was found for
the key class [com.acme.domain.entities.User] in the Metamodel - please
verify that the [Managed] class was referenced in persistence.xml using a
specific <class>com.acme.domain.entities.User</class> property or a global
<exclude-unlisted-classes>false</exclude-unlisted-classes> element.
It appears to occur when the repository autowiring takes place (code examples below):
Service class
#Component
public class UserDataService {
#Autowired
private UserRepository userRepository;
...
}
Entity class
package com.acme.domain.entities;
...
#Entity
#Table(name = "users")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private Integer id;
...
}
persistence.xml
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.acme.domain.entities.User</class>
...
</persistence-unit>
Can this be due to some conflict between spring and eclipselink?
UPDATE:
Stacktrace...
[#|2012-07-31 16:25:02,317|ERROR|pool-2-thread-40|org.springframework.web.context.ContextLoader|Context initialization failed|#]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDataService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.acme.data.repositories.UserRepository com.acme.data.services.UserDataService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:897)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:873)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:958)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1599)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.acme.data.repositories.UserRepository com.acme.data.services.UserDataService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:512)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 27 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1442)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:876)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:484)
... 29 more
Caused by: java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entityEmbeddableManagedTypeNotFound(MetamodelImpl.java:174)
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:489)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:58)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:149)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:87)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:70)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:137)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:125)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:41)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
... 37 more
I was able to solve my issue but it was another setup as the one above, i just add a few things i stumbled across until i was able to solve it in my SE-Environment:
Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=338837 affects EclipseLink Version 2.2.0 and below versions. Mostly happening in Local-Environment (RESOURCE_LOCAL). A EclipseLink version-Upgrade or the following workaround may help:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
Having multiple persistence.xml files in classpath (e.g. especially in 3th party JARs) that all define the same persistence-unit-name (above "default" may be very common). Try renaming your persistence-unit-name in this case as a first step
In case of renaming the persistence-unit-name worked but changing it back to the old value reproduces the problem there is either above mentioned 3th party JAR or old JARs of your own project beeing included to your build (e.g. refactoring/ renaming on project level or similar changed the structure so for example a maven build could still take old build artifacts from the repository)
Finaly when it comes to my setup (Spring-Standalone Application, no persistence.xml but tons of Spring-configurations because a custom company Framework is used) it showed that i just forgot to add the the entity-package of the custom framework-core when i wanted to run one of their service-implementations (Spring-Bean implementation) in my local project rather than having their service-implementation from a JAR-dependency. So make sure that you have all of the required entity packages listed for your EntityManagerFactory:
<bean id="customEntityManagerFactory" parent="abstractEntityManagerFactory">
<property name="dataSource" ref="dataSource"/>
<!-- Packages of EntityClasses -->
<property name="packagesToScan">
<list merge="true">
<value>ch.company.div1.foo.bar.model</value>
<value>ch.company.div1.foo.barnicle.model</value>
<value>ch.company.div2.we.help.model</value>
</list>
</property>
<property name="jpaProperties">
<props merge="true">
<prop key="eclipselink.target-database">org.eclipse.persistence.platform.database.SQLServerPlatform
</prop>
<prop key="javax.persistence.transactionType">RESOURCE_LOCAL</prop>
</props>
</property>
</bean>
In my case i forgot to add the model packagege with the used entitys of another division (that writes the custom framework core) of our company.
Good luck, that error's a beast :/
Not sure if you are having the same problem I had: trying to create 2 different entity factories... The exception is the same, so maybe this will help. Essentially this exception was happening when it was instantiating an Entity on the wrong EntityManagerFactory.
My project was running fine with a single database connection but when I added a second one EclipseLink was confused on where to instantiate my entities. After a few debug my conclusion was to remove the property "packagesToScan" from my root-context.xml and replace it with a "persistenceXmlLocation". In that XML, I listed every class I needed to be scanned and excluded everything else with "<exclude-unlisted-classes>"
Here is my full XML configuration that is currently working:
root-context.xml
<bean id="dataSource1" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://server1.example.com:5432/db1" />
<property name="username" value="username" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="validationQuery" value="SELECT 1" />
<property name="timeBetweenEvictionRunsMillis" value="600000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="10" />
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://server2.example.com:5432/db2" />
<property name="username" value="user" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="validationQuery" value="SELECT 1" />
<property name="timeBetweenEvictionRunsMillis" value="600000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="10" />
</bean>
<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence1.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
<entry key="eclipselink.logging.level" value="WARNING" />
<entry key="eclipselink.logging.timestamp" value="false" />
<entry key="eclipselink.logging.session" value="false" />
<entry key="eclipselink.logging.thread" value="false" />
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource2" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence2.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
<entry key="eclipselink.logging.level" value="WARNING" />
<entry key="eclipselink.logging.timestamp" value="false" />
<entry key="eclipselink.logging.session" value="false" />
<entry key="eclipselink.logging.thread" value="false" />
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean name="transaction1" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="emf1" />
<bean name="transaction2" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="emf2" />
<jpa:repositories base-package="org.myproject.repository1" transaction-manager-ref="transaction1" entity-manager-factory-ref="emf1" />
<jpa:repositories base-package="org.myproject.repository2" transaction-manager-ref="transaction2" entity-manager-factory-ref="emf2" />
<tx:annotation-driven />
persistence1.xml
<persistence-unit name="persistence1" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.myproject.repository1.Repo1</class>
<class>org.myproject.repository1.Repo2</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
persistence2.xml
<persistence-unit name="persistence2" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.myproject.repository2.Repo1</class>
<class>org.myproject.repository2.Repo2</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
So, this works for me...
Apparently specifying each "persistence.xml" location prevents classes that are meant for another EntityManagerFactory to be instantiated on the first "emf". In fact, this looks like a bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=338837. All I could figure out from my debugging is that without the "persistenceXmlLocation" ALL classes that are found with "packageScan" were instantiated on the first created "emf", the second "emf" was completely ignored.
Hope this helps. Good luck!
Add the package (com.acme.domain.entities) with entities to packagesToScan.
Set the PersistenceUnitName, instead of the persistenceXmlLocation
No persistence.xml needed.
factory.setPersistenceUnitName("dummy1");
factory.setPersistenceUnitName("dummy2");

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

Alfresco set permissions for node in bootstrap

I have a problem with setting permission for existing node("Sites" folder). I have a group and I need to give her full control permission for "Sites" folder. I'm used the next xml for this
<cm:folder view:childName="cm:Sites">
<view:acl>
<view:ace view:access="ALLOWED">
<view:authority>GROUP_NOTEBOOK_PROJECT_CREATOR_GROUP</view:authority>
<view:permission>FullControl</view:permission>
</view:ace>
</view:acl>
<view:properties>
<cm:name>Sites</cm:name>
<sys:node-uuid>1e6f0610-a018-4966-ab37-c71e809dc6ed</sys:node-uuid>
</view:properties>
</cm:folder>
and next config context
<bean id="com.agilent.datastore.notebook.server.systemBootstrap" class="org.alfresco.repo.module.ImporterModuleComponent"
parent="module.baseComponent">
<property name="moduleId" value="${artifactId}" />
<property name="name" value="${name}" />
<property name="description" value="${description}" />
<property name="sinceVersion" value="${noSnapshotVersion}.${buildNumber}" />
<property name="appliesFromVersion" value="${noSnapshotVersion}.${buildNumber}" />
<!-- Uncomment next line if you want to execute bootstrap again -->
<!-- property name="executeOnceOnly" value="false" / -->
<property name="importer" ref="spacesBootstrap" />
<property name="bootstrapViews">
<list>
<props>
<prop key="uuidBinding">UPDATE_EXISTING</prop>
<prop key="path">/${spaces.company_home.childname}</prop>
<prop key="location">alfresco/extension/agilent/sites.acp</prop>
But when I'm bootstrap this folder I got exception Cannot insert duplicate key row in object 'dbo.alf_child_assoc' with unique index 'parent_node_id'.; nested exception is java.sql.SQLException: Cannot insert duplicate key row in object 'dbo.alf_child_assoc' with unique index 'parent_node_id'.
The best way to achieve what you want is to write a patch, that is a java class that extends the alfresco AbstractPatch.java class.
In the applyInternal method you first get hold of the sites-folder preferable with an xpath-search since this uses the nodeService in the background. Solr won't be available during the execution of this code since the patch is ran during bootstrap.
Declare you patch in a spring context file like this:
<bean id="patch.setPermissionsOnSitesFolderPatch" class="org.yourdomain.alfresco.patch.SetPermissionOnSitesFolderPatch" parent="basePatch">
<property name="id">
<value>patch.patch.setPermissionsOnSitesFolderPatch</value>
</property>
<property name="description">
<value>patch.setPermissionsOnSitesFolderPatch.description</value>
</property>
<property name="fixesFromSchema">
<value>0</value>
</property>
<property name="fixesToSchema">
<value>${version.schema}</value>
</property>
<property name="targetSchema">
<value>10000</value>
</property>
<property name="force" value="true" />
<property name="repository" ref="repositoryHelper"/>
</bean>
To complete the answer by #billerby you will also need a Java class to go along with that snippet. The Alfresco docs contain a good example. Using that this is what I came up with for my use-case:
Note I'm using Lombok, but that's just for convenience
public class UpdatePermissionsPatch extends AbstractPatch {
/**
* The Alfresco Service Registry that gives access to all public content services in Alfresco.
*/
#Setter private ServiceRegistry serviceRegistry;
/* Properties */
#Setter private String path;
#Setter private String authority;
#Setter private String permission;
#Setter private boolean allowed;
/** This will clear permissions for the specified authority if set to true */
#Setter private boolean clearPermissions;
private String getSuccessId() {
return getId() + ".result";
}
private String getErrorId() {
return getId() + ".error";
}
#Override
protected String applyInternal() throws Exception {
log.info("Starting execution of patch: {}", I18NUtil.getMessage(getId()));
// Get the store reference for the Repository store that contains live content
StoreRef store = StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
// Get root node for store
NodeRef rootRef = serviceRegistry.getNodeService().getRootNode(store);
// Do the patch work
setPermissions(getWipNodeRef(rootRef));
log.info("Finished execution of patch: {}", I18NUtil.getMessage(getId()));
return I18NUtil.getMessage(getSuccessId());
}
private void setPermissions(NodeRef nodeRef) {
PermissionService permsService = serviceRegistry.getPermissionService();
if (clearPermissions) {
permsService.clearPermission(nodeRef, authority);
}
permsService.setPermission(nodeRef, authority, permission, allowed);
}
private NodeRef getWipNodeRef(NodeRef rootNodeRef) {
NamespaceService nsService = serviceRegistry.getNamespaceService();
List<NodeRef> refs = searchService.selectNodes(rootNodeRef, path, null, nsService, false);
if (refs.size() != 1) {
throw new AlfrescoRuntimeException(I18NUtil.getMessage(getErrorId(),
String.format("Node could not be found, XPATH query %s returned %i nodes.", path, refs.size())
));
}
return refs.get(0);
}
}
And your bootstrap context xml will need to include something like this:
<bean
id="org.tutorial.folderUpdateWipPermissions"
class="org.tutorial.patch.UpdatePermissionsPatch"
parent="basePatch"
>
<property name="id" value="org.tutorial.bootstrap.patch.folderUpdateWipPermissions" />
<property name="description" value="org.tutorial.bootstrap.patch.folderUpdateWipPermissions.description" />
<property name="fixesFromSchema" value="0" />
<property name="fixesToSchema" value="${version.schema}" />
<property name="targetSchema" value="100003" />
<property name="serviceRegistry">
<ref bean="ServiceRegistry"/>
</property>
<property name="path" value="/${spaces.company_home.childname}/cm:Work_x0020_In_x0020_Progress" />
<property name="authority" value="GROUP_MyGroup" />
<property name="permission" value="Consumer" />
<property name="allowed" value="true" />
<property name="clearPermissions" value="true" />
</bean>

How to configure RetryAdvice and ExceptionTranslation for Deadlocks using NHibernate and Spring

i am using Spring.net 1.2 with NHibernate 2.0.1.
Within my project i'am facing some Deadlock issues and besides the database tweaks to minimize the occurence i would like to implement Springs RetryAdvice to handle this.
I can't find any working example how to configure a this. The reference seems to be clear about how to use it but somehow i can't get it working.
<!--Used to translate NHibernate exception to Spring.DataAccessExceptions-->
<object type="Spring.Dao.Attributes.PersistenceExceptionTranslationPostProcessor, Spring.Data"/>
<!--ExceptionHandler performing Retry on Deadlocks-->
<object name="ExceptionHandlingAdvice" type="Spring.Aspects.RetryAdvice, Spring.Aop">
<property name="retryExpression" value="on exception name DeadLockLoserException retry 3x rate (1*#n + 0.5)"/>
</object>
I have added the [Repository] attribute to my DAOs to get ExceptionTranslation enabled and tried to add the RetryAdvice to the TransactionProxyFactoryObject i am using but it won't work. I don't understand where to put this Advice. Do i have to declare a PointCut to add it or how could i get it to work as expected.
Thx in advance - any help appreciated.
After 1 and a half month of waiting for someone solving my problem i finally found time to elaborate the solution for this by myself. In fact it wasn't that difficult i thought it was. Maybe thats why i wasn't able to find any good example.
So here we go: The following test will show the usage:
Configuration: (SessionFactory and TransactionManager etc. omitted for brevity)
<!-- Retries the Tx after DeadlockExceptions -->
<object name="ExceptionHandlingAdvice" type="Spring.Aspects.RetryAdvice, Spring.Aop">
<property name="retryExpression" value="on exception name DeadlockLoserDataAccessException retry 3x delay 1s"/>
</object>
<!--A Transaction-Configuration for our DAO-MOCK-->
<object id="TxProxyConfigurationTemplate" abstract="true" type="Spring.Transaction.Interceptor.TransactionProxyFactoryObject, Spring.Data">
<property name="PlatformTransactionManager" ref="HibernateTransactionManager"/>
<property name="TransactionAttributes">
<name-values>
<add key="ThrowDeadLock*" value="PROPAGATION_REQUIRED"/>
</name-values>
</property>
</object>
<object id="MockDaoTxPFO" parent="TxProxyConfigurationTemplate">
<property name="Target" ref="MockDao"/>
</object>
<!--The ProxyFactoryObject based on the DAO-Mock interface-->
<object id="MockDao" type="Spring.Aop.Framework.ProxyFactoryObject, Spring.Aop" >
<property name="proxyInterfaces" value="RetryAdvice.IDaoMock"/>
<property name="target" ref="MockDaoImpl"/>
<property name="interceptorNames">
<list>
<value>ExceptionHandlingAdvice</value>
</list>
</property>
</object>
<!--Mocked DAO Implementation -->
<object id="MockDaoImpl" type="RetryAdvice.DaoMock, RetryAdvice">
<constructor-arg name="maxExceptionCount" value="2" />
</object>
Mocked Dao: This DAO will throw DeadLockLooserExceptions twice and then pass.
public interface IDaoMock
{
void ThrowDeadLock();
int MethodCallCount { get; }
}
[Repository]
public class DaoMock : IDaoMock
{
private int maxExceptionCount;
public int MethodCallCount { get; private set; }
public DaoMock(int maxExceptionCount)
{
this.maxExceptionCount = maxExceptionCount;
}
public void ThrowDeadLock()
{
MethodCallCount++;
if (MethodCallCount <= maxExceptionCount)
{
throw new DeadlockLoserDataAccessException("FAKE", new HibernateException("This is a fake Exception.", null));
}
}
The Test:
[Test]
public void RetryAdviceTest()
{
IDaoMock mockDao = (IDaoMock)this.appContext.GetObject("MockDaoTxPFO");
mockDao.ThrowDeadLock();
Assert.That(mockDao.MethodCallCount, Is.EqualTo(3));
}
Any hints or remarks appreciated.