Using #EJB injection in an Application Client, both in same EAR - eclipse

I've searched now for days to find some solution for my, in my opinion not too hard but obviously unsolvable problem.
I have an EAR project containing Some EJB, a web client (works fine) and now I added an Application Client Module.
As everything is in the same project, I thought a simple #EJB injection in the main class of the application client would do. I also tried a JNDI lookup.
I use eclipse and glassfish as a server and tried to run the application 1. in eclipse (there my injected bean is just null) and 2. downloaded the client-stub from the glassfish administration and tried to start it with sh appclient -client (or -jar) OmazanClient.jar (and also the other two jars hidden in the client-stub folder). There I get mostly a "ClassNotFoundExeption:Main" like
java.lang.ClassNotFoundException: Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at org.glassfish.appclient.client.acc.ACCClassLoader.findClass(ACCClassLoader.java:212)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.glassfish.appclient.client.acc.FacadeLaunchable.getMainClass(FacadeLaunchable.java:262)
at org.glassfish.appclient.client.acc.AppClientContainer.setClient(AppClientContainer.java:324)
at org.glassfish.appclient.client.acc.AppClientContainerBuilder.createContainer(AppClientContainerBuilder.java:185)
at org.glassfish.appclient.client.acc.AppClientContainerBuilder.newContainer(AppClientContainerBuilder.java:172)
at org.glassfish.appclient.client.AppClientFacade.createContainerForAppClientArchiveOrDir(AppClientFacade.java:492)
at org.glassfish.appclient.client.AppClientFacade.createContainer(AppClientFacade.java:454)
at org.glassfish.appclient.client.AppClientFacade.prepareACC(AppClientFacade.java:269)
at org.glassfish.appclient.client.acc.agent.AppClientContainerAgent.premain(AppClientContainerAgent.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:323)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:338)
So for the injection, my code looks like:
public class Main {
#EJB (mappedName="ejb/customerBean")
public static CustomerInterface customerBean;
#EJB (mappedName="ejb/productBean")
public static ProductInterface productBean;
public static void main(String[] args) {
try{
Main m = new Main();
m.runDialog();
}
catch (Exception e){
e.printStackTrace();
}
}
/* (non-Java-doc)
* #see java.lang.Object#Object()
*/
public Main() {
super();
}
private void runDialog() throws Exception{
System.out.println("Test");
List<ProductDTO> productList = productBean.getAllProducts();
...
My remote interface looks like this:
#Remote
public interface ProductInterface {
public int addProduct(String productName);
public void deleteProduct(int prodid);
public void updateProduct(int prodid, String newName);
List<ProductDTO> getAllProducts();
...
My implementation is this:
/**
* Session Bean implementation productInterface
* */
#Stateless(mappedName="ejb/productBean")
#LocalBean
#WebService
public class ProductBean implements ProductInterface {
#EJB ProductEAO eao;
#EJB Conversion conv;
/**
* Default constructor.
*/
public ProductBean() {
// TODO Auto-generated constructor stub
}
#Override
public int addProduct(String prodName) {
return eao.addProduct(prodName);
}
#Override
public List<ProductDTO> getAllProducts() {
List<ProductDTO> result = new ArrayList<ProductDTO>();
List<Product> allProducts = eao.allProducts();
for (Product pr : allProducts) {
ProductDTO ci = conv.fromProduct(pr);
result.add(ci);
}
return result;
}
... and so on (all methods required by the interface are implemented, just try to keep it shorter here)
and the MANIFEST.MF is just
Manifest-Version: 1.0
Main-Class: Main
I've tried a lot like JNDI lookup, giving the bean names (see example) etc. But either the interface is not found (lookup) or the bean simply null.
How ever I am also not quite sure how to run the application client. I thought glassfishs appclient is the right starting point? It shall be a console-interaction so no swing components or anything similar.
Now I'd be thankful for any suggestions what I might have missed.
Cheers :)
Found a solution. Somehow, JNDI works now. Another problem was that my db query returned an Object and not primitive value or string - this caused a buffer error.
However, I am still confused on how to export an run an application client correctly. Maybe someone has an idea?!

There is a good example here: Create and Run a JEE6 Client Application with Netbeans 6.8 and Glassfish V3 - Part 2: Enhancing and Deploying the Application. It is a few years old, but it does give a pretty good overview.

Related

NullPointer while using JPA EntityManager in a ThredPoolExecutor

I'm implementing a JavaEE8 application using CDI and running on an Open Liberty (v20.0.0.4). The application has a event-triggered job, which runs some code in an separate thread using the ThreadPoolExecutor like this:
#Singleton
public class MyJobExecutorService {
#PostConstruct
public void init() {
thredPoolExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
}
public void runJob(MyConfigs configs) {
thredPoolExecutor.submit(() -> new MyJobRunnable(configs).run());
}
}
The job gets data from the underlying sql database using an EntityManager, which is injected in the data access class and produced like following. My querys are written using querydsl (which should not be relevant).
public class EntityManagerProducer {
#PersistenceContext(unitName = "my-unit")
private EntityManager entityManager;
#Produces
#Dependent
public EntityManager getEntityManager() {
return entityManager;
}
}
My persistence.xml looks like this:
<persistence ...>
<persistence-unit name=my-unit">
<jta-data-source>jdbc/datasource</jta-data-source>
</persistence-unit>
</persistence>
I have no issues accessing the database from the main thred, but the job throws a NullPointerException with the following stacktrace (and no further information):
com.ibm.ws.jpa.management.JPATxEntityManager.getEMInvocationInfo(JPATxEntityManager.java:213)
com.ibm.ws.jpa.management.JPATxEntityManager.getEMInvocationInfo(JPATxEntityManager.java:164)
com.ibm.ws.jpa.management.JPAEntityManager.getDelegate(JPAEntityManager.java:402)
com.querydsl.jpa.impl.JPAProvider.getTemplates(JPAProvider.java:61)
com.querydsl.jpa.impl.JPAQuery.<init>(JPAQuery.java:48)
com.querydsl.jpa.impl.JPAQueryFactory.query(JPAQueryFactory.java:138)
com.querydsl.jpa.impl.JPAQueryFactory.select(JPAQueryFactory.java:81)
com.querydsl.jpa.impl.JPAQueryFactory.selectFrom(JPAQueryFactory.java:111)
my.application.MyRepository.getAll(DataAccess.java:67)
sun.reflect.GeneratedMethodAccessor1888.invoke(UnknownSource)
java.lang.reflect.Method.invoke(Method.java:498)
org.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:106)
my.application.MyRepository$Repository$Serializable$925348889$Proxy$_$$_WeldClientProxy.getAll(UnknownSource)
sun.reflect.GeneratedMethodAccessor1887.invoke(UnknownSource)
java.lang.reflect.Method.invoke(Method.java:498)
org.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:106)
my.application.DataAccess$587668909$Proxy$_$$_WeldClientProxy.getAllData(UnknownSource)
my.application.job.MyDefaultJob.runJob(MyDefaultJob.java:50)
sun.reflect.GeneratedMethodAccessor1886.invoke(UnknownSource)
java.lang.reflect.Method.invoke(Method.java:498)
org.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:106)
my.application.job.MyJob$588111896$Proxy$_$$_WeldClientProxy.runJob(UnknownSource)
my.application.job.MyJobExecutorService$MyRunnable.run(MyJobExecutorService.java:59)
my.application.job.MyJobExecutorService.lambda$runJob$0(MyJobExecutorService.java:36)
my.application.job.MyJobExecutorService$$Lambda$280/00000000A8128A20.run(UnknownSource)
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
java.util.concurrent.FutureTask.run(FutureTask.java:266)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:823)
Why am I getting this exception and how can I fix this? Activating the jpa an concurrency features in the server.xml of the application server didnt help. Thanks a lot.
Enabling the concurrent-1.0 feature alone doesn't do anything unless you are using the managed resources that it provides which capture the context of the application component (such as its java:comp name space and so forth) and makes it available when running the tasks that are submitted to it.
If you must use a ThreadPoolExecutor in order to manipulate its queue in some way beyond enforcing concurrency constraints (ManagedExecutorService can impose concurrency constraints via a configurable concurrencyPolicy), the simplest way to continue using a ThreadPoolExecutor is by supplying it with a ManagedThreadFactory,
#PostConstruct
public void init() {
ManagedThreadFactory threadFactory = InitialContext.doLookup(
"java:comp/DefaultManagedThreadFactory");
thredPoolExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
threadFactory);
}
ManagedThreadFactory captures the context that is present on the thread from which it is initially looked up. You'll need to decide if there is a better place for it than your init() method based on what context you want it to provide to your ThreadPoolExecutor tasks.
You should also be aware that any use of ThreadPoolExecutor (even in combination with a ManagedThreadFactory or ContextService) bypasses use of the Liberty global thread pool.

