IllegalStateException while using UserTransaction (Java EE) - java-ee-6

I am trying to make my first Java Enterprise Application and use UserTransactions.
Therefore I use JNDI Lookup with java:comp/UserTransaction to get my UserTransaction Object.
public void myMethod(MyEntity e) throws ApplicationException {
try {
this.ut = getUserTransaction();
this.ut.begin();
this.myStatefulBean.myBusinessMethod(e);
} catch ...
When I start my Transaction with .begin() and try to invoke any method in my stateful Bean (which works properly before starting a UserTransaction) I get an EJBTransactionRolledbackException which leads me to the following error:
java.lang.IllegalStateException: cannot add non-XA Resource to global JTS transaction
The Bean I am using is annotated with #DataSourceDefinition having className = "org.apache.derby.jdbc.ClientXADataSource" thus there is imo no non-XA Resource.
What am I doing wrong?
I am using openjpa 2.2.1, Java EE Version 6

Solved the problem by myself. I used in my DataSourceDefinition name = "java:global/jdbc/testDB" as name, but in my persistence.xml the DataSource name was defined as <jta-data-source>testDB</jta-data-source>
This seems to work in CMTs but not in a UserTransaction. Correcting the entry in persistence.xml to <jta-data-source>java:global/jdbc/testDB</jta-data-source> fixed the problem.

Related

Unable to access Weblogic datasource through JNDI name using Spring Data JPA

I am using Weblogic 12c and I have configured my datasources like this:
Notice that they are all deployed on target "AdminServer". Also, the "Name" field and "JNDI Name" field are identical. For example, suppose one datasource's name is "MYDS".
Now, when I try to acquire that datasource through Spring Data JPA like this:
#Bean
#Primary
public DataSource businessDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean dataSource = new JndiObjectFactoryBean();
dataSource.setResourceRef(true);
dataSource.setJndiName("MYDS");
dataSource.afterPropertiesSet();
return (DataSource) dataSource.getObject();
}
I get the following error when trying to deploy the war file to weblogic:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [javax.sql.DataSource]: Factory method
'businessDataSource' threw exception; nested exception is
javax.naming.NameNotFoundException: Unable to resolve 'MYDS'. Resolved
''; remaining name 'MYDS'
Also I see this error:
DEBUG o.s.jndi.JndiObjectFactoryBean - Converted JNDI name
[java:comp/env/MYDS] not found - trying original name [MYDS].
javax.naming.NameNotFoundException: While trying to look up
comp/env/MYDS in /app/myapp/webclient/404708050.; remaining name
'comp/env/MYDS'
Just looking at the source for setResourceRef and it states :
public void setResourceRef(boolean resourceRef)
Set whether the lookup occurs in a Java EE container,
i.e. if the prefix "java:comp/env/" needs to be added if the JNDI name doesn't already contain it.
Default is "false".
Note: Will only get applied if no other scheme (e.g. "java:") is given.
If you are setting it to true have you tried adding java:comp/env/ to the JNDI name ?

UnknownServiceException: Unknown service requested [EnversService]

I want to run Hibernate in OSGi. I have added the standard Hibernate OSGi bundle and a Blueprint implementation, so that Envers gets registered right on startup.
Even without any kind of documentation I found out you have to start Envers, because... I doubt there is a logical reason, it does not work otherwise.
However now, even though Envers was registered in Blueprint, I get the following exception:
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.envers.boot.internal.EnversService]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:184)
at org.hibernate.envers.boot.internal.TypeContributorImpl.contribute(TypeContributorImpl.java:22)
at org.hibernate.boot.internal.MetadataBuilderImpl.applyTypes(MetadataBuilderImpl.java:280)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.populate(EntityManagerFactoryBuilderImpl.java:798)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:187)
at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:34)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:165)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:114)
at org.hibernate.osgi.OsgiPersistenceProvider.createEntityManagerFactory(OsgiPersistenceProvider.java:78)
at org.acme.project.Main.startSession(PersistenceUnitJpaProvider.java:38)
The stack trace starts at PersistenceProvider#createEntityManagerFactory in the following snippet:
public class Main {
private EntityManagerFactory entityManagerFactory;
public void startSession(Map<String, Object> config) {
BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
ServiceReference<PersistenceProvider> serviceReference = context.getServiceReference(PersistenceProvider.class);
PersistenceProvider persistenceProvider = context.getService(serviceReference);
this.entityManagerFactory = persistenceProvider.createEntityManagerFactory("persistenceUnit", config);
context.ungetService(serviceReference);
}
I found this bug, and maybe this issue is fixed in the current version of Hibernate. But since the bundle IDs are broken, I have to use 5.1.
So Envers is registered, but not really. What could be the reason for such a strange error message?

Injecting EJB within JAX-RS resource in JBoss 5

Although there already are quite some StackOverflow questions, blog entries, etc. on the web, I still cannot figure out a solution to the problem stated below.
Similar to this question (Injecting EJB within JAX-RS resource on JBoss7) I'd like to inject a EJB instance into a JAX-RS class. I tried with JBoss 5, JBoss 7, and WildFly 8. I either get no injection at all (field is null), or the server does not deploy (as soon as I try to combine all sorts of annotations).
Adding #Stateless to the JAX-RS makes the application server know both classes as beans. However, no injection takes place.
Is there a way to inject EJBs into a REST application? What kind of information (in addition to that contained in the question linked to above) could I provide to help?
EDIT: I created a Github project showing code that works (with Glassfish 4.0) and does not work (with JBoss 5).
https://github.com/C-Otto/beantest
Commit 4bf2f3d23f49d106a435f068ed9b30701bbedc9d works using Glassfish
4.0.
Commit 50d137674e55e1ceb512fe0029b9555ff7c2ec21 uses Jersey 1.8, which does not work.
Commit 86004b7fb6263d66bda7dd302f2d2a714ff3b939
uses Jersey 2.6, which also does not work.
EDIT2:
Running the Code which I tried on JBoss 5 on Glassfish 4.0 gives:
Exception while loading the app : CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)
EDIT3: The crucial information might be that I'd like a solution that works on JBoss 5
If you don't want to make your JAX-RS resource an EJB too (#Stateless) and then use #EJB or #Resource to inject it, you can always go with JNDI lookup (I tend to write a "ServiceLocator" class that gets a service via its class.
A nice resource to read about the topic:
https://docs.jboss.org/author/display/AS71/Remote+EJB+invocations+via+JNDI+-+EJB+client+API+or+remote-naming+project
A sample code:
try {
// 1. Retreive the Home Interface using a JNDI Lookup
// Retrieve the initial context for JNDI. // No properties needed when local
Context context = new InitialContext();
// Retrieve the home interface using a JNDI lookup using
// the java:comp/env bean environment variable // specified in web.xml
helloHome = (HelloLocalHome) context.lookup("java:comp/env/ejb/HelloBean");
//2. Narrow the returned object to be an HelloHome object. // Since the client is local, cast it to the correct object type.
//3. Create the local Hello bean instance, return the reference
hello = (HelloLocal)helloHome.create();
} catch(NamingException e) {
} catch(CreateException e) {
}
This is not "injecting" per-se, but you don't use "new" as-well, and you let the application server give you an instance which is managed.
I hope this was useful and I'm not telling you something you already know!
EDIT:
This is an excellent example: https://docs.jboss.org/author/display/AS72/EJB+invocations+from+a+remote+client+using+JNDI
EDIT 2:
As you stated in your comment, you'd like to inject it via annotations.
If the JNDI lookup is currently working for you without problems, and
If you're using Java EE 6+ (which I'm guessing you are), you can do the following:
#EJB(lookup = "jndi-lookup-string-here")
private RemoteInterface bean;

