sexta-feira, 23 de abril de 2010

MotoristaCadBean

package agape.agfrota.view;

import agape.agfrota.controller.MotoristaController;
import agape.agfrota.exception.AgFrotaException;
import agape.agfrota.utils.AgUtils;
import agape.agfrota.view.data.MotoristaData;
import java.text.ParseException;

public class MotoristaCadBean{
private MotoristaData motoristaData;
public MotoristaCadBean(){
motoristaData = new MotoristaData();
}

public MotoristaData getMotoristaData() {
return motoristaData;
}

public void setDataObject(MotoristaData MotoristaData) {
this.motoristaData = MotoristaData;
}

public String clickSalvar(){
try {
MotoristaController controller = new MotoristaController();
controller.insert(motoristaData.getMotoristaTO());
MotoristaConBean bean = (MotoristaConBean)AgUtils.getSessionObject("motoristaConBean");
bean.setPesquisaTxt(motoristaData.getNomeTxt());
motoristaData = new MotoristaData();
bean.clickPesquisar();

return "motorista_form_con";
} catch (ParseException ex) {
AgUtils.setAlerta("Data com formato inválido", 'e');
return "";
}catch (Exception ex) {
if(ex instanceof AgFrotaException){
AgUtils.setAlerta(ex.getMessage(), 'i');
}else{
AgUtils.setAlerta(ex.getMessage(), 'e');
}
return "";
}
}

public String clickVoltar(){
return "motorista_form_con";
}
}

ConnectionFactory

package agape.agfrota.db;

import java.sql.Connection;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectionFactory {

public static Connection getConnection() throws Exception {
try {
InitialContext initCtx = new InitialContext();
DataSource ds = (DataSource) initCtx.lookup("java:/comp/env/jdbc/conexao");
return ds.getConnection();
} catch (NamingException ex) {
throw ex;
}


}
}

MotoristaController

agfrota.model.DAO.MotoristaDAO;
import agape.agfrota.model.TO.MotoristaTO;
import agape.agfrota.model.TO.UsuarioTO;
import agape.agfrota.utils.AgUtils;
import java.util.List;
import javax.faces.model.SelectItem;
import org.brazilutils.br.cpfcnpj.CpfCnpj;
import org.brazilutils.validation.ValidationException;

public class MotoristaController {
private MotoristaDAO motoristaDAO;
private int codCliente;

public MotoristaController(){
try {
motoristaDAO = new MotoristaDAO();
codCliente = ((UsuarioTO) AgUtils.getSessionObject("usuarioSessao")).getCodCliente();
} catch (Exception ex) {
if(ex instanceof ValidationException ){
AgUtils.setAlerta("CPF inválido!", 'i');
}else{
AgUtils.setAlerta("Erro ao conectar ao Banco de Dados", 'e');
}
}
}

public void insert(MotoristaTO motoristaTO) throws Exception{
try {
verificaDados(motoristaTO);
motoristaDAO.insert(motoristaTO);
AgUtils.setAlerta("Motorista inserido com sucesso!", 's');

}catch (Exception ex){

throw ex;
}
}

public void update(MotoristaTO motoristaTO)throws Exception{
try {
verificaDados(motoristaTO);
motoristaDAO.update(motoristaTO);
AgUtils.setAlerta("Motorista alterado com sucesso!", 's');
}catch (Exception ex){
throw ex;
}
}

public void delete(int codigo){
try {
motoristaDAO.delete(codigo, codCliente);
AgUtils.setAlerta("Motorista removido com sucesso!", 's');
} catch (Exception ex) {
AgUtils.setAlerta(ex.getMessage(), 'i');
}
}

public Object getObject(int codigo){
try {
return motoristaDAO.getByPK(codigo, codCliente);
} catch (Exception ex) {
AgUtils.setAlerta(ex.getMessage(), 'i');
return null;
}
}

public List getListMotorista(){
try {
return motoristaDAO.getListMotorista(codCliente);
} catch (Exception ex) {
AgUtils.setAlerta(ex.getMessage(), 'i');
return null;
}
}

public List getAll() throws Exception{
return motoristaDAO.getAll(codCliente);
}

public List getByNome(String nome) throws Exception{
return motoristaDAO.getByNome(nome, codCliente);
}

public List getCodNome() throws Exception{
return motoristaDAO.getCodNome(codCliente);
}


private void verificaDados(MotoristaTO motoristaTO) throws AgFrotaException{
CpfCnpj cpf = new CpfCnpj(motoristaTO.getCpf());
if(!cpf.isValid()){
throw new AgFrotaException("CPF Inválido!");
}
}
}

