/java/

AngularJS – Example App - Part 1 Beckend. Java EE CORS Filter

2014-06-29 10:49:17

This is very simple example of REST. I use it in my sandbox project called "Louis Btbw". Louis Btbw is frontend application base on AngularJS.

Only one thing here is interesting - CORS Filter. If you deploy your frontend and backend applications on different servers, you have to use something like CORSFilter.

package pl.btbw.core;

import org.apache.log4j.Logger;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    private static Logger LOG = Logger.getLogger(CORSFilter.class);

    @Override
    public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext cres) throws IOException {
        cres.getHeaders().add("Access-Control-Allow-Origin", "*");
        cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
        cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        cres.getHeaders().add("Access-Control-Max-Age", "1209600");
    }

}

PostController.java```package pl.btbw.web.resources.post;import org.apache.log4j.Logger;import javax.inject.Inject;import javax.ws.rs.*;import javax.ws.rs.core.MediaType;import java.util.ArrayList;import java.util.List;@Path("/posts")public class PostController { private static Logger LOG = Logger.getLogger(PostController.class); @Inject private PostStorage postStorage; @GET @Produces(MediaType.APPLICATION_JSON) public List doList() { return new ArrayList<>(postStorage.getAll().values()); }

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Post doOne(@PathParam("id") long id) {
    return postStorage.getOne(id);
}

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Post create(Post post) {
    LOG.info("Create:" + post);
    return postStorage.add(post);
}

@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
public void update(@PathParam("id") long id, Post post) {
    postStorage.update(post);
}

@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public void delete(@PathParam("id") long id) {
    postStorage.remove(id);
}

}


</post></strong>**PostStorage.java**

package pl.btbw.web.resources.post;

import javax.inject.Singleton; import java.io.Serializable; import java.util.HashMap; import java.util.Map;

@Singleton public class PostStorage implements Serializable {

private Map

posts = new HashMap<>();

public Map<long, post=""> getAll() {
    return posts;
}

public Post add(Post post) {
    posts.put(post.getId(), post);
    return post;
}

public Post getOne(long id) {
    return posts.get(id);
}

public void remove(long id) {
    posts.remove(id);
}

public void update(Post post) {
    posts.put(post.getId(), post);
}

}


<strong>PostStorageTest</strong>

package pl.btbw.web.resources.post;

import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

public class PostStorageTest {

private PostStorage postStorage;

@Test
public void shouldReturnEmptyMap() {
    postStorage = new PostStorage();
    assertThat(postStorage.getAll()).hasSize(0);
}

@Test
public void shouldReturnMapWithTwoItem() {
    postStorage = new PostStorage();
    postStorage.add(new Post(1, "Lorem1"));
    postStorage.add(new Post(2, "Lorem2"));
    assertThat(postStorage.getAll()).hasSize(2);
}

@Test
public void shouldReturnOneItem() {
    postStorage = new PostStorage();
    Post post = new Post(1, "Lorem1");
    postStorage.add(post);
    postStorage.add(new Post(2, "Lorem2"));
    assertThat(postStorage.getOne(1)).isEqualTo(post);
}

@Test
public void shouldRemoveOneItem() {
    postStorage = new PostStorage();

    postStorage.add(new Post(1, "Lorem1"));
    postStorage.add(new Post(2, "Lorem2"));

    postStorage.remove(1);

    assertThat(postStorage.getAll()).hasSize(1);
}

@Test
public void shouldUpdateItem() {
    String newPostName = "Lorem1.1";

    postStorage = new PostStorage();
    postStorage.add(new Post(1, "Lorem1"));
    postStorage.update(new Post(1, newPostName));
    assertThat(postStorage.getOne(1).getName()).isEqualTo(newPostName);
}

}


<strong>Post.java</strong>

package pl.btbw.web.resources.post;

import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Post {

private long id;
private String name;

public Post(long id, String name) {
    this.id = id;
    this.name = name;
}

public Post() {
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "Post{" +
            "id=" + id +
            ", name='" + name + '\'' +
            '}';
}

}


<strong>pom.xml</strong>

4.0.0 pl.btbw angular 1.0-SNAPSHOT war 1.7 1.7 false app javax javaee-api 7.0 log4j log4j 1.2.15 junit junit-dep 4.11 test org.mockito mockito-core 1.9.5 test org.easytesting fest-assert 1.4 test org.hamcrest hamcrest-core 1.3 test org.hamcrest hamcrest-library 1.3 test ```