555henny555 555henny555 - 1 month ago 11
Java Question

Error 500 when returning a list of objects from restful webservice

I'm trying to return a list of objects from my restful webservice but I keep getting an error 500, internal server error.

The server encountered an internal error that prevented it from fulfilling this request.

When I create my objects manually, the api works like expected.

@GET
@Path("getAll")
@Produces(MediaType.APPLICATION_XML)
public List<Vak> getAllVakken() {
List<Vak> vakken = new ArrayList<>();
Vak v = new Vak("vak1");
Vak v2 = new Vak("vak2");
vakken.add(v);
vakken.add(v2);

return vakken;
}


When I change the function to the following it doesn't work anymore.

@GET
@Path("getAll")
@Produces(MediaType.APPLICATION_XML)
public List<Vak> getAllVakken() {
List<Vak> vakken = em.createNamedQuery("Vak.getAll").getResultList();
return vakken;
}


When debugging the function,
List<Vak> vakken
gets filled with objects from my database so the named query is working. But when I step over to the next line
return vakken;
it jumps to Method.java line 498
return ma.invoke(obj, args);
.

Vak.java

@NamedQueries({
@NamedQuery(name = "Vak.getAll", query = "select v from Vak v")
})

@Entity
@XmlRootElement
public class Vak implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String naam;

@OneToMany(mappedBy = "vak")
private List<Test> testen = new ArrayList<>();


public Vak() {
}

public Vak(String naam) {
this.naam = naam;
}

@XmlElement
public Long getId() {
return id;
}

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

@XmlElement
public String getNaam() {
return naam;
}

public void setNaam(String naam) {
this.naam = naam;
}

@XmlElement
public List<Test> getTesten() {
return testen;
}

public void setTesten(List<Test> testen) {
this.testen = testen;
}


@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Vak)) {
return false;
}
Vak other = (Vak) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "info.toegepaste.www.entity.Vak[ id=" + id + " ]";
}

}


Test.java

@NamedQueries({
@NamedQuery(name = "Test.getAll", query = "select t from Test t order by t.vak")
})

@Entity
@XmlRootElement
public class Test implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private float behaaldCijfer, maxScore;
private String naam;
@Temporal(TemporalType.DATE)
private GregorianCalendar datum;

@ManyToOne
private Vak vak;

@ManyToOne
private Student student;

public Test() {
}

public Test(String naam, float behaaldCijfer, float maxScore, GregorianCalendar datum, Student student, Vak vak) {
this.maxScore = maxScore;
this.behaaldCijfer = behaaldCijfer;
this.naam = naam;
this.datum = datum;
this.vak = vak;
this.student = student;
}

@XmlElement
public Long getId() {
return id;
}

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

@XmlElement
public float getBehaaldCijfer() {
return behaaldCijfer;
}

public void setBehaaldCijfer(float behaaldCijfer) {
this.behaaldCijfer = behaaldCijfer;
}

@XmlElement
public float getMaxScore() {
return maxScore;
}

public void setMaxScore(float maxScore) {
this.maxScore = maxScore;
}

@XmlElement
public String getNaam() {
return naam;
}

public void setNaam(String naam) {
this.naam = naam;
}

@XmlElement
public GregorianCalendar getDatum() {
return datum;
}

public void setDatum(GregorianCalendar datum) {
this.datum = datum;
}

@XmlElement
public Vak getVak() {
return vak;
}

public void setVak(Vak vak) {
this.vak = vak;
}

@XmlElement
public Student getStudent() {
return student;
}

public void setStudent(Student student) {
this.student = student;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Test)) {
return false;
}
Test other = (Test) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return naam;
}

}


I don't get any errors in my output window from my server client when calling the function. But when I call the function from the client side I get this:

GlassFish output from client side:

Severe: javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1020)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:877)
at org.glassfish.jersey.client.JerseyInvocation.access$800(JerseyInvocation.java:92)
at org.glassfish.jersey.client.JerseyInvocation$3.call(JerseyInvocation.java:722)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:718)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:430)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:321)
at info.toegepaste.www.ManageServlet.getApiVak(ManageServlet.java:148)
at info.toegepaste.www.ManageServlet.processRequest(ManageServlet.java:126)
at info.toegepaste.www.ManageServlet.doPost(ManageServlet.java:179)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Warning: StandardWrapperValve[ManageServlet]: Servlet.service() for servlet ManageServlet threw exception
java.lang.NullPointerException
at info.toegepaste.www.ManageServlet.processRequest(ManageServlet.java:142)
at info.toegepaste.www.ManageServlet.doPost(ManageServlet.java:179)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)


Any help would be very appreciated!

EDIT

I think I found the problem but I don't know how to solve it.

The API works when I remove any related objects from my Class.
So I have my class
Vak
which contains a list of tests. If I manually create a new list where I put my objects of
Vak
in without the references to
Test
it works.

@GET
@Path("getAll")
@Produces(MediaType.APPLICATION_XML)
public List<Vak> getAllVakken() {

List<Vak> vakken1 = em.createNamedQuery("Vak.getAll").getResultList();
List<Vak> vakken2 = new ArrayList<>();

for (Vak vak : vakken1) {
Vak v = new Vak(vak.getNaam());
vakken2.add(v);
}

return vakken2;
}


The code above returns all my objects of Vak in proper XML-layout just as I want.

When I add the line
v.setTesten(vak.getTesten());
I get that error 500.

@GET
@Path("getAll")
@Produces(MediaType.APPLICATION_XML)
public List<Vak> getAllVakken() {

List<Vak> vakken1 = em.createNamedQuery("Vak.getAll").getResultList();
List<Vak> vakken2 = new ArrayList<>();

for (Vak vak : vakken1) {
Vak v = new Vak(vak.getNaam());
v.setTesten(vak.getTesten());
vakken2.add(vak);
}

return vakken2;
}


So the problem must be laying here. Is it something with an infinite loop problem? That Vak holds a list of tests where each Test holds an object of Vak where each Vak again holds a list of tests etc..?

Answer

Finally found the solution after more than 4 days!

There were several problems:

Add following dependency to your pom.xml:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.19</version>
</dependency>

Add register(MoxyXmlFeature.class); in your root Application.

@ApplicationPath("rest")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        super(MultiPartFeature.class);
        register(MoxyXmlFeature.class);
        packages("info.toegepaste.www.ejb"); 
        packages("info.toegepaste.www.entity");
    }
}

My entities were wrong. I removed all @XmlElement from the getters and added @XmlAccessorType(XmlAccessType.FIELD) and @XmlInverseReference(mappedBy="something")

Vak.java

@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Vak implements Serializable {

private static final long serialVersionUID = 1L;
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  private String naam;

  @OneToMany(mappedBy = "vak", cascade = CascadeType.ALL)
  @XmlElement
  @XmlInverseReference(mappedBy = "vak")
  private List<Test> testen = new ArrayList<>();

  public Vak() {
  }

  public Vak(String naam) {
    this.naam = naam;
  }

  //no @XmlElement here!
  public String getNaam() {
    return naam;
  }

  .....
}

Test.java

@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Test implements Serializable {

  private static final long serialVersionUID = 1L;
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  private float behaaldCijfer, maxScore;
  private String naam;
  @Temporal(TemporalType.DATE)
  private GregorianCalendar datum;

  @ManyToOne
  @XmlElement
  private Vak vak;

  @ManyToOne
  @XmlElement
  private Student student;

  public Test() {
  }

  .....
}

I had also a bug with GlassFish after I fixed my code. Have a look here. I fixed this by using Payara.