MotoristaDAO

package agape.agfrota.model.DAO;

import agape.agfrota.db.ConnectionFactory;
import agape.agfrota.exception.AgFrotaException;
import java.util.*;
import java.sql.*;
import agape.agfrota.model.TO.MotoristaTO;
import agape.agfrota.utils.AgUtils;
import javax.faces.model.SelectItem;

public class MotoristaDAO {

public Integer getNextCountCodigo(int codCliente) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql = "select coalesce(max(mot_codigo),0) as quant from agfrota.tb_mot_motorista " +
"where agc_codigo = ?";
pStmt = con.prepareStatement(sql);
pStmt.setInt(1, codCliente);
rs = pStmt.executeQuery();
rs.next();
return rs.getInt("quant") + 1;
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pStmt.close();
con.close();
} catch (Exception e) {
}
}
}

public void insert(MotoristaTO motoristaTO) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
try {
String sql = "insert into agfrota.tb_mot_motorista ( mot_codigo, agc_codigo, mot_nome, " +
"mot_sexo, mot_dt_aniversario, mot_estado_civil, mot_logradouro, " +
"mot_numero, mot_bairro, mot_cep, mot_complemento, mot_uf, " +
"mot_municipio, mot_telefone, mot_cel1, mot_cel2, mot_cpf, " +
"mot_cnh, mot_uf_cnh, mot_cat_cnh, mot_pon_cnh, mot_dt_emissao_cnh, " +
"mot_dt_primeira_cnh, mot_foto, mot_situacao )" +
"values ( ? , ? , upper(?) , upper(?) , ? , upper(?) , upper(?) , upper(?) , " +
"upper(?) , upper(?) , upper(?) , upper(?) , upper(?) , ? , ? , ? , ? , ? , ? , upper(?) , " +
"? , ? , ? , ? , ? )";

pStmt = con.prepareStatement(sql);

pStmt.setInt(1, getNextCountCodigo(motoristaTO.getCodCliente()));
pStmt.setInt(2, motoristaTO.getCodCliente());
pStmt.setString(3, motoristaTO.getNome());
pStmt.setString(4, String.valueOf(motoristaTO.getSexo()));
pStmt.setDate(5, new java.sql.Date(motoristaTO.getDtaniversario().getTime()));
pStmt.setString(6, String.valueOf(motoristaTO.getEstadoCivil()));
pStmt.setString(7, motoristaTO.getLogradouro());
pStmt.setString(8, motoristaTO.getNumero());
pStmt.setString(9, motoristaTO.getBairro());
pStmt.setString(10, motoristaTO.getCep());
pStmt.setString(11, motoristaTO.getComplemento());
pStmt.setString(12, motoristaTO.getUf());
pStmt.setString(13, motoristaTO.getMunicipio());
pStmt.setString(14, motoristaTO.getTelefone());
pStmt.setString(15, motoristaTO.getCel1());
pStmt.setString(16, motoristaTO.getCel2());
pStmt.setString(17, motoristaTO.getCpf());
pStmt.setString(18, motoristaTO.getCnh());
pStmt.setString(19, motoristaTO.getUf_cnh());
pStmt.setString(20, motoristaTO.getCat_cnh());
pStmt.setInt(21, motoristaTO.getPon_cnh());
pStmt.setDate(22, new java.sql.Date(motoristaTO.getDt_emissao_cnh().getTime()));
pStmt.setDate(23, new java.sql.Date(motoristaTO.getDt_primeira_cnh().getTime()));
pStmt.setBytes(24, motoristaTO.getFoto());
pStmt.setString(25, String.valueOf(motoristaTO.getSituacao()));
pStmt.execute();
con.commit();
} catch (SQLException e) {
con.rollback();
if (e.getSQLState().equals("23505")) {
String key = AgUtils.getMessageErrorKey(e.getMessage());
if (key.equals("u_cpf_motorista")) {
throw new AgFrotaException("Já existe um motorista com o CPF " + motoristaTO.getCpf().toUpperCase() + " cadastrado.");
}
if (key.equals("u_cnh_motorista ")) {
throw new AgFrotaException("Já existe um motorista com a CNH " + motoristaTO.getCnh().toUpperCase() + " cadastrado.");
}
}
} catch (Exception e) {
con.rollback();
throw e;
} finally {
try {
pStmt.close();
con.close();
} catch (Exception e) {
}
}
}

