jeudi 16 juillet 2015

Unknown sources error when call a controller founction in my ejb services. EJB3

I want write a RESTful service for my EJB3 function.

My workflow is: entity class -> controller -> controller interface-> logic -> logic interface -> service class.

When I call my getMessages services, I get Error HTTP Status 500.

I found these lines in my glassfish server log:

at com.sun.proxy.$Proxy359.getMessages(Unknown Source) at ir.gharch.services.GharchService.getMessages(GharchService.java:58)`

I imported JAKCSON jar files, and Java EE Web 7 API Library in war source library.

What could be causing this error?

My Entity class is:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ir.gharch.domains;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author zakaria
 */
@Entity
@Table(name = "messages")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Messages.findAll", query = "SELECT m FROM Messages m"),
    @NamedQuery(name = "Messages.findById", query = "SELECT m FROM Messages m WHERE m.id = :id"),
    @NamedQuery(name = "Messages.findByCreatedAt", query = "SELECT m FROM Messages m WHERE m.createdAt = :createdAt"),
    @NamedQuery(name = "Messages.findByUpdatedAt", query = "SELECT m FROM Messages m WHERE m.updatedAt = :updatedAt")})
public class Messages implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Lob
    @Size(max = 65535)
    @Column(name = "content")
    private String content;
    @Basic(optional = false)
    @NotNull
    @Column(name = "created_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
    @Basic(optional = false)
    @NotNull
    @Column(name = "updated_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @ManyToOne(fetch = FetchType.LAZY)
    private Companies companyId;

    public Messages() {
    }

    public Messages(Integer id) {
        this.id = id;
    }

    public Messages(Integer id, Date createdAt, Date updatedAt) {
        this.id = id;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt;
    }

    public Integer getId() {
        return id;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Companies getCompanyId() {
        return companyId;
    }

    public void setCompanyId(Companies companyId) {
        this.companyId = companyId;
    }

    @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 Messages)) {
            return false;
        }
        Messages other = (Messages) 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 "ir.gharch.domains.Messages[ id=" + id + " ]";
    }

}

my controller is:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ir.gharch.controllers;

import ir.gharch.controllerints.MessagesJpaControllerInt;
import ir.gharch.controllers.exceptions.NonexistentEntityException;
import ir.gharch.controllers.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import ir.gharch.domains.Companies;
import ir.gharch.domains.Messages;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;

/**
 *
 * @author zakaria
 */
@Stateless(name="MessagesJpaController")
public class MessagesJpaController implements MessagesJpaControllerInt {

    public MessagesJpaController() {
    }

    public MessagesJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    @PersistenceContext(unitName = "GharchServer-ejbPU")
    private EntityManagerFactory emf = null;

    @Override
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    @Override
    public void create(Messages messages) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Companies companyId = messages.getCompanyId();
            if (companyId != null) {
                companyId = em.getReference(companyId.getClass(), companyId.getId());
                messages.setCompanyId(companyId);
            }
            em.persist(messages);
            if (companyId != null) {
                companyId.getMessagesList().add(messages);
                companyId = em.merge(companyId);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void edit(Messages messages) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Messages persistentMessages = em.find(Messages.class, messages.getId());
            Companies companyIdOld = persistentMessages.getCompanyId();
            Companies companyIdNew = messages.getCompanyId();
            if (companyIdNew != null) {
                companyIdNew = em.getReference(companyIdNew.getClass(), companyIdNew.getId());
                messages.setCompanyId(companyIdNew);
            }
            messages = em.merge(messages);
            if (companyIdOld != null && !companyIdOld.equals(companyIdNew)) {
                companyIdOld.getMessagesList().remove(messages);
                companyIdOld = em.merge(companyIdOld);
            }
            if (companyIdNew != null && !companyIdNew.equals(companyIdOld)) {
                companyIdNew.getMessagesList().add(messages);
                companyIdNew = em.merge(companyIdNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = messages.getId();
                if (findMessages(id) == null) {
                    throw new NonexistentEntityException("The messages with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Messages messages;
            try {
                messages = em.getReference(Messages.class, id);
                messages.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The messages with id " + id + " no longer exists.", enfe);
            }
            Companies companyId = messages.getCompanyId();
            if (companyId != null) {
                companyId.getMessagesList().remove(messages);
                companyId = em.merge(companyId);
            }
            em.remove(messages);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public List<Messages> findMessagesEntities() {
        return findMessagesEntities(true, -1, -1);
    }

    @Override
    public List<Messages> findMessagesEntities(int maxResults, int firstResult) {
        return findMessagesEntities(false, maxResults, firstResult);
    }

    private List<Messages> findMessagesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Messages.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    @Override
    public Messages findMessages(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Messages.class, id);
        } finally {
            em.close();
        }
    }

    @Override
    public int getMessagesCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Messages> rt = cq.from(Messages.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}

controller interfaces:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ir.gharch.controllerints;

import ir.gharch.controllers.exceptions.NonexistentEntityException;
import ir.gharch.controllers.exceptions.RollbackFailureException;
import ir.gharch.domains.Messages;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Local;
import javax.persistence.EntityManager;

/**
 *
 * @author zakaria
 */
@Local
public interface MessagesJpaControllerInt extends Serializable {

    void create(Messages messages) throws RollbackFailureException, Exception;

    void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception;

    void edit(Messages messages) throws NonexistentEntityException, RollbackFailureException, Exception;

    Messages findMessages(Integer id);

    List<Messages> findMessagesEntities();

    List<Messages> findMessagesEntities(int maxResults, int firstResult);

    EntityManager getEntityManager();

    int getMessagesCount();

}

my logic is:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ir.gharch.logics;

import ir.gharch.controllerints.ClientsJpaControllerInt;
import ir.gharch.controllerints.CompaniesJpaControllerInt;
import ir.gharch.controllerints.MessagesJpaControllerInt;
import ir.gharch.domains.Clients;
import ir.gharch.domains.Companies;
import ir.gharch.domains.Messages;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.core.Response;

/**
 *
 * @author zakaria
 */
@Stateless
public class GharchLogics implements GharchLogicsInt {

    @EJB
    MessagesJpaControllerInt messageController;

    @Override
    public Messages getMessages() {

        return (Messages) messageController.getEntityManager().createNamedQuery("Messages.findAll").getSingleResult();

    }


}

my logic interface:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ir.gharch.logics;

import ir.gharch.domains.Clients;
import ir.gharch.domains.Companies;
import ir.gharch.domains.Messages;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.ejb.Local;

/**
 *
 * @author zakaria
 */
@Local
public interface GharchLogicsInt extends Serializable{

    Messages getMessages();

}

and finally, my service code is:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ir.gharch.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import ir.gharch.controllerints.MessagesJpaControllerInt;
import ir.gharch.domains.Messages;
import ir.gharch.logics.GharchLogicsInt;
import javax.ejb.EJB;
import javax.faces.bean.RequestScoped;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

/**
 * REST Web Service
 *
 * @author zakaria
 */
@Path("/v1")
@RequestScoped
public class GharchService {

    @Context
    private UriInfo context;

    @EJB
    private GharchLogicsInt logic;
    @EJB
    private MessagesJpaControllerInt cjc;

    protected ObjectMapper mapper;


    /**
     * Creates a new instance of GharchService
     */
    public GharchService() {
        mapper = new ObjectMapper();
    }



    @GET
    @Path("getmessage")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getMessages() {
        //TODO return proper representation object

        Messages msgs = logic.getMessages();

        if ( msgs != null ) {
            return Response.ok( msgs ).build();
        } else {
            return Response.status( Status.NOT_FOUND ).build();
        } 
    }


}

Aucun commentaire:

Enregistrer un commentaire