java ee lookup ejbs from from different app - rest

Java EE Tutorial is not helpful at all. Internet search was underwhelming.
I have an EJB module that is deployed to glassfish by itself. It has #Local and #Remote annotated iterfaces which are both implemented by the concrete class.
Then i have a REST resource that needs to get a reference to that ejb module and invoke some methods.
Can you give me a barebones, simple example of how that is done? I mean, i can't even inject SessionContext into my rest app, as it crashes... Please, keep it simple.
The ejb should just have a:
public String getMsg(){
return "ohai";
}
The rest service:
#GET
#Produces("text/plain")
public String asd(){
return <the myterious ejb that was injected somehow>.getMsg();
}
Thanks.

Alright, i figured it out. Using NetBeans, but probably applicable to Eclipse. Server - glassfish
Create webapp, an EJB -> call EJB from webapp. All these run inside the same server as separate modules.
First: create an EJB module, it will be deployed on its own:
remote interface:
package main;
import javax.ejb.Remote;
#Remote
public interface YourRemoteInterface{
public String tellMeSomething();
public void otherMethod(); //etc...
}
then create the EJB implementation class:
concrete implementation
package main;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.EJB; //crucial to JNDI lookup
#Remote(RemoteInterface.class)
#Stateless
#EJB(name="java:global:/MYSTUFF", beanInterface=YourRemoteInterface.class)
public class YourConcreteClass implements YourRemoteInterface{
#Override
public String tellMeSomething(){//...} //and do the other methods
}
#EJB name attribute names your bean, that you will use to look it up. Can by any name. For ex: "some-name", or "java:global/YourConcreteClass"
Part two - webapp:
For web app i used a rest service, but surely can be another EJB or a SE client app. For SE client you'd need to set connection info, but that for another life.
#Path("/somePath")
public class Service{
#GET
#Produces("text/plain")
public String qwe(){
try{
javax.naming.InitialCOntext ic = new javax.naming.InitialContext();
YourRemoteInterface rb = (YourRemoteInterface)ic.lookup("java:global:/MYSTUFF");
return rb.tellMeSomething();
} catch (Exception ex) {
return "F*uck your life";
}
}
}
Now, from Project Properties of your webapp, you need to:
1) add the ejb jar file to Libraries so it shows in the Compile tab. I used the "Add project" button
2) Build -> Packaging: add the ejb jar file to WAR content. I used "Add file/folder", where i navigated to NetBeans projects / the EJB module / build / dist
note: you may experience an error when trying to deploy the ejb, or redeploy it. Error name is: java.lang.RuntimeException: Error while binding JNDI name main.RemoteInterface#main.RemoteInterface for EJB RemoteBean . Skipping the vague explanation, to cure it, you need to execute a command in glassfish:
asadmin set server.ejb-container.property.disable-nonportable-jndi-names="true"
Now, you can compile the webapp and deploy it. Should work.
At the end it's that simple. I swear i've eaten the WHOLE ejb section in glassfish tutorial and nowhere do they tell you this stuff. It's so annoying.

Related

How do I access DispatcherServlet with MockMvc?