Arquillian Integration with WildFly 10

Can anyone please guide me on how to use Arquillian with WildFly 10. I have recently migrated my application from JBoss 7 to WildFly 10. Arquillian used to work with JBoss 7, but the same configuration is not working on WildFly 10.
I am able to integrate now, however my EJBs with JNDI names as "java:global/xyz/xyzEMFactor" is failing with following error:
Caused by: java.lang.Exception: {"WFLYCTL0180: Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.test.test.env.\"com.xyz.abc.poc.knowledge_ba‌​se.ontology.DBContex‌​tBean\".emFactory is missing [jboss.naming.context.java.global.xyz_dal.xyzpEMFactory‌​]"]} at org.jboss.as.controller.client.helpers.standalone.impl.Serve‌​rDeploymentPlanResul‌​tFuture.getActionRes‌​ult(ServerDeployment‌​PlanResultFuture.jav‌​a:134)
Following is my class:
#AccessTimeout(5 * 60 * 60 * 1000)
#StatefulTimeout(-1)
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class DBContextBean<T> {
#Inject
#EJB(lookup = "java:global/xyz_dal/xyzEMFactory")
private xyzEMFactory emFactory;
}
It was because, The testable war file, i was creating a jar as,
#Deployment(name = "xyz_dal", order = 3)
public static Archive<?> createDeployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive .class, "xyz_dal.jar")
.addClasses(xyzEMFactory.class, DBContextBean.class, xyzDao.class)
.addPackages(true, "com.xyz.abc.poc.entities")
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml").setManifest(new Asset() {
#Override
public InputStream openStream() {
// dependency management
return ManifestBuilder.newInstance()
.addManifestHeader("Dependencies", "xyz,javax.api,deployment.abc_common.jar")
.openStream();
}
});
return jar;
}
It worked when i changed it to
#Deployment(name = "xyz_dal", order = 3)
public static Archive<?> createDeployment() {
WebArchive jar = ShrinkWrap.create(WebArchive.class, "xyz_dal.war")
.addClasses(xyzpEMFactory.class, DBContextBean.class, xyzDao.class)
.addPackages(true, "com.xyz.abc.poc.entities")
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml").setManifest(new Asset() {
#Override
public InputStream openStream() {
// dependency management
return ManifestBuilder.newInstance()
.addManifestHeader("Dependencies", "xyz,javax.api,deployment.abc_common.jar")
.openStream();
}
});
return jar;
}
It was because when i was creating a testable jar,the container wraps the jar in a test.war, and hence the context "java:global/xyz/xyzEMFactory" was not available.
I don't know how this could work in JBoss7 but: either #EJB or #Inject, I presume #Inject, is superfluous. In my experience wildfly is sometimes more rigorous than jboss7 when looking at unclear constructs.
#Inject
#EJB(lookup = "java:global/xyz_dal/xyzEMFactory")
xyzEMFactory emFactory;
CDI can't inject ejbs. What we do sometimes is:
#Produces
#EJB(lookup = "java:global/xyz/xyzEMFactory")
xyzEMFactory emFactory;
Then you can use at other places
#Inject
xyzEMFactory emFactory;
because the ejb-injected bean can be used as Producer-Field.

