cristianogro BOM dia !
classes :
usuario.cpntroler
package com.wbotelhos.controller;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import com.wbotelhos.common.TipoPerfil;
import com.wbotelhos.dao.UsuarioDao;
import com.wbotelhos.interceptor.Permissao;
import com.wbotelhos.model.Usuario;
@Resource
@Permissao({TipoPerfil.USUARIO})
@Path("/usuario")
public class UsuarioController {
private Result result;
private UsuarioDao usuarioDao;
public UsuarioController(Result result,
UsuarioDao usuarioDao) {
this.result = result;
this.usuarioDao = usuarioDao;
}
@Get
public void listar() {
int tam = usuarioDao.getUsuarioList().size();
result.include("msg", "[" + tam + "] usuário(s) encontrado(s)...");
}
@Post
@Path("/adicionar")
@Permissao({TipoPerfil.USUARIO})
public void adicionar(Usuario usuario) {
usuario.setId((long) (usuarioDao.getUsuarioList().size() + 1));
usuarioDao.adicionar(usuario);
result.include("msg", "Usuário adicionado com sucesso!");
result.redirectTo(getClass()).listar();
}
@Get
@Path("/remover/{usuario.id}")
@Permissao({TipoPerfil.USUARIO})
public void remover(Usuario usuario) {
usuarioDao.remover(usuario);
result.include("msg", "Usuário removido com sucesso!");
result.redirectTo(getClass()).listar();
}
@Get
@Path("/negado")
public void negado() {
result.include("msg", "Ops! Você não pode fazer isso! (:");
}
}[/code]
usuario dao
[code]package com.wbotelhos.dao;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import br.com.caelum.vraptor.ioc.Component;
//import br.com.caelum.vraptor.ioc.SessionScoped;
import com.wbotelhos.model.Usuario;
import java.util.ArrayList;
import java.util.Collection;
@Component
//@SessionScoped
public class UsuarioDao {
private EntityManager manager;
public UsuarioDao(EntityManager manager) {
this.manager = manager;
}
private Collection<Usuario> usuarioList = new ArrayList<Usuario>();
public void adicionar(Usuario usuario) {
usuarioList.add(usuario);
}
public void remover(Usuario usuario) {
usuarioList.remove(usuario);
}
public Collection<Usuario> getUsuarioList() {
return usuarioList;
}
public void setUsuarioList(Collection<Usuario> usuarioList) {
this.usuarioList = usuarioList;
}
public Usuario login(String email, String senha) throws Exception {
try {
Query query = manager.createQuery("from Usuario u where u.email = :email and u.senha = :senha");
query.setParameter("email", email);
query.setParameter("senha", senha);
return (Usuario) query.getSingleResult();
} catch (NoResultException e) {
throw new Exception("Usuario ou senha incorreta!", e);
} catch (NonUniqueResultException e) {
throw new Exception("Erro! Usuario duplicado.", e);
} catch (Exception e) {
throw new Exception("Nao foi possivel acessar o sistema!", e);
}
}
}
admin controler
[code]
package com.wbotelhos.controller;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import com.wbotelhos.common.TipoPerfil;
import com.wbotelhos.dao.UsuarioDao;
import com.wbotelhos.interceptor.Permissao;
import com.wbotelhos.model.Usuario;
@Resource
@Permissao(TipoPerfil.ADMINISTRADOR)
//@Path("/admin")
public class AdminController {
private Result result;
private UsuarioDao usuarioDao;
public AdminController(Result result,
UsuarioDao usuarioDao) {
this.result = result;
this.usuarioDao = usuarioDao;
}
@Get
@Path("/admin")
public void admin() {
result.include("msg", "Seja bem-vindo ao painel administrativo");
}
@Post
@Path("/adicionar")
@Permissao({TipoPerfil.ADMINISTRADOR})
public void adicionar(Usuario usuario) {
result.include("msg", "Usuário adicionado com sucesso!");
}
@Get
@Permissao({TipoPerfil.ADMINISTRADOR})
public void listar() {
int tam = usuarioDao.getUsuarioList().size();
result.include("msg", "[" + tam + "] usuário(s) encontrado(s)...");
}
@Get
@Path("/negado")
public void negado() {
result.include("msg", "Ops! Você não pode fazer isso! (:");
}
}[/code]
index controller
[code]package com.wbotelhos.controller;
import br.com.caelum.vraptor.Get;
import javax.servlet.http.HttpSession;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
//import com.wbotelhos.model.Usuario;
//import com.wbotelhos.common.TipoPerfil;
@Resource
public class IndexController {
private HttpSession session;
public IndexController(HttpSession session) { //HttpSession
this.session = session;
}
@Get
@Path("/")
public void index() {
//session.setAttribute("user", this.getUsuario());
}
/*
private Usuario getUsuario() {
Usuario entity = new Usuario();
entity.setNome(“Washington Botelho”);
entity.setPerfil(TipoPerfil.USUARIO);
return entity;
}
}[/code]
login controler
package com.wbotelhos.controller;
import static br.com.caelum.vraptor.view.Results.logic;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import com.wbotelhos.dao.UsuarioDao;
import com.wbotelhos.model.Usuario;
import com.wbotelhos.util.SessionUser;
@Resource
public class LoginController {
private Result result;
private UsuarioDao usuarioDao;
private SessionUser sessionUser; // SessionUser
public LoginController(Result result,
UsuarioDao usuarioDao,
SessionUser sessionUser) {
this.result = result;
this.usuarioDao = usuarioDao;
this.sessionUser = sessionUser;
}
@Get
@Path("/login")
public void login() {
}
@Post
@Path("/login")
public void login(Usuario usuario) {
try {
Usuario user = usuarioDao.login(usuario.getEmail(), usuario.getSenha());
sessionUser.setUsuario(user);
result.use(logic()).redirectTo(IndexController.class).index();
} catch (Exception e) {
e.printStackTrace();
result.use(logic()).redirectTo(getClass()).login();
result.include("msg", "SENHA INCORRETA");//***********
}
}
@Get
@Path("/logout")
public void logout() {
sessionUser.setUsuario(null);
result.use(logic()).redirectTo(getClass()).login();
}
}
permissao intecepto
package com.wbotelhos.interceptor;
import static br.com.caelum.vraptor.view.Results.logic;
import java.util.Arrays;
import javax.servlet.http.HttpSession;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.resource.ResourceMethod;
import com.wbotelhos.controller.IndexController;
import com.wbotelhos.controller.UsuarioController;
import com.wbotelhos.model.Usuario;
import com.wbotelhos.common.TipoPerfil;
@Intercepts
@RequestScoped
public class PermissaoInterceptor implements Interceptor {
private Result result;
private HttpSession session;
public PermissaoInterceptor(Result result,
HttpSession session) {
this.result = result;
this.session = session;
}
@Override
@SuppressWarnings({"unchecked", "element-type-mismatch"})
public boolean accepts(ResourceMethod method) {
System.out.print("============PermissaoInterceptor,accepts, IndexController!=========");
return !Arrays.asList(IndexController.class)
.contains(method.getMethod()
.getDeclaringClass());
}
@Override
public void intercept(InterceptorStack stack,
ResourceMethod method,
Object resourceInstance) {
if (isAcessoMetodo(method) && isAcessoController(method)) {
System.out.print("============PermissaoInterceptor,intercept, Interceptor, Stack stack!=========");
stack.next(method, resourceInstance);
} else {
System.out.print("============PermissaoInterceptor,intercept,else Interceptor, Stack stack!=========");
result.use(logic()).redirectTo(UsuarioController.class).negado();
}
}
private Usuario getUser() {
System.out.print("============PermissaoInterceptor,getUser, Atributo User!=========");
return (Usuario) session.getAttribute("user");
}
private boolean isAcessoMetodo(ResourceMethod method) {
Permissao permissaoList = method.getMethod()
.getAnnotation(Permissao.class);
System.out.print("============PermissaoInterceptor,isAcessoMetodo, Se existe permissão anotada. Lista!=========");
return isExistePermissao(permissaoList);
}
private boolean isAcessoController(ResourceMethod method) {
Permissao permissaoList = method.getResource()
.getType()
.getAnnotation(Permissao.class);
System.out.print("============PermissaoInterceptor,isAcessoController, Se existe permissão anotada. Lista!=========");
return isExistePermissao(permissaoList);
}
private boolean isExistePermissao(Permissao permissaoList) {
Usuario user = this.getUser();
if (permissaoList != null) { // Com permissão anotada. Verificar!
for (TipoPerfil perfil : permissaoList.value()) {
if (perfil.equals(user.getPerfil())) {
System.out.print("============PermissaoInterceptor,Com permissão anotada. Verificar!=========");
return true;
}
}
} else { // Sem permissão anotada. Continue!
System.out.print("============PermissaoInterceptor,Sem permissão anotada. Continue!=============");
return true;
}
return false;
}
}
[code]
package com.wbotelhos.interceptor;
import com.wbotelhos.common.TipoPerfil;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME) //Em tempo de execução
public @interface Permissao {
TipoPerfil[] value();
}[/code]
package com.wbotelhos.interceptor;
import static br.com.caelum.vraptor.view.Results.logic;
import java.util.Arrays;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import com.wbotelhos.controller.LoginController;
import com.wbotelhos.util.SessionUser;
@Intercepts
public class LoginInterceptor implements Interceptor {
private Result result;
private SessionUser sessionUser; // chama a classe SessionUser
public LoginInterceptor(Result result,
SessionUser sessionUser) {
this.result = result;
this.sessionUser = sessionUser;
}
@Override
@SuppressWarnings({"unchecked", "element-type-mismatch"})
public boolean accepts(ResourceMethod method) {
System.out.println("==========LoginInterceptor,accepts, sessionUser, Arrays.asList=========");
return !Arrays.asList(LoginController.class)
.contains(method.getMethod()
.getDeclaringClass());
}
@Override
public void intercept(InterceptorStack stack,
ResourceMethod method,
Object resourceInstance) {
if (sessionUser.getUsuario() != null) {
stack.next(method,
resourceInstance);
System.out.println("==========LoginInterceptor,Intercept, sessionUser, Usuario != Null==========");
} else {
System.out.println("==========LoginInterceptor,Intercept, sessionUser, RedirectTo Login Controller========");
result.use(logic())
.redirectTo(LoginController.class)
.login();
}
}
}