com.zappy.purefit6.service.UserHistoricFacadeREST.java Source code

Java tutorial

Introduction

Here is the source code for com.zappy.purefit6.service.UserHistoricFacadeREST.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 com.zappy.purefit6.service;

import com.sun.jersey.multipart.FormDataParam;
import com.zappy.purefit6.model.Day;
import com.zappy.purefit6.model.User;
import com.zappy.purefit6.model.UserHistoric;
import com.zappy.purefit6.util.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.QueryHint;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;
import org.joda.time.DateTime;
import org.joda.time.Days;

/**
 *
 * @author gianksp
 */
@Stateless
@Path("history")
public class UserHistoricFacadeREST extends AbstractFacade<UserHistoric> {
    @PersistenceContext(unitName = "com.zappy_Purefit6_war_1.0PU")
    private EntityManager em;

    //Log
    private static Logger log = Logger.getLogger(UserHistoricFacadeREST.class.getName());

    public UserHistoricFacadeREST() {
        super(UserHistoric.class);
    }

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public void create(@FormDataParam("breakfast") Boolean hadBreakfast,
            @FormDataParam("totalFruits") Integer fruits, @FormDataParam("totalSteps") Integer steps,
            @FormDataParam("weight") Float weight, @FormDataParam("idDay") Integer idDay,
            @FormDataParam("idUser") Integer idUser) {

        User user = null;
        UserHistoric previous = null;
        int index = 0;

        user = (User) em.createNamedQuery("User.findByIdUser").setParameter("idUser", idUser).getSingleResult();

        try {
            previous = (UserHistoric) em.createNamedQuery("UserHistoric.findFirstByIdUser")
                    .setParameter("idUser", user).setMaxResults(1).getSingleResult();
            log.info("todays: " + new DateTime() + " previous " + new DateTime(previous.getSubmitted()));
            int days = Days.daysBetween(new DateTime(previous.getSubmitted()), new DateTime()).getDays();
            log.info("total days between: " + days);
            index = days + 1;
        } catch (NoResultException ex) {
            index++;
        }

        UserHistoric historic = new UserHistoric();
        historic.setBreakfast(hadBreakfast);
        historic.setIdDay(index);
        historic.setSteps(steps);
        historic.setSubmitted(new Date());
        historic.setTotalFruits(fruits);
        historic.setWeight(weight);
        historic.setIdUser(user);
        super.create(historic);
    }

    @PUT
    @Path("{id}")
    @Consumes({ "application/xml", "application/json" })
    public void edit(@PathParam("id") Integer id, UserHistoric entity) {
        super.edit(entity);
    }

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

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

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

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

    @GET
    @Path("user/{id}")
    @Produces({ "application/json", "application/xml" })
    public List<UserHistoric> findHistoryForUser(@PathParam("id") Integer id) {

        List<UserHistoric> historics = new ArrayList<UserHistoric>();

        try {
            User user = (User) em.createNamedQuery("User.findByIdUser").setParameter("idUser", id)
                    .getSingleResult();

            historics = em.createNamedQuery("UserHistoric.findByIdUser").setParameter("idUser", user)
                    .setHint(QueryHints.REFRESH, HintValues.TRUE).getResultList();
        } catch (NoResultException ex) {

        } catch (Exception ex) {
            log.log(Level.SEVERE, "Could not request user history for .idUser:" + id, ex);
        }

        return historics;
    }

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

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

}