public void update(MotoristaTO motoristaTO) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
try {
String sql = "update agfrota.tb_mot_motorista " +
"set mot_nome = upper(?) , mot_sexo = upper(?) , mot_dt_aniversario = ? , " +
"mot_estado_civil = upper(?) , mot_logradouro = upper(?) , mot_numero = ? , " +
"mot_bairro = upper(?) , mot_cep = ? , mot_complemento = upper(?) , " +
"mot_uf = upper(?) , mot_municipio = upper(?) , mot_telefone = ? , " +
"mot_cel1 = ? , mot_cel2 = ? , mot_cpf = ? , mot_cnh = ? , mot_uf_cnh = upper(?) , " +
"mot_cat_cnh = upper(?) , mot_pon_cnh = ? , mot_dt_emissao_cnh = ? , " +
"mot_dt_primeira_cnh = ? , mot_foto = ? , mot_situacao = upper(?) " +
"where mot_codigo = ? and agc_codigo = ?";

pStmt = con.prepareStatement(sql);

pStmt.setString(1, motoristaTO.getNome());
pStmt.setString(2, String.valueOf(motoristaTO.getSexo()));
pStmt.setDate(3, new java.sql.Date(motoristaTO.getDtaniversario().getTime()));
pStmt.setString(4, String.valueOf(motoristaTO.getEstadoCivil()));
pStmt.setString(5, motoristaTO.getLogradouro());
pStmt.setString(6, motoristaTO.getNumero());
pStmt.setString(7, motoristaTO.getBairro());
pStmt.setString(8, motoristaTO.getCep());
pStmt.setString(9, motoristaTO.getComplemento());
pStmt.setString(10, motoristaTO.getUf());
pStmt.setString(11, motoristaTO.getMunicipio());
pStmt.setString(12, motoristaTO.getTelefone());
pStmt.setString(13, motoristaTO.getCel1());
pStmt.setString(14, motoristaTO.getCel2());
pStmt.setString(15, motoristaTO.getCpf());
pStmt.setString(16, motoristaTO.getCnh());
pStmt.setString(17, motoristaTO.getUf_cnh());
pStmt.setString(18, motoristaTO.getCat_cnh());
pStmt.setInt(19, motoristaTO.getPon_cnh());
pStmt.setDate(20, new java.sql.Date(motoristaTO.getDt_emissao_cnh().getTime()));
pStmt.setDate(21, new java.sql.Date(motoristaTO.getDt_primeira_cnh().getTime()));
pStmt.setBytes(22, motoristaTO.getFoto());
pStmt.setString(23, String.valueOf(motoristaTO.getSituacao()));
pStmt.setInt(24, motoristaTO.getCodigo());
pStmt.setInt(25, motoristaTO.getCodCliente());
pStmt.execute();
con.commit();
} catch (SQLException e) {
con.rollback();
if (e.getSQLState().equals("23505")) {
String key = AgUtils.getMessageErrorKey(e.getMessage());
if (key.equals("u_cpf_motorista")) {
throw new AgFrotaException("Já existe um motorista com o CPF " + motoristaTO.getCpf().toUpperCase() + " cadastrado.");
}
if (key.equals("u_cnh_motorista ")) {
throw new AgFrotaException("Já existe um motorista com a CNH " + motoristaTO.getCnh().toUpperCase() + " cadastrado.");
}
}
} catch (Exception e) {
con.rollback();
throw e;
} finally {
try {
pStmt.close();
con.close();
} catch (Exception e) {
}
}
}

public void delete(int codMotorista, int codCliente) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
try {
String sql = "delete from agfrota.tb_mot_motorista " +
"where mot_codigo = ? and agc_codigo = ?";

pStmt = con.prepareStatement(sql);
pStmt.setInt(1, codMotorista);
pStmt.setInt(2, codCliente);
pStmt.execute();
con.commit();
} catch (SQLException e) {
con.rollback();
//throw new AgFrotaException(e.getSQLState());
if (e.getSQLState().equals("23503")) {
throw new AgFrotaException("Esse motorista está sendo usado como fonte de dados no cadastro de abastecimento e/ou manutenção. Por esse motivo ele não será excluido, mas o mesmo pode ser desativado.");
}
} catch (Exception e) {
con.rollback();
throw e;
} finally {
try {
pStmt.close();
con.close();
} catch (Exception e) {
}
}
}

