11
votes

I am working on Java restful web service. While testing the restful service I am getting the responses correct for GET and DELETE methods but it is not working for POST and PUT methods. Can anyone help me? I have written the following code:

StudentService.java

@Stateless
@Path("students")
public class StudentService extends StudentServiceLocal<Students> {
    @PersistenceContext(unitName = "RestFulAPIPU")
    private EntityManager em;

    public StudentsFacadeREST() {
        super(Students.class);
    }

    @POST
    @Override
    @Consumes({"application/xml", "application/json"})
    public String create(Students entity) {
        return(super.create(entity));
    }

    @PUT
    @Override
    @Consumes({"application/xml", "application/json"})
    public String edit(@PathParam("id") Students entity) {
        return(super.edit(entity));
    }

    @DELETE    
    @Path("{id}")
    public String remove(@PathParam("id") Integer id) {
        return(super.remove(super.find(id)));
    }

    @GET
    @Path("{id}")
    @Produces({"application/xml", "application/json"})
    public Students find(@PathParam("id") Integer id) {
        return super.find(id);
    }

    @GET
    @Override
    @Produces({"application/xml", "application/json"})
    public List<Students> findAll() {
        return super.findAll();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({"application/xml", "application/json"})
    public List<Students> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        return super.findRange(new int[]{from, to});
    }

    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

}

StudentServiceLocal.java

public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public String create(T entity) {
        getEntityManager().persist(entity);
        return "inserted";
    }

    public String edit(T entity) {
           getEntityManager().merge(entity);
        return "Updated";
    }

    public String remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));        
            return "deleted";  
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

Students.java

@Entity
@Table(name = "students")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Students.findAll", query = "SELECT s FROM Students s"),
    @NamedQuery(name = "Students.findByRollno", query = "SELECT s FROM Students s WHERE s.rollno = :rollno"),
    @NamedQuery(name = "Students.findByName", query = "SELECT s FROM Students s WHERE s.name = :name")})
public class Students implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "rollno")
    private Integer rollno;
    @Size(max = 20)
    @Column(name = "name")
    private String name;

    public Students() {
    }

    public Students(Integer rollno) {
        this.rollno = rollno;
    }

    public Integer getRollno() {
        return rollno;
    }

    public void setRollno(Integer rollno) {
        this.rollno = rollno;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (rollno != null ? rollno.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Students)) {
            return false;
        }
        Students other = (Students) object;
        if ((this.rollno == null && other.rollno != null) || (this.rollno != null && !this.rollno.equals(other.rollno))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.ikanksha.rest.entity.Students[ rollno=" + rollno + " ]";
    }

}
3
And how are you testing it? It's a problem with the one who makes the request, not with the service.Esailija
i m using netbeans IDE so there is available tool for testing the restful service.Manohar Bomma
my input is in xml fromate as <students> <name>Manohar</name> <rollno>1</rollno> </students>Manohar Bomma
You need to include an example of how you are testing POSTs and PUTs.Perception
In netbeans IDE there is testing tool when we test the restful service we will get the page on the browser to ask to perform the operations like POST,PUT,DELETE . i doing so after page is loaded in browser i m choosing the POST method from dropdown list and passing the data in xml format but the browser to showing the which media type to choose for PUT and POST methodsManohar Bomma

3 Answers

8
votes

Be sure that you set Content-Type: application/xml in the headers of your request.

I don't know how it is done with NetBeans but it is quite straightforward to do this with RESTClient.

2
votes

My error is

InboundJaxrsResponse{ClientResponse{method=POST, uri="http://localhost:8080/test/mypath", status=415, reason=Unsupported Media Type}}

Adding the following dependency in pom.xml solved my problem:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.22.1</version>
</dependency>

MyModelClass has name and surname properties

@POST
@Path("mypath")
@Consumes(MediaType.APPLICATION_JSON)
public Response convertToObject(MyModelClass modelClass){}

Post like this in the test class.

String entity = "{\"name\":\"My Name\", \"surname\":\"My Surname\"}"

request().post(Entity.json(entity)

if you POST or PUT some data please register JacksonProvider and JacksonFeature

class TestRestApplication extends ResourceConfig {

    public TestRestApplication() {
        packages(true, "com.your_app_package");
        register(JacksonProvider.class);
        register(JacksonFeature.class);
        property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true");
    }

}
0
votes

I was having this very same issue just now...
My solution was to remove the constructor with parameters.
In your case: remove

public Students(Integer rollno) {
    this.rollno = rollno;
}