JPA static metamodel classes in EclipseLink throw NullPointerException when accessing attributes

I have a problem with generated static metamodel classes in EclipseLink.
In my project I firstly generated static metamodel classed for my entities using:
1) org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor and IntelliJ IDEA
and this classes have been generated to: target/generated-sources
Then I try to use such Hibernate generated metamodel classes (ex. below) with EclipseLink (GlassFish embedded), but lines of code that contains references to metamodel attributes throws NullPointerException exception:
SingularAttribute<Employee, String> descriptionAttr = Employee_.description;
predicates.add(criteriaBuilder.like(employee.get(descriptionAttr), "%" + description + "%"));
Here emploee.get( >> null << ) throws exception.
#Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
#StaticMetamodel(Employee.class)
public abstract class Employee_ extends pl.salonea.entities.NaturalPerson_ {
public static volatile SetAttribute<Employee, Skill> skills;
public static volatile SetAttribute<Employee, ProviderService> suppliedServices;
public static volatile SetAttribute<Employee, EmployeeRating> receivedRatings;
public static volatile SingularAttribute<Employee, String> description;
public static volatile SetAttribute<Employee, Education> educations;
public static volatile SingularAttribute<Employee, String> jobPosition;
public static volatile SetAttribute<Employee, TermEmployeeWorkOn> termsOnWorkStation;
}
2) Next I thought that this metamodel classes maybe are implementation specific. So I generated them analogically with EclipseLink using
org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor and target/generated-sources-eclipselink (as on picture)
At the end I have something like this directory stracture with metamodel:
3) I am also using in build.gradle such configuration to as I think include this generated sources in project:
if(hasProperty('jboss')) {
sourceSets {
main {
java {
srcDir 'target/generated-sources/'
}
}
}
} else {
sourceSets {
main {
java {
srcDir 'target/generated-sources-eclipselink/'
}
}
}
}
This way I want to use Hibernate generated classes with Jboss and EclipseLink generated classes with EclipseLink.
4) Such configuration works only if running on WilfFly/Hibernate but not on GlassFish/EclipseLink here is this NullPointerException
5) In persistence.xml I have more over EclipseLink generation using such property for one Persistence Unit
<property name="eclipselink.canonicalmodel.subpackage" value="metamodel" />
and such property for second Persistence Unit (to avoid duplicate conflict)
<property name="eclipselink.canonicalmodel.subpackage" value="metamodel_local" />
But I'm trying not to use this generation. It is in subpackage and in my code I only import previously generated metamodel classes.
The reason is that I would like to have in the same namespace metamodel classes generated by Hibernate/Eclipse and use them appropriately.
However if Hibernate generated metamodel classes could be also work with EclipseLink there won't be problem to using only one generation.
6) Moreover I cant use metamodel classes generated by EclipseLink persistence.xml property as they are regenerated each time I run/build my project. And I need in my code to manually modify two metamodel classes as they are inherited from single abstract metamodel class. Here I am overriding in subclasses AbstractType with ConcreteType on SetAttribute of metamodel class.
7) At the end I paste error I'm getting while running integration test with such configuration of metamodel classes
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.internal.jpa.querydef.FromImpl.get(FromImpl.java:263)
at pl.salonea.ejb.stateless.EmployeeFacade.findByMultipleCriteria(EmployeeFacade.java:295)
at pl.salonea.ejb.stateless.EmployeeFacade.findByMultipleCriteria(EmployeeFacade.java:269)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor113.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor141.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 149 more
-I'm checking EclipseLink sources:
public <Y> Path<Y> get(SingularAttribute<? super X, Y> att){
if (att.getPersistentAttributeType().equals(
PersistentAttributeType.BASIC)) {
return new PathImpl<Y>(
this, this.metamodel, att.getBindableJavaType(),
this.currentNode.get(att.getName()), att);
} else {
Class<Y> clazz = att.getBindableJavaType();
Join join = new JoinImpl<X, Y>(
this, this.metamodel.managedType(clazz),
this.metamodel, clazz,
this.currentNode.get(att.getName()), att);
this.joins.add(join);
return join;
}
}
FromImpl.java:263 is condition of if statement so it looks like att.getPersistentAttributeType() returns null.
It would be good if you'll file a bug against EclipseLink on https://bugs.eclipse.org/bugs/enter_bug.cgi?product=EclipseLink
Component is JPA. Please copy-paste this description there and provide some test-case (sample application with this metamodel) to let us reproduce it and develop some fix.
The problem can be in the failed initialization Canonical Metamodel.
You can investigate yours eclipselink log for checking something like that:
Could not load the field named [...] on the class [...]
IllegalArgumentException: Can not set static ... field ... to ...
In my case after fixing initialization, NPE had gone.
I know this is an old ticket but i still wanted to let you guys know how we fixed the problem. Especially the last nullpointer exception.
The problem is that your entitimanager is not loaded when you are using your Criteriabuilder for the first time.
To solve this problem you can set following in you persistence.xml
<property name="eclipselink.deploy-on-startup" value="true" />