I have a basic SpringMVC Application which is running (and mapping) fine.
Now I wanted to set up my UnitTests with MockMvc to perform get requests and stuff.
But if I run the test there is an AssertionError "Status expected: <200> but was: <404>" and my console gives warning "No mapping found for HTTP request with URI [/] in DispatcherServlet with name ''".
I get the feeling my MockMvc cant communicate with my DispatcherServlet, so how do I define this connection?
Here is my short test class:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration
public class HomeControllerTest {
private MockMvc mvc;
#Autowired
private WebApplicationContext wac;
#Before
public void setup() throws ServletException {
mvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
#Test
public void testLandingPagePath() throws Exception {
mvc.perform(get("/")).andExpect(status().isOk());
}
}
So I expected MockMvc to get the location of my DispatcherServlet by default. But it actually doesn't call it for mapping.
I have my "web.xml" and "dispatcher-servlet.xml" located in "WEB-INF" folder and no extra configuration defined.
I got the feeling the problem is based on my project structure, but this is a basic eclipse "Dynamic Web Application", the tests are located in "src/test/java", parallel to "src/main/java".
I appreciate any help, since I spend last 2 hours on reading for solutions but not getting the trick.
After some more time I got things right now:
There is still no way for me to access the dispatcher-servlet.xml in WEB-INF folder. I added a new "config" package to my test-package in parallel to my "controller" test package and put a copy of the dispatcher-servlet.xml in there, called "test-dispatcher-servlet.xml".
Now my test class is able to access this with
#ContextConfiguration("../config/test-dispatcher-servlet.xml")
public class HomeControllerTest {
Hope this can help others who start with spring mvc testing :-)

Wildfly 10 JAX-RS REST Service is not working - Result 404 not found

I want to create a simple JAX-RS REST Service for Wildfly 10. My issue is that my REST Service is not found. Result in browser is 404 not found. I am not sure what exactly the issue is. I get no error or exception in wildfly log file. I am using eclipse neon 3 and wildfly 10. My project is using JAX-RS not resteasy.
Here my project setup and code:
I have created a Dynamic Web Project in Eclipse.
I have set JAX-RS(REST Service) support in the project facets. JAX-RS version is 2.0 (also tried with version 1.1)
I have create a subclass which extends Application (javax.ws.rs.core.Application)
I added the annotation #ApplicationPath("/yoshi-rest") to the class which extends Application.
I have created a class which contains my rest service method. The class itself has the #Path("/StatusService") annotation.
The affected method has the annotations #Get and #Path("/getStatus").
Due to I have the subclass of Application I didn't set the servlet mapping in web.xml.
Here the code:
Subclass of Application(RESTConfig):
#ApplicationPath("/yoshi-rest")
public class RESTConfig extends Application {
}
REST Service class(StatusService):
#Path("/StatusService")
public class StatusService {
#Get
#Path("/getStatus")
public String getStatus() {
return "Yoshi is up and running";
}
}
I can see during startup of wildfly that the subclass RESTConfig is deployed:
11:09:23,777 INFO [org.jboss.resteasy.resteasy_jaxrs.i18n] (ServerService Thread Pool -- 61) RESTEASY002225: Deploying javax.ws.rs.core.Application: class XXXX.yoshi.rest.services.RESTConfig
If I call the rest service url (http://localhost:8080/yoshi-rest/StatusService/getStatus) in browser, I get a '404 - Not found' as result.
Any idea what I am doing wrong?
You need to register service to connect to your RESTConfig:
#ApplicationPath("/yoshi-rest")
public class RESTConfig extends ResourceConfig {
public RESTConfig() {
register(StatusService.class);
}
See more on ResourceConfig configuration options
Standard JAX-RS uses an Application as its configuration class. ResourceConfig extends Application.
Putting the project name in the url solved the issue.
Thanks for help.

JAX-RS service as #Stateless EJB : NameNotFoundException

I try to build a Java EE 7 app with Rest services and EJB injection.
I created a multi module maven project which I deploy on Glassfish 4. My final EAR contain a JAR with my EJBs, with for example my Rest services definitions :
#Stateless
#Path("countries")
public class CountryRest {
//#EJB
//StockService stockService;
#GET
public Response getCountries() {
//stockService.getAll(); --> firing a NPE, stockService is Null
return Response.ok().build();
}
}
#Stateless
#Remote(IStockService.class)
public class StockService implements IStockService {
#Override
public List<Stock> getAllStock() {
return new ArrayList<Stock>();
}
}
When I deploy my app, I see the following logs which seems ok. Even if I wonder why it defines "java:global" JNDI since by default #Stateless EJB is #Local :
Portable JNDI names for EJB CountryRest: [java:global/GeoData-ear/GeoData-ejb-1.0-SNAPSHOT/CountryRest, java:global/GeoData-ear/GeoData-ejb-1.0-SNAPSHOT/CountryRest!com.tomahim.geodata.rest.CountryRest]
Portable JNDI names for EJB StockService: [java:global/GeoData-ear/GeoData-ejb-1.0-SNAPSHOT/StockService, java:global/GeoData-ear/GeoData-ejb-1.0-SNAPSHOT/StockService!com.tomahim.geodata.services.IStockService]
Then when I'm doing a GET on /rest/countries, the status is 200 as expected but I have a NameNotFoundException / NamingException :
Avertissement: An instance of EJB class, com.tomahim.geodata.rest.CountryRest, could not be looked up using simple form name. Attempting to look up using the fully-qualified form name.
javax.naming.NamingException: Lookup failed for 'java:module/CountryRest' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:module/CountryRest]
I see that the lookup for "java:module/ContryRest" is not matching "java:global/.../CountryRest" but what am I doing wrong ?
EDIT 1 : I was able to make #Ejb injection work by placing my Rest definitions ans EJBs in my webapp maven module deploy as a WAR. So it seems that the problem occur only when I deploy my EJB in a JAR. Any idea ? What could be the difference between JAR and WAR deployment ?
It is required by the JAX-RS spec that all REST endpoints must live within your WAR file. Do you really need an EAR file?

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;

Configuring one ear to call remote ejb3 on another ear in JBoss

I am new to EJB3 and am missing something when it comes to accessing a #Remote #Stateless bean deployed as an ejb module inside an ear file. I want to access a remote bean in lima.ear from soup.ear.
Here is what I am doing now (somewhat abbreviated):
//deployed under lima.ear
#Remote
#Stateless
public interface LimaBean {
String sayName();
}
I want to put LimaBean in the Soup:
//deployed in soup.ear
#Stateless
public class Soup implements SoupLocal {
#EJB
private LimaBean limaBean;
public String taste() {
return limaBean.sayName();
}
}
When I start JBoss I get the following error:
java.lang.RuntimeException: could not resolve global JNDI name for #EJB for container Soup: reference class: com.example.LimaBean ejbLink: not used by any EJBs
I have had a hard time finding out what this ejbLink is about, if that is the right path to go down.
If I deploy LimaBean as a jar file in jboss then everything works great!
I ran accross an article that had a section called "2.5.3. References between beans in different jars and different ears"
(http://jonas.ow2.org/doc/howto/jboss2_4-to-jonas3_0/html/x111.html)
Example of jboss.xml file for SB_BrowseRegions:
<jboss>
<session>
<ejb-name>SB_BrowseRegions</ejb-name>
<ejb-ref>
<ejb-ref-name>ejb/Region</ejb-ref-name>
<jndi-name>protocol://serverName/directory/RegionHome</jndi-name>
</ejb-ref>
</session>
</jboss>
If I touch the soup.ear, after JBoss starts up then it deploys fine, so I am assuming I need to specify a dependency like the above article says.
But even after it deploys then I get an error when accessing the remote LimaBean:
Caused by: java.lang.IllegalArgumentException: Can not set com.soup.LimaBean field com.soup.Soup.limaBean to $Proxy147
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63)
at java.lang.reflect.Field.set(Field.java:657)
at org.jboss.injection.JndiFieldInjector.inject(JndiFieldInjector.java:115)
... 49 more
I have tried a few things but, if anyone can point me in the right direction about this I would appreciate it.
It looks like the JNDI properties need to be set as if it were a remote client outside of the app server because of the ear isolation we have setup.
properties.put(Context.PROVIDER_URL, url);
InitialContext ctx = new InitialContext(properties);
Just specify the URL for the InitialContext and that should do the trick.