Wildfly resteasy javax.ws.rs.NotFoundException - java

i know that this post is duplicate and there are a lot of solutions yet, but i wasn't able to use them to resolve the problem.
I am trying to use spring + wildflyAS + resteasy. I have problems with resteasy integration, here is error which i am getting while trying to access controller:
javax.ws.rs.NotFoundException: Could not find resource for full path: http://localhost:8080/BQP/rest/student/test/1/pass/1
Controller:
#Controller
#RequestMapping(value = "student")
public class StudentController {
#Autowired
StudentService studentService;
public StudentController() {
}
#RequestMapping(value = "/test/{id}/pass/{testId}", method = RequestMethod.GET, produces = "application/json")
public
#ResponseBody
Response getCurrentTest(#PathVariable("id") String id,#PathVariable("testId") String testId){
TestDTO testDTO = studentService.getCurrentTest(id,testId);
return Response.status(200).entity(testDTO).build();
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<display-name>BQP</display-name>
<!--Spring-->
<servlet>
<servlet-name>Spring MVC Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--/Spring-->
<!--RestEASY-->
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.bionic.rest.ApplicationConfiguration</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<!--/RestEASY-->
ApplicationConfiguration:
package com.bionic.rest;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class ApplicationConfiguration extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ApplicationConfiguration() {
singletons.add(new StudentController());
}
#Override
public Set<Class<?>> getClasses() {
return empty;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
Moreover, i can access this controller without /rest in url.

Related

Getting 404 page not found after adding ContextLoaderListener to spring mvc project with primefaces pages

I am new to Spring and trying to make integration between spring and primefaces. I am getting 404 page no found when I run the project on tomcat after adding the ContextLoaderListener and RequestContextListener.
My web.xml file:
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id = "WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>login.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
</web-app>
and this is my faces-config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_3.xsd"
version="2.3">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<navigation-rule>
<display-name>/login.xhtml</display-name>
<from-view-id>/login.xhtml</from-view-id>
</navigation-rule>
<navigation-rule>
<display-name>/login.xhtml</display-name>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>viewRecords</from-outcome>
<to-view-id>view.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
</faces-config>
and following is my controller class:
package com.testtask.nagarro.controller;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.hibernate.annotations.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.testtask.nagarro.forms.LoginForm;
import com.testtask.nagarro.forms.StatementForm;
import com.testtask.nagarro.interfaces.StatementRepository;
import com.testtask.nagarro.interfaces.UserService;
import com.testtask.nagarro.models.Statement;
#Controller
public class NagarroController {
#Autowired
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(value= "/", method=RequestMethod.GET)
public String loginPage() {
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView login() {
ModelAndView model = new ModelAndView();
model.setViewName("login");
return model;
}
#RequestMapping(value="/viewRecords", method = RequestMethod.POST)
public String showHomePage(StatementForm form) {
System.out.println("In view records controller");
List<Statement> records = getUserService().getRecordsByAccountId(form.getAccountId());
return "view";
}
#RequestMapping(method=RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map<String, LoginForm> model) {
String username = "UserName";
String password = "password";
if(result.hasErrors()) {
return "loginform";
}
loginForm = (LoginForm) model.get("loginForm");
if(!loginForm.getUsername().equals(username) || !loginForm.getPassword().equals(password)) {
return "loginForm";
}
model.put("loginForm", loginForm);
return "home";
}
}
I tried to find a solution online but I am confused because most of the examples are using jsps.
please point me to the problem, I am attaching the github link.
Your views are NOT in webapp/WEB-INF folder as you defined in your InternalViewResolver bean.
They are located in webapp folder.

JAX-RS Rest Filter does not invoke

I have an api that needs to implement security.
But the filter is not invoked. my call pass directly to the endpoint...
My Secure interface
#NameBinding
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE,ElementType.METHOD})
public #interface Seguro {}
My Filter
#Seguro
#Provider
#Priority(Priorities.AUTHENTICATION)
public class FiltroAutenticacao implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new NotAuthorizedException("Authorization header precisa ser provido");
}
String token = authorizationHeader.substring("Bearer".length()).trim();
try {
...
} catch (Exception e) {
...
}
}
}
My method that needs to be authenticated.
#Seguro
#GET
#Path("/metodo-teste")
#Produces("application/json")
public Response medotoTeste(#QueryParam("codigo") String codigo){
ModeloTesteTO to = new ModeloTesteTO("codigo enviado foi " + codigo);
return Response.ok(to, MediaType.APPLICATION_JSON).build();
}
Do I need to implement anything else?
My web.xml
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
<param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>br.gov.es.dataci.aprender</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>br.gov.es.dataci.aprender.seguranca.FiltroAutenticacao</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
I am using Jersey 1.17 and glassfish 4
I discovered the problem, following Paul's suggestion of trying to publish the application with Jersey 2 on the glassfish, I discovered incompatibility in glassfish version. Glassfish 4.0 does not support jersey 2, the 4.1.2 version yes. I migrated the server and solved the problem.

Swagger.json is not generated in Jersey + Tomcat8