Connect to a running JBoss AS7 instance for test purposes

I already have a integration-test phase, when I ran the selenium tests. I also want to run some unit tests in this phase, because the app is too much complex and have a lot of dependencies between his modules (a hell), so, after a week fighting against OpenEJB and Arquillian, I believe that this would be easier.
The thing is: how do I made it work?
I have the instance already running, if I instantiate an InitialContext and try to lookup some bean, I got an exception telling me that I have not set the java.naming.initial.factory, and I don't know what to put in there.
I'm also complaining about the annotated beans.
Suppose a Bean like this:
#Stateless
public class ABeanImpl implements ABean {
#EJB
private BBean;
}
Will the container automatically get right the BBean?
Thanks in advance
How to connect to JBoss 7.1 remote JNDI:
Here is the code snippet that I use for JBoss 7.1:
Properties props = new Properties();
String JBOSS_CONTEXT = "org.jboss.naming.remote.client.InitialContextFactory";
props.put("jboss.naming.client.ejb.context", true);
props.put(Context.INITIAL_CONTEXT_FACTORY, JBOSS_CONTEXT);
props.put(Context.PROVIDER_URL, "remote://localhost:4447");
props.put(Context.SECURITY_PRINCIPAL, "jboss");
props.put(Context.SECURITY_CREDENTIALS, "jboss123");
InitialContext ctx = new InitialContext(props);
Resolution of ambiguous ejb references:
According to JBoss EJB 3 reference, if at any level of your EJB environment (EJB/EAR/Server) are duplicates in used interfaces, exception will be thrown during resolution of injected beans.
Based on above, if you have got a reference to EJB bean which interface:
has two implementations in your EJB module (JAR/WAR) - exception will be thrown
has two implementations in your application (other EJB JAR's in same EAR) - exception will be thrown
has two implementations, one in module with bean ABeanImpl, second somewhere else - implemetation from current module is used.

TomEE 4 JPA issue

I am trying out simple JPA example on TomEE 4.0.0 and I am not able to get PersistenceContextType.EXTENDED working
If I make my session bean Stateless and leave PersistenceContextType then it works fine
#PersistenceContext(unitName = "xxx" )
private EntityManager entityManager;
If I keep my session bean as Stateless and then try to use this
#PersistenceContext(unitName = "xxx", type = PersistenceContextType.EXTENDED))
private EntityManager entityManager;
it gives me an error while deploying, which is perfectly fine and in line with expectation.
However now when I make my bean as #Stateful, then also it gives me an error
Managed ejbs are not capable of using EntityManagers with EXTENTED persistence. Convert your bean to a Stateful ejb or update the "java:comp/env/com.testwebservice.TestJPAService/entityManager" PersistenceContext reference to PersistenceContextType.TRANSACTION.
Can some one please help, I am really confused for this
#Stateful EXTENDED persistence contexts are tested in numerous ways in the TomEE build and also in the Java EE TCK.
Likely this is something else completely. We do our best to warn you when you make obvious mistakes as you note with the incorrect combination of #Stateless with PersistenceContextType.EXTENDED
Looking at the JNDI name which contains com.testwebservice.TestJPAService and given the fact it was #Stateless before it was changed to #Stateful, my guess is that this bean is also an #WebService which is illegal. #Stateful beans cannot be #WebService beans. Without a proper check to prevent this mistake, my guess is that the bean is actually being deployed twice; once as a #Stateful bean and once as an pojo #WebService. The pojo web service is the one causing the error.
In case that is the error, I've filed a JIRA for us to explicitly check that condition.