Added support for cross-origin requests (CORS).

This commit is contained in:
Jonathan Bernard 2015-03-02 21:24:58 -06:00
parent 83a0f7275c
commit dc5cb78320
5 changed files with 45 additions and 15 deletions

View File

@ -0,0 +1,12 @@
package com.jdbernard.nlsongs.rest;
import javax.ws.rs.NameBinding;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@NameBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface AllowCors {}

View File

@ -0,0 +1,30 @@
package com.jdbernard.nlsongs.rest;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
@Provider @AllowCors @Priority(Priorities.HEADER_DECORATOR)
public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext reqCtx,
ContainerResponseContext respCtx) {
MultivaluedMap<String, Object> headers = respCtx.getHeaders();
headers.add("Access-Control-Allow-Origin",
reqCtx.getHeaderString("Origin"));
headers.add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS");
headers.add("Access-Control-Allow-Headers",
reqCtx.getHeaderString("Access-Control-Request-Headers"));
}
}

View File

@ -1,12 +0,0 @@
package com.jdbernard.nlsongs.rest
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("v1/ping")
public class PingResource {
@GET
@Produces("text/plain")
public String ping() { return "pong" } }

View File

@ -14,7 +14,7 @@ import javax.ws.rs.core.MediaType;
import com.jdbernard.nlsongs.servlet.NLSongsContext;
import com.jdbernard.nlsongs.model.Service;
@Path("v1/services")
@Path("v1/services") @AllowCors
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public class ServicesResource {

View File

@ -13,12 +13,12 @@ import javax.ws.rs.core.MediaType;
import com.jdbernard.nlsongs.servlet.NLSongsContext;
import com.jdbernard.nlsongs.model.Song;
@Path("v1/songs")
@Path("v1/songs") @AllowCors
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public class SongsResource {
@GET
@GET @AllowCors
public List<Song> getSongs() {
return NLSongsContext.songsDB.findAllSongs(); }