pom.xml
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.5.7</version>
<exclusions>
<exclusion>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</exclusion>
</exclusions>
</dependency>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>io.swagger.jaxrs.listing,
rs
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Jersey2Config</servlet-name>
<servlet-class>io.swagger.jersey.config.JerseyJaxrsConfig</servlet-class>
<init-param>
<param-name>api.version</param-name>
<param-value>1.0</param-value>
</init-param>
<init-param>
<param-name>swagger.api.title</param-name>
<param-value>Swagger APIzz</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8080/SwaggerExample/webapi</param-value>
</init-param>
<init-param>
<param-name>swagger.pretty.print</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>swagger.scan</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
</web-app>
SwaggerExample is context root
PeopleRestService.java is present inside rs package
#Path( "/people" )
#Api( value = "/", description = "Manage people" )
public class PeopleRestService {
private static PeopleService peopleService;
static{
peopleService = new PeopleService();
}
#Produces( { MediaType.APPLICATION_JSON } )
#GET
#ApiOperation( value = "List all people", notes = "List all people using paging", response = Person.class, responseContainer = "List")
public Collection< Person > getPeople( #ApiParam( value = "Page to fetch", required = true ) #QueryParam( "page") #DefaultValue( "1" ) final int page ) {
System.out.println("inside service........");
return peopleService.getPeople( page, 100 );
}
}
Above code is able get the data via webservice but on accessing swagger.json, it is giving 404
http://localhost:8080/SwaggerExample/webapi/people : is working fine
http://localhost:8080/SwaggerExample/webapi/swagger.json : is giving 404
In web.xml replace
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>io.swagger.jaxrs.listing,
rs
</param-value>
</init-param>
with
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>
services.ConfigApplication
</param-value>
</init-param>
and register class explicitly
class ConfigApplication extends ResourceConfig{
public ConfigApplication(){
register(ApiListingResource.class);
register(SwaggerSerializers.class);
register(PeopleRestService.class);
}
}
If you can see your API on the swagger UI, it mean swagger UI knows where your swagger.json is, in my case I went to the index.html and searched for swagger.json.
I found this code
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "/my-app-name/app/swagger.json"; << this
}
Edit 1:
In newer versions you will find something like
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json", << this
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
I guess you will also have to replace your init-param accordingly so you could access it remotely.
<param-value>http://localhost:8080/SwaggerExample/webapi</param-value>
to a relative path
<param-value>/SwaggerExample/webapi</param-value>

Http 404 Spring java config

Hello i have problem with java config in spring. I was trying to complete it by learning from mutliple tutorials but still i have something wrong. Any clue ?
error
AppConfig.java
package org.spring.mvc.libraryDemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Created by wiktor on 28.12.2015.
*/
#Configuration //adnotacja oznaczajaca plik konfiguracyjny
#EnableWebMvc
#ComponentScan(basePackages = "org.spring.mvc.libraryDemo") //enable skan komponentow
#Import({AppConfig.class}) //na co musi jeszcze uwazac Spring
public class AppConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SpringConfigInit
package org.spring.mvc.libraryDemo.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringConfigInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Controller
package org.spring.mvc.libraryDemo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by wiktor on 28.12.2015.
*/
#Controller
public class HomeController {
#RequestMapping(value="/",method= RequestMethod.GET)
public String sayHello(ModelMap modelMap)
{
modelMap.addAttribute("greeting","witaj");
return "index";
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
With this type of servlet mapping, I think you will find your app at http://localhost:8080/{warfile name}/, not at http://localhost:8080/
You are mixing up two approaches here (as seen is your web.xml):
ContextLoaderListener with /WEB-INF/applicationContext.xml : this means that your spring application will be configured by the xml stuff in applicationContext.xml.
But obviously you want to use the Java Config, that is the beans defined under #Configuration annotated classes. To enable this, one way is to change your web xml for something like this:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>SpringRootConfig</param-value>
</init-param>
</servlet>
AnnotationConfigWebApplicationContext is the key here. That will scan your classpath and take the #Configuration stuff into account.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.spring.mvc.libraryDemo.config.AppConfig</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

When trying to produce a JSON Array with Apache Wink I get WebApplicationException

i'm new to JAX-RS. I'm trying to represent a List to a JSON array:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/getUsersResource/{userId}")
public List<AbstractResource> getUsersResources(#PathParam("userId") final String userId) {
if (userId == null) {
return null;
}
User user = null;
try {
user = userDao.getUserById(Integer.parseInt(userId));
} catch (NumberFormatException nfe) {
user = userDao.getUser(userId);
}
if (user == null) {
return null;
}
return abstractResourceDao.getUsersResources(null, user.userId);
}
When i execute this url i get:
{"exception": {"name": "WebApplicationException"}}
I annotated my AbstractResource class with the #XmlRootElement only and when i change the #Produces annotation parameter to
#Produces(MediaType.APPLICATION_XML)
I get the proper result. Here is my web.xml:
<servlet>
<servlet-name>REST Application</servlet-name>
<servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.balthaser.b3e.rest.RESTApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>REST Client</servlet-name>
<servlet-class>com.balthaser.b3e.rest.client.RESTClient</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST Client</servlet-name>
<url-pattern>/rest/index.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>REST Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Are there any additional requirements when producing JSON Arrays ?
Apache Wink is using json.org and jettison as a Json provider and they can't handle Java List properly.
So you need to configure Wink to use Jackson instead as a Json provider.
Here is the detail.
http://www.ibm.com/developerworks/java/library/wa-aj-jackson/index.html

Categories

Resources