private List resultSetToObjectTransfer(ResultSet rs) throws Exception {
List objs = new ArrayList();
while (rs.next()) {
MotoristaTO motoristaTO = new MotoristaTO();
motoristaTO.setCodigo(rs.getInt("mot_codigo"));
motoristaTO.setNome(rs.getString("mot_nome"));
motoristaTO.setCpf(rs.getString("mot_cpf"));
motoristaTO.setSituacao(rs.getString("mot_situacao").charAt(0));
objs.add(motoristaTO);
}
return objs;
}

private List getAllCodNome(ResultSet rs) throws Exception {
List objs = new ArrayList();
while (rs.next()) {
SelectItem si = new SelectItem(rs.getInt("mot_codigo"), rs.getString("mot_nome"));
objs.add(si);
}
return objs;
}

private MotoristaTO getObject(ResultSet rs) throws Exception {

MotoristaTO motoristaTO = new MotoristaTO();

if (rs.next()) {
motoristaTO.setCodigo(rs.getInt("mot_codigo"));
motoristaTO.setCodCliente(rs.getInt("agc_codigo"));
motoristaTO.setNome(rs.getString("mot_nome"));
motoristaTO.setSexo(rs.getString("mot_sexo").charAt(0));
motoristaTO.setDtaniversario(rs.getDate("mot_dt_aniversario"));
motoristaTO.setEstadoCivil(rs.getString("mot_estado_civil").charAt(0));
motoristaTO.setLogradouro(rs.getString("mot_logradouro"));
motoristaTO.setNumero(rs.getString("mot_numero"));
motoristaTO.setBairro(rs.getString("mot_bairro"));
motoristaTO.setCep(rs.getString("mot_cep"));
motoristaTO.setComplemento(rs.getString("mot_complemento"));
motoristaTO.setUf(rs.getString("mot_uf"));
motoristaTO.setMunicipio(rs.getString("mot_municipio"));
motoristaTO.setTelefone(rs.getString("mot_telefone"));
motoristaTO.setCel1(rs.getString("mot_cel1"));
motoristaTO.setCel2(rs.getString("mot_cel2"));
motoristaTO.setCpf(rs.getString("mot_cpf"));
motoristaTO.setCnh(rs.getString("mot_cnh"));
motoristaTO.setUf_cnh(rs.getString("mot_uf_cnh"));
motoristaTO.setCat_cnh(rs.getString("mot_cat_cnh"));
motoristaTO.setPon_cnh(rs.getInt("mot_pon_cnh"));
motoristaTO.setDt_emissao_cnh(rs.getDate("mot_dt_emissao_cnh"));
motoristaTO.setDt_primeira_cnh(rs.getDate("mot_dt_primeira_cnh"));
motoristaTO.setFoto(rs.getBytes("mot_foto"));
motoristaTO.setSituacao(rs.getString("mot_situacao").charAt(0));
}
return motoristaTO;
}

public List getAll(int codCliente) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql = "select mot_codigo, mot_nome, mot_cpf, mot_situacao from agfrota.tb_mot_motorista m " +
"where m.agc_codigo = ? order by mot_nome ";
pStmt = con.prepareStatement(sql);
pStmt.setInt(1, codCliente);
rs = pStmt.executeQuery();
List list = resultSetToObjectTransfer(rs);
return list;
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pStmt.close();
con.close();
} catch (Exception e) {
}
}
}

public MotoristaTO getByPK(int codMotorista, int CodCliente) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql = "select * from agfrota.tb_mot_motorista " +
"where mot_codigo = ? and agc_codigo = ?";
pStmt = con.prepareStatement(sql);
pStmt.setInt(1, codMotorista);
pStmt.setInt(2, CodCliente);
rs = pStmt.executeQuery();
return getObject(rs);
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pStmt.close();
con.close();
} catch (Exception e) {
}
}
}

public List getByNome(String nome, int CodCliente) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql = "select * from agfrota.tb_mot_motorista " +
"where agc_codigo = ? and upper(mot_nome) like upper(?) ";

pStmt = con.prepareStatement(sql);
pStmt.setInt(1, CodCliente);
pStmt.setObject(2, '%' + nome + '%');

rs = pStmt.executeQuery();
return resultSetToObjectTransfer(rs);
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pStmt.close();
con.close();
} catch (Exception e) {
}
}
}

