Java tutorial
/* * The MIT License * * Copyright 2016 victor. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.sislivros.persistencia; import io.github.sislivros.entidades.TimeLineEvent; import io.github.sislivros.entidades.Usuario; import io.github.sislivros.enums.TimeLineEventType; import io.github.sislivros.enums.TipoUsuario; import java.io.IOException; import java.net.URISyntaxException; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.codec.digest.DigestUtils; /** * DAO da entidade Usuario * * @author victor */ public class UsuarioBdDao extends GenericBancoDadosDao<Usuario, Integer> { /** * Salva a foto de capa do usuario no diretorio 'img/capa/EmailUsuario' * * @param usuario_id * @param foto * * @return */ public boolean salvarFotoCapa(int usuario_id, String foto) { try { conectar(); String sql = "UPDATE usuario SET foto_capa = ? WHERE id = ?"; PreparedStatement ps = getConnection().prepareStatement(sql); ps.setString(1, foto); ps.setInt(2, usuario_id); return ps.executeUpdate() != 0; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return false; } finally { desconectar(); } } /** * Salva a foto de perfil do usuario no diretoro 'img/perfil/EmailUsuario' * * @param usuario_id * @param foto * * @return */ public boolean salvarFotoPerfil(int usuario_id, String foto) { try { conectar(); String sql = "UPDATE usuario SET foto_perfil = ? WHERE id = ?"; PreparedStatement ps = getConnection().prepareStatement(sql); ps.setString(1, foto); ps.setInt(2, usuario_id); return ps.executeUpdate() != 0; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return false; } finally { desconectar(); } } @Override public Usuario buscarId(Integer id) { try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } String sql = "SELECT * FROM usuario WHERE id = ?"; PreparedStatement ps = getConnection().prepareStatement(sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); rs.next(); Usuario usuario = preencherObjeto(rs); return usuario; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return null; } finally { desconectar(); } } @Override public boolean salvar(Usuario usuario) { try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } String sql = "INSERT INTO usuario (email, senha, apelido, data_nascimento, " + "cidade, estado, nome, foto_perfil, foto_capa, tipo, data_cadastro) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement ps = getConnection().prepareStatement(sql); Date dataNascimento = null; if (usuario.getDataNascimento() != null) { dataNascimento = new Date(usuario.getDataNascimento().getTime()); } ps.setString(1, usuario.getEmail()); ps.setString(2, DigestUtils.sha1Hex(usuario.getSenha())); ps.setString(3, usuario.getApelido()); ps.setDate(4, dataNascimento); ps.setString(5, usuario.getCidade()); ps.setString(6, usuario.getEstado()); ps.setString(7, usuario.getNome()); ps.setString(8, usuario.getFotoPerfil()); ps.setString(9, usuario.getFotoCapa()); ps.setInt(10, usuario.getTipo().id); ps.setTimestamp(11, new Timestamp(System.currentTimeMillis())); ps.executeUpdate(); TimeLineEvent timeLineEvent = new TimeLineEvent(); timeLineEvent.setData(new Timestamp(System.currentTimeMillis())); timeLineEvent.setNome("Criou uma conta"); timeLineEvent.setDescricao("Conta criada com sucesso !"); timeLineEvent.setTipo(TimeLineEventType.CRIACAO_CONTA); timeLineEvent.setEmailUsuario(usuario.getEmail()); TimeLineEventBdDao timeDao = new TimeLineEventBdDao(); timeDao.salvar(timeLineEvent); return true; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return false; } finally { desconectar(); } } @Override public boolean apagar(Usuario usuario) { try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } String sql = "DELETE FROM usuario WHERE email = ?"; PreparedStatement ps = getConnection().prepareStatement(sql); ps.setString(1, usuario.getEmail()); ps.executeUpdate(); return true; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return false; } finally { desconectar(); } } @Override public boolean alterar(Usuario usuario) { try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } String sql = "UPDATE usuario SET email = ?, apelido = ?, data_nascimento = ?, cidade = ?" + ", estado = ?, nome = ?, foto_perfil = ?, foto_capa = ?, tipo = ? WHERE id = ?"; PreparedStatement ps = getConnection().prepareStatement(sql); Date dataNascimento = null; try { dataNascimento = new Date(usuario.getDataNascimento().getTime()); } catch (NullPointerException ex) { } ps.setString(1, usuario.getEmail()); ps.setString(2, usuario.getApelido()); ps.setDate(3, dataNascimento); ps.setString(4, usuario.getCidade()); ps.setString(5, usuario.getEstado()); ps.setString(6, usuario.getNome()); ps.setString(7, usuario.getFotoPerfil()); ps.setString(8, usuario.getFotoCapa()); ps.setInt(9, usuario.getTipo().id); ps.setInt(10, usuario.getId()); ps.executeUpdate(); return true; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return false; } finally { desconectar(); } } /** * Busca na base de dados se h um usuario com o email e senha passados * * @param email * @param senha * * @return */ public Usuario login(String email, String senha) { try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } String sql = "SELECT * FROM usuario WHERE email = ? AND senha = ?"; PreparedStatement ps = getConnection().prepareStatement(sql); ps.setString(1, email); ps.setString(2, senha); ResultSet rs = ps.executeQuery(); if (!rs.next()) { return null; } Usuario usuario = preencherObjeto(rs); return usuario; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return null; } finally { desconectar(); } } public List<Usuario> buscarAtributosNaoExatos(Map<String, String> map) { StringBuilder sql = null; try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } sql = new StringBuilder("SELECT * FROM usuario WHERE "); Set<String> keys = map.keySet(); Iterator<String> it = keys.iterator(); String key; while (it.hasNext()) { key = it.next(); sql.append(key); sql.append(" ilike "); sql.append("'%").append(map.get(key)).append("%'"); if (it.hasNext()) { sql.append(" AND "); } } PreparedStatement ps = getConnection().prepareStatement(sql.toString()); ResultSet rs = ps.executeQuery(); List<Usuario> usuarios = new ArrayList<>(); while (rs.next()) { Usuario usuario = preencherObjeto(rs); usuarios.add(usuario); } return usuarios; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return null; } finally { desconectar(); } } @Override public List<Usuario> buscarAtributos(Map<String, String> map) { StringBuilder sql = null; try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } sql = new StringBuilder("SELECT * FROM usuario WHERE "); Set<String> keys = map.keySet(); Iterator<String> it = keys.iterator(); String key; while (it.hasNext()) { key = it.next(); sql.append(key); sql.append(" = "); sql.append("'").append(map.get(key)).append("'"); if (it.hasNext()) { sql.append(" AND "); } } PreparedStatement ps = getConnection().prepareStatement(sql.toString()); ResultSet rs = ps.executeQuery(); List<Usuario> usuarios = new ArrayList<>(); while (rs.next()) { Usuario usuario = preencherObjeto(rs); usuarios.add(usuario); } return usuarios; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return null; } finally { desconectar(); } } @Override public List<Usuario> listarTodos() { try { if (getConnection() == null || getConnection().isClosed()) { conectar(); } String sql = "SELECT * FROM usuario"; PreparedStatement ps = getConnection().prepareStatement(sql.toString()); ResultSet rs = ps.executeQuery(); List<Usuario> usuarios = new ArrayList<>(); while (rs.next()) { Usuario usuario = preencherObjeto(rs); usuarios.add(usuario); } return usuarios; } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) { ex.printStackTrace(); return null; } finally { desconectar(); } } public Usuario preencherObjeto(ResultSet rs) { Usuario usuario = new Usuario(); try { usuario.setApelido(rs.getString("apelido")); usuario.setDataNascimento(rs.getDate("data_nascimento")); usuario.setCidade(rs.getString("cidade")); usuario.setEstado(rs.getString("estado")); usuario.setEmail(rs.getString("email")); usuario.setFotoPerfil(rs.getString("foto_perfil")); usuario.setFotoCapa(rs.getString("foto_capa")); usuario.setNome(rs.getString("nome")); usuario.setSenha(rs.getString("senha")); usuario.setId(rs.getInt("id")); usuario.setDataCadastro(rs.getTimestamp("data_cadastro")); for (TipoUsuario t : TipoUsuario.values()) { if (t.id == rs.getInt("tipo")) { usuario.setTipo(t); break; } } } catch (SQLException ex) { ex.printStackTrace(); } return usuario; } }