cimitero.rest.SessionRESTService.java Source code

Java tutorial

Introduction

Here is the source code for cimitero.rest.SessionRESTService.java

Source

/*
 * 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 cimitero.rest;

import cimitero.dto.ItemWrapper;
import cimitero.dto.ResponseDto;
import cimitero.dto.UserDto;
import cimitero.entities.TUser;
import cimitero.persistence.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.hibernate.Session;
import org.jboss.logging.Logger;

/**
 * REST Web Service
 *
 * @author Markus
 */
@Stateless
@Path("/session")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public class SessionRESTService {

    Logger log = Logger.getLogger(SessionRESTService.class);

    @Context
    HttpServletRequest req;

    @Context
    HttpServletResponse resp;

    public SessionRESTService() {

    }

    @GET
    @Path("/user")
    public ResponseDto getCurrentUser() {
        ResponseDto response = new ResponseDto(true);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        TUser user = (TUser) session.get(TUser.class,
                Integer.parseInt(req.getSession().getAttribute("userId").toString()));
        if (user != null) {
            UserDto userDto = new UserDto(user.getId(), user.getUsername(), user.isIsAdmin(),
                    user.getCustomer().getPersonId());
            List<UserDto> results = new ArrayList<UserDto>();
            results.add(userDto);
            response.setItems(new ItemWrapper(results));
        } else {
            response.setOk(false);
            response.addError(1, "current user not found");
        }
        session.getTransaction().commit();
        return response;
    }
}