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

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.

Related

How to integrate Keycloak with Payara Micro?

How i can integrate the Keycloak with Payara Micro?
I want create an stateless REST JAX-RS application that use the Keycloak as authentication and authorization server, but i unknown how do it.
The Eclipse MicroProfile JWT Authentication API defines the #LoginConfig annotation:
#LoginConfig(authMethod = "MP-JWT", realmName = "admin-realm")
#ApplicationPath("/")
public class MyApplication extends Application {...}
And the java EE the #RolesAllowed annotation:
#Path("/api/v1/books")
public class BooksController {
#GET
#RolesAllowed("read-books")
public Books findAll() {...}
}
How integrate these two things?
Keycloak project doesn't provide a native adapter for Payara Server or Payara Micro and the Payara project doesn't provide it either.
But Keycloak also provides a generic servlet filter adapter which should also use with Payara Micro: https://www.keycloak.org/docs/latest/securing_apps/index.html#_servlet_filter_adapter
Just add the keycloak-servlet-filter-adapter dependency into your web application and configure the adapter in the web.xml according to the documentation. I haven't tested it though, so I don't know if it really works.
I faced the same challenge in a personal project and as is mentioned Keycloak project does not provide a native adapter for Payara, in that moment I did a library to secure my app with Keycloak, if you like, you can take it a look and let me know if it's ok or how we can improve it.
https://github.com/pablobastidasv/kc_security
You can find solution in The Payara Monthly Roundup for April 2019
MicroProfile JWT with Keycloak - In this step by step blog, Hayri Cicekā€ demonstrates how to secure your services using MicroProfile JWT and Keycloak.
Init LoginConfig and map your roles using DeclareRoles
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.eclipse.microprofile.auth.LoginConfig;
import javax.annotation.security.DeclareRoles;
#LoginConfig(authMethod = "MP-JWT")
#ApplicationPath("/")
#DeclareRoles({ "mysimplerole", "USER" })
public class ApplicationConfig extends Application {
}
Add params to microprofile-config.properties
mp.jwt.verify.publickey.location=http://localhost:8084/auth/realms/public/protocol/openid-connect/certs
mp.jwt.verify.issuer=http://localhost:8084/auth/realms/public
And you can use your roles in RolesAllowed
#ApplicationScoped
#Path("/hello")
public class HelloWorldEndpoint {
#GET
#Produces("text/plain")
#RolesAllowed("mysimplerole")
public Response doGet() {
return Response.ok("Hello from MicroProfile!").build();
}
}

Swagger + jaxrs + embedded jetty + no web.xml

I have maven project with embedded jetty server.
I have already created apis using JAX-RS, which are working properly. Now I want to create swagger documentation for my apis.
To start with swagger I have added servlet configuration as describe below :
#WebServlet(name = "SwaggerConfig")
public class SwaggerServlet extends HttpServlet {
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("init SwaggerServlet");
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.0");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8082");
beanConfig.setBasePath("/api");
beanConfig.setResourcePackage("com.myCompany.myApisResourcePackage");
beanConfig.setScan(true);
}
}
Also, in main method,
along with my jersey configuration I have added following code :
//swagger
ServletHolder swaggerServletHolder = new ServletHolder(SwaggerServlet.class);
swaggerServletHolder.setInitOrder(1);
swaggerServletHolder.setInitParameter("swagger.api.basepath", "http://localhost:8082");
context.addServlet(swaggerServletHolder, "/api/*");
//swagger end
So, the problem is, I am not able to find where swagger.json will be created.
In this case, swagger scans packages as server log says it, but swagger.json still not getting created.
Note: I am currently not adding swagger-ui as I think it is not mandatory for creating swagger.json
I got swagger json by hitting url "localhost:8082/swagger.json". I used same configuration as posted in my question.

java ee lookup ejbs from from different app

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.

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?

Simple RESTful endpoint using wildfly

I am running a javaee web application from the ground up using wildfly and simply want to expose some RESTful web services. My wildfly application server is running with the defaults it shipped with and I am not using any database entities although I do have a persisitance.xml to make wildfly happy. My application deploys fine as indicated by log messages below.
12:50:38,585 INFO [org.jboss.resteasy.spi.ResteasyDeployment] (MSC service thread 1-5) Deploying javax.ws.rs.core.Application: class org.netbeans.rest.application.config.ApplicationConfig
12:50:38,585 INFO [org.jboss.resteasy.spi.ResteasyDeployment] (MSC service thread 1-5) Adding class resource os.acquisition.acq.Acquisition from Application class org.netbeans.rest.application.config.ApplicationConfig
12:50:38,588 INFO [org.wildfly.extension.undertow] (MSC service thread 1-5) JBAS017534: Registered web context: /acq-1.0
12:50:38,712 INFO [org.jboss.as.server] (management-handler-thread - 29) JBAS018565: Replaced deployment "acq-1.0.war" with deployment "acq-1.0.war"
My issue comes when trying to call the GET request below. (always returns 404)
#Path("/acq")
public class Acquisition {
#GET
#Path("ping")
public Response ping(#Context HttpServletRequest req) {
return Response.ok().entity(GenericResponse.OK).build();
}
}
I have also used the standard IDE generated ApplicationConfig.java which has this service as one of its resources.
#javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(os.acquisition.acq.Acquisition.class);
}
}
I have been using a short curl script to call the rest service and have tried every possible combination of #Path params and URL configurations to no avail.
#!/bin/bash
curl -v -X GET http://localhost:8080/acq-1.0/acq/ping
Additionally, when curl -v -X GET http://localhost:8080/acq-1.0/ is called it returns to me the index.html page as I expect.
It seems that I am missing something fundimental here. Any ideas?
#ApplicationPath's value is appended to the resource URI before the individual resource paths. Looks like your curl request is missing the "webresources" portion.