public List getCodNome(int codCliente) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql = "select mot_codigo, mot_nome from agfrota.tb_mot_motorista where agc_codigo = ?";
pStmt = con.prepareStatement(sql);
pStmt.setInt(1, codCliente);
rs = pStmt.executeQuery();

return getAllCodNome(rs);
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pStmt.close();
con.close();
} catch (Exception e) {
throw e;
}
}
}

public List getListMotorista(int codCliente) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql = "select mot_codigo, mot_nome " +
"from agfrota.tb_mot_motorista " +
"where agc_codigo = ?";

pStmt = con.prepareStatement(sql);

pStmt.setInt(1, codCliente);
rs = pStmt.executeQuery();
return getList(rs);
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pStmt.close();
con.close();
} catch (Exception e) {
throw e;
}

}
}


public List getListMotoristaViagem(int codCliente , int codMotorista) throws Exception {
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
String sql = "select mot_codigo, mot_nome " +
"from agfrota.tb_mot_motorista " +
"where agc_codigo = ? and mot_codigo = ?";

pStmt = con.prepareStatement(sql);

pStmt.setInt(1, codCliente);
pStmt.setInt(2, codMotorista);
rs = pStmt.executeQuery();
return getList(rs);
} catch (Exception e) {
throw e;
} finally {
try {
rs.close();
pStmt.close();
con.close();
} catch (Exception e) {
throw e;
}

}
}

private List getList(ResultSet rs) throws Exception {
List objs = new Vector();
objs.add(new SelectItem("-1", "Selecione o Motorista"));
while (rs.next()) {
objs.add(new SelectItem(String.valueOf(rs.getInt("mot_codigo")), rs.getString("mot_nome")));
}
return objs;
}
}

MotoristaTO

package agape.agfrota.model.TO;

import agape.agfrota.utils.AgUtils;
import java.sql.Date;

public class MotoristaTO {
private int codCliente;
private int codigo;
private String nome;
private char sexo;
private Date dtaniversario;
private char estadoCivil;
private String cnh;
private String uf_cnh;
private String cat_cnh;
private int pon_cnh;
private Date dt_emissao_cnh;
private Date dt_primeira_cnh;
private byte[] foto;
private char situacao;

public MotoristaTO(){
codAgCliente = ((UsuarioTO) AgUtils.getSessionObject("usuarioSessao")).getCodAgCliente();
}

public String getCnh() {
return cnh;
}

public void setCnh(String cnh) {
this.cnh = cnh;
}

public int getCodAgCliente() {
return codAgCliente;
}

public void setCodCliente(int codAgCliente) {
this.codAgCliente = codAgCliente;
}

public int getCodigo() {
return codigo;
}

public void setCodigo(int codigo) {
this.codigo = codigo;
}

public Date getDt_emissao_cnh() {
return dt_emissao_cnh;
}

public void setDt_emissao_cnh(Date dt_emissao_cnh) {
this.dt_emissao_cnh = dt_emissao_cnh;
}

public Date getDt_primeira_cnh() {
return dt_primeira_cnh;
}

public void setDt_primeira_cnh(Date dt_primeira_cnh) {
this.dt_primeira_cnh = dt_primeira_cnh;
}

public Date getDtaniversario() {
return dtaniversario;
}

public void setDtaniversario(Date dtaniversario) {
this.dtaniversario = dtaniversario;
}

public char getEstadoCivil() {
return estadoCivil;
}

public void setEstadoCivil(char estadoCivil) {
this.estadoCivil = estadoCivil;
}

public byte[] getFoto() {
return foto;
}

public void setFoto(byte[] foto) {
this.foto = foto;
}

public String getNome() {
return nome;
}

public void setNome(String nome) {
this.nome = nome;
}

public int getPon_cnh() {
return pon_cnh;
}

public void setPon_cnh(int pon_cnh) {
this.pon_cnh = pon_cnh;
}

public char getSexo() {
return sexo;
}

public void setSexo(char sexo) {
this.sexo = sexo;
}

public char getSituacao() {
return situacao;
}

public void setSituacao(char situacao) {
this.situacao = situacao;
}

public String getUf_cnh() {
return uf_cnh;
}

public void setUf_cnh(String uf_cnh) {
this.uf_cnh = uf_cnh;
}

public String getCat_cnh() {
return cat_cnh;
}

public void setCat_cnh(String cat_cnh) {
this.cat_cnh = cat_cnh;
}
}