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>
Related
I have this Cors filter:
public class SimpleCorsFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
System.out.println("here");
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
System.out.println("here2");
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
}
And it seems it doesnt work. HEre is my web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app-context.xml</param-value>
</context-param>
<filter>
<filter-name>SimpleCORSFilter</filter-name>
<filter-class>org.heller.filter.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SimpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
Can someone please give me a poit how to make this filter work? When I tried to request, there is no message ,,here" in console. I saw lot of tutorials, and code seems to be fine. It should be some mistake, which I dont see. Thank you for help.
My web.xml look like:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app-context.xml</param-value>
</context-param>
<filter>
<filter-name>SimpleCORSFilter</filter-name>
<filter-class>org.heller.filter.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SimpleCORSFilter</filter-name>
<servlet-name>app</servlet-name>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
And now it runs! Thank you for help!
This is my filter :-
package com.test.test.apis.filter;
public class AuthenticationFilter implements Filter{
private FilterConfig filterConfig;;
private List<String> excludedApiUrls;
protected ServletContext servContext;
private static final String AUTHENTICATION_HEADER_KEY = "Authorization";
private static final String AUTHENTICATION_HEADER_VALUE_PREFIX = "Bearer "; // with trailing space to separate token
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
String excludePattern = filterConfig.getInitParameter("excludedUrls");
excludedApiUrls = Arrays.asList(excludePattern.split(","));
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {
if (filterConfig == null) return;
HttpServletRequest request = (HttpServletRequest) servletRequest;
if(!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
// filter logic
}else {
filterChain.doFilter(request, servletResponse);
}
}
#Override
public void destroy() {
filterConfig = null;
}
}
CORS Configurration:-
package com.test.test.apis.filter;
public class CORSFilter implements ContainerResponseFilter {
#Override
public ContainerResponse filter(ContainerRequest request,ContainerResponse response) {
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
return response;
}
}
web.xml;-
<filter>
<filter-name>ApiFilter</filter-name>
<filter-class>com.test.test.apis.filter.AuthenticationFilter</filter-class>
<init-param>
<param-name>excludedUrls</param-name>
<param-value>/tb/login/doLogin</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ApiFilter</filter-name>
<servlet-name>api-serlvet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>api-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.test.test.apis.controllers</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.test.test.apis.filter.CORSFilter</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api-serlvet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
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.
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>
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.
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