package adios.interceptor;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import adios.model.Ingredient4Recipe;
import adios.model.Tag;
import adios.model.User;
import adios.model.UserRole;
import adios.service.IngredientService;
import adios.service.TagService;
import adios.service.UserService;
import org.springframework.web.servlet.ModelAndView;
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter{
private static final Log Log = LogFactory.getLog(UserRole.class);
private static final String loginUser = "LOGGEDIN_USER";
@Autowired
private TagService tagService;
@Autowired
private IngredientService ingredientService;
//before the actual handler will be executed
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception
{
String uri = request.getRequestURI();
User userData = (User) request.getSession().getAttribute(loginUser);
if(uri.contains("/user/welcome.html")){
return true;
}
if(uri.contains("user") && userData == null)
{
response.sendRedirect("/adiosMama/login.html");
return false;
}
return true;
}
//after the handler is executed
public void postHandle(
HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView)
throws Exception {
try{
ArrayList<Tag> tagList = tagService.getMostUsedTags();
modelAndView.addObject("searchTags",tagList);
ArrayList<Ingredient4Recipe> ing = ingredientService.getMostUsedIng4Recipe();
modelAndView.addObject("searchIngredients",ing);
}catch(Exception e){
Log.info("ERRRRRRORRRRRRR!!!!!!!");
}
// TypedQuery<Tag> query = em.createQuery(
// "SELECT t.name FROM Tag t GROUP BY t.name ORDER BY COUNT(t.name) desc", Tag.class);
// ArrayList<Tag> a = (ArrayList<Tag>)query.setFirstResult(0).setMaxResults(10).getResultList();
// System.out.println(":::::11111111::::::::::::::::::::::"+a.size());
// TypedQuery<Ingredient> query2 = em.createQuery(
// "SELECT i.name FROM Ingredient i ", Ingredient.class);
// ArrayList<Ingredient> a = (ArrayList<Ingredient>)query2.setFirstResult(0).setMaxResults(10).getResultList();
// System.out.println("::::::2222222:::::::::::::::::::::"+a.size());
}
}