Test the remote client jndi lookup using arquillian

Setup: arquillian, jboss as 7.1.1.final as a managed Container
I am currently migrating an EJB application from EJB 2.x to 3.x and JBoss 3.x to JBoss AS 7.1.
During this process i would like to get most classes under test and stumbled over arquillian.
While arquillian seems to offer some nice features on inter-bean-functionality i cannot figure out whether or not the testing of remote client features using jndi lookups works or not.
I used the Arquillian Getting started guides on my beans which worked, but since these are using #Inject and in my application jndi lookups are used everywhere i (at least think that i) need to swerve from that path.
Here is the TestCase i created based on Arquillian Getting Started. I explicitly left in all attempts using jndi properties of which i thought they might help.
The Test
should_create_greeting()
works if the Greeter bean using a separate Producer.
#RunWith(Arquillian.class)
public class GreeterTest {
public static final String ARCHIVE_NAME = "test";
Logger logger = Logger.getLogger(GreeterTest.class.getName());
#Deployment
public static Archive<?> createDeployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar").addPackage(Greeter.class.getPackage())
.addAsManifestResource("test-persistence.xml", "persistence.xml").addAsManifestResource("OracleGUIDS-ds.xml")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
return jar;
}
/**
* #Inject works using a producer with {#code #Produces}
*/
// #Inject
// Greeter greeter;
#ArquillianResource
Context context;
GreeterRemote greeter;
#Before
public void before() throws Exception {
Map<String, String> env = new HashMap<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory");
env.put("jboss.naming.client.ejb.context", "true");
// env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT",
// "false");
// env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS",
// "false");
// env.put("jboss.naming.client.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
// "false");
for (Map.Entry<String, String> entry : env.entrySet()) {
context.addToEnvironment(entry.getKey(), entry.getValue());
}
greeter = (GreeterRemote) context.lookup(ARCHIVE_NAME + "/" + Greeter.class.getSimpleName() + "!"
+ GreeterRemote.class.getName());
}
#Test
public void should_create_greeting() {
Assert.assertEquals("Hello, Earthling!", greeter.createGreeting("Earthling"));
greeter.greet(System.out, "Earthling");
}
}
Is it possible to get this test running with jndi lookup? Am i missing something?
If you want to test the Remote features of a EJB you probably want to run on the client side and not in container.
You can configure the Deployment to be only client side by using #Deployment(testable=false). The #Test methods will then run as if you were a remote client.
Beyond that you can just lookup the bean via the injected Context if you want.
I had the same issue, so in a workaround i just added on the method to be tested the remoteejb as a parameter.
On my ejb:
public List localBean.obtain(RemoteEJB remoteEjb){
return remoteEjb.obtain();
}
Then on the arquillian test :
#Inject
private LocalBean localBean;
#Inject
private RemoteEJB remoteEjb;
#Test
public void test(){
List<Vo>voList = localBean.obtain(remoteEjb);
}
The best part is the remote ejb its injected and on the caller method original
#EJB(lookup="java:global/ear/ejb/RemoteEjb")
private RemoteEJB remoteEjb;

google-gin a provider needs a dependency. NullPointerException BindingsProcessor.java:498

In my GWT application i'm trying to setup a DI mechanism wihich would allow me to have all the commonly necessary stuff at hand everywhere. I'm using google-gin which is an adaptation of guice for GWT. I have an injector interface defined as this:
#GinModules(InjectionClientModule.class)
public interface MyInjector extends Ginjector {
public PlaceController getPlaceController();
public Header getHeader();
public Footer getFooter();
public ContentPanel getContent();
public EventBus getEventBus();
public PlaceHistoryHandler getPlaceHistoryHandler();
}
My injection module is this:
public class InjectionClientModule extends AbstractGinModule {
public InjectionClientModule() {
super();
}
protected void configure() {
bind(Header.class).in(Singleton.class);
bind(Footer.class).in(Singleton.class);
bind(ContentPanel.class).in(Singleton.class);
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
bind(PlaceController.class).toProvider(PlaceControllerProvider.class).asEagerSingleton();
bind(PlaceHistoryHandler.class).toProvider(PlaceHistoryHandlerProvider.class).asEagerSingleton();
}
}
When calling MyInjector injector = GWT.create(MyInjector.class); i'm gettign the following exception:
java.lang.NullPointerException: null
at com.google.gwt.inject.rebind.BindingsProcessor.createImplicitBinding(BindingsProcessor.java:498)
at com.google.gwt.inject.rebind.BindingsProcessor.createImplicitBindingForUnresolved(BindingsProcessor.java:290)
at com.google.gwt.inject.rebind.BindingsProcessor.createImplicitBindingsForUnresolved(BindingsProcessor.java:278)
at com.google.gwt.inject.rebind.BindingsProcessor.process(BindingsProcessor.java:240)
at com.google.gwt.inject.rebind.GinjectorGeneratorImpl.generate(GinjectorGeneratorImpl.java:76)
at com.google.gwt.inject.rebind.GinjectorGenerator.generate(GinjectorGenerator.java:47)
at com.google.gwt.core.ext.GeneratorExtWrapper.generate(GeneratorExtWrapper.java:48)
at com.google.gwt.core.ext.GeneratorExtWrapper.generateIncrementally(GeneratorExtWrapper.java:60)
at com.google.gwt.dev.javac.StandardGeneratorContext.runGeneratorIncrementally(StandardGeneratorContext.java:647)
at com.google.gwt.dev.cfg.RuleGenerateWith.realize(RuleGenerateWith.java:41)
at com.google.gwt.dev.shell.StandardRebindOracle$Rebinder.rebind(StandardRebindOracle.java:78)
at com.google.gwt.dev.shell.StandardRebindOracle.rebind(StandardRebindOracle.java:268)
at com.google.gwt.dev.shell.ShellModuleSpaceHost.rebind(ShellModuleSpaceHost.java:141)
at com.google.gwt.dev.shell.ModuleSpace.rebind(ModuleSpace.java:585)
at com.google.gwt.dev.shell.ModuleSpace.rebindAndCreate(ModuleSpace.java:455)
at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:49)
at com.google.gwt.core.client.GWT.create(GWT.java:97)
The problem is that the PlaceController class actually depends on one of the other dependencies. I've implemented it's provider like this:
public class PlaceControllerProvider implements Provider<PlaceController> {
private final PlaceController placeController;
#Inject
public PlaceControllerProvider(EventBus eventBus) {
this.placeController = new PlaceController(eventBus);
}
#Override
public PlaceController get() {
return placeController;
}
}
what should i change for this to work?
Old question but having the same problem I kept falling here. I finally found the way to know which class is messing during ginjection.
When I launch my app in development mode and put stack to Trace, I noticed there is a step called : "Validating newly compiled units".
Under this, I had an error but I didn't notice it since I had to expand 2 nodes which weren't even in red color.
The error was "No source code available for type com.xxx.xxxx ...", which was due to a bad import on client side which couldn't be converted to Javascript.
Hope this may help other here !
While I'm not actually seeing how the errors you're getting are related to the PlaceController being injected, I do see that the provider is returning a singleton PlaceController even if the provider were not bound as an eager singleton or in a different scope. The correct way to write that provider would be:
public class PlaceControllerProvider implements Provider<PlaceController> {
private final EventBus eventBus;
#Inject
public PlaceControllerProvider(EventBus eventBus) {
this.eventBus = eventBus;
}
#Override
public PlaceController get() {
return new PlaceController(eventBus);
}
}
Let guice handle the scoping i.e. "Letting guice work for you".
Other than that, I almost bet that your problem is due to the use of asEagerSingleton. I recommend you try this with just in(Singleton.class) and I further posit that you didn't really need the singleton to be eager. It seems others had problems with the behavior too, there's some indication that it has to do with overusing asEagerSingleton or misunderstanding the #Singleton annotation in a few cases.
I also got a lot of NullPointerException warnings using GIN 1.x with no real explanation of what happened. When I upgraded to gin 2.0 I was told with high accuracy what the error was. You might be helped by upgrading to the 2.0 version that was released a year after you asked this question.
Had the same problem problem, same trace, and the error was that I used "server" classes in my "client" classes, so GIN can't find these classes.
I mean by "server" and "client" the packages in my project.
Hope this could help