Commit 94d0c27c by Alonso Moreno Postigo

[EDIT] v0.1

parent ba1776aa
......@@ -2,77 +2,75 @@ package demojsoncrud.beans;
import java.io.Serializable;
/**
*
* @author Alonso
*/
public class PersonaBean implements Serializable {
private String codigo;
private String dni;
private String apellidos;
private String nombres;
private String edad;
private String correo;
private String estado;
private static final long serialVersionUID = 4594333294248399680L;
public PersonaBean() {
}
private String codigo;
private String dni;
private String apellidos;
private String nombres;
private String edad;
private String correo;
private String estado;
public String getCodigo() {
return codigo;
}
public PersonaBean() {
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getCodigo() {
return codigo;
}
public String getDni() {
return dni;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getDni() {
return dni;
}
public String getApellidos() {
return apellidos;
}
public void setDni(String dni) {
this.dni = dni;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getApellidos() {
return apellidos;
}
public String getNombres() {
return nombres;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getNombres() {
return nombres;
}
public String getEdad() {
return edad;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public void setEdad(String edad) {
this.edad = edad;
}
public String getEdad() {
return edad;
}
public String getCorreo() {
return correo;
}
public void setEdad(String edad) {
this.edad = edad;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public String getCorreo() {
return correo;
}
public String getEstado() {
return estado;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
......@@ -4,59 +4,64 @@ import java.io.Serializable;
public class UbigeoBean implements Serializable {
private String codigoDepartamento;
private String nombreDepartamento;
private String codigoProvincia;
private String nombreProvincia;
private String codigoDistrito;
private String nombreDistrito;
public String getCodigoDepartamento() {
return codigoDepartamento;
}
public void setCodigoDepartamento(String codigoDepartamento) {
this.codigoDepartamento = codigoDepartamento;
}
public String getNombreDepartamento() {
return nombreDepartamento;
}
public void setNombreDepartamento(String nombreDepartamento) {
this.nombreDepartamento = nombreDepartamento;
}
public String getCodigoProvincia() {
return codigoProvincia;
}
public void setCodigoProvincia(String codigoProvincia) {
this.codigoProvincia = codigoProvincia;
}
public String getNombreProvincia() {
return nombreProvincia;
}
public void setNombreProvincia(String nombreProvincia) {
this.nombreProvincia = nombreProvincia;
}
public String getCodigoDistrito() {
return codigoDistrito;
}
public void setCodigoDistrito(String codigoDistrito) {
this.codigoDistrito = codigoDistrito;
}
public String getNombreDistrito() {
return nombreDistrito;
}
public void setNombreDistrito(String nombreDistrito) {
this.nombreDistrito = nombreDistrito;
}
private static final long serialVersionUID = 4594333294248399680L;
private String codigoDepartamento;
private String nombreDepartamento;
private String codigoProvincia;
private String nombreProvincia;
private String codigoDistrito;
private String nombreDistrito;
public UbigeoBean() {
}
public String getCodigoDepartamento() {
return codigoDepartamento;
}
public void setCodigoDepartamento(String codigoDepartamento) {
this.codigoDepartamento = codigoDepartamento;
}
public String getNombreDepartamento() {
return nombreDepartamento;
}
public void setNombreDepartamento(String nombreDepartamento) {
this.nombreDepartamento = nombreDepartamento;
}
public String getCodigoProvincia() {
return codigoProvincia;
}
public void setCodigoProvincia(String codigoProvincia) {
this.codigoProvincia = codigoProvincia;
}
public String getNombreProvincia() {
return nombreProvincia;
}
public void setNombreProvincia(String nombreProvincia) {
this.nombreProvincia = nombreProvincia;
}
public String getCodigoDistrito() {
return codigoDistrito;
}
public void setCodigoDistrito(String codigoDistrito) {
this.codigoDistrito = codigoDistrito;
}
public String getNombreDistrito() {
return nombreDistrito;
}
public void setNombreDistrito(String nombreDistrito) {
this.nombreDistrito = nombreDistrito;
}
}
/*
* 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 demojsoncrud.dao;
import demojsoncrud.sqlserverdao.SqlserverDAOFactory;
/**
*
* @author Alonso
*/
public abstract class DAOFactory {
public static final int SQL_SERVER = 1;
public static final int MYSQL = 2;
public static final int SQL_SERVER = 1;
public static final int MYSQL = 2;
public static DAOFactory getDAOFactory(int whichFactory) {
switch (whichFactory) {
case SQL_SERVER:
return new SqlserverDAOFactory();
default:
return null;
}
public static DAOFactory getDAOFactory(int whichFactory) {
switch (whichFactory) {
case SQL_SERVER:
return new SqlserverDAOFactory();
default:
return null;
}
}
public abstract PersonaDAO getPersonaDAO();
public abstract PersonaDAO getPersonaDAO();
public abstract UbigeoDAO getUbigeoDAO();
public abstract UbigeoDAO getUbigeoDAO();
}
package demojsoncrud.dao;
import demojsoncrud.beans.PersonaBean;
import org.json.JSONObject;
public interface PersonaDAO {
public JSONObject listarPersona(String search, String draw, String start, String length);
public JSONObject listarPersona(JSONObject datos);
public JSONObject registrarPersona(JSONObject datos);
......
/*
* 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 demojsoncrud.dao;
import demojsoncrud.beans.UbigeoBean;
import org.json.JSONObject;
/**
*
* @author Alonso
*/
public interface UbigeoDAO {
public JSONObject listarDepartamento();
public JSONObject listarDepartamento();
public JSONObject listarProvincia(JSONObject datos);
public JSONObject listarProvincia(JSONObject datos);
public JSONObject listarDistrito(JSONObject datos);
public JSONObject listarDistrito(JSONObject datos);
}
package demojsoncrud.services;
import demojsoncrud.beans.PersonaBean;
import demojsoncrud.dao.DAOFactory;
import demojsoncrud.dao.PersonaDAO;
import org.json.JSONObject;
public class PersonaService {
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
PersonaDAO service = daoFactory.getPersonaDAO();
public JSONObject listarPersona(String search, String draw, String start, String length) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarPersona(search, draw, start, length);
} catch (Exception e) {
e.getMessage();
}
return jsonReturn;
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
PersonaDAO dao = daoFactory.getPersonaDAO();
public JSONObject listarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = dao.listarPersona(datos);
} catch (Exception e) {
System.out.println("Error PersonaService >> listarPersona >> " + e.getMessage());
}
return jsonReturn;
}
public JSONObject registrarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.registrarPersona(datos);
} catch (Exception e) {
e.getMessage();
}
return jsonReturn;
public JSONObject registrarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = dao.registrarPersona(datos);
} catch (Exception e) {
System.out.println("Error PersonaService >> registrarPersona >> " + e.getMessage());
}
return jsonReturn;
}
public JSONObject editarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.editarPersona(datos);
} catch (Exception e) {
e.getMessage();
}
return jsonReturn;
public JSONObject editarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = dao.editarPersona(datos);
} catch (Exception e) {
System.out.println("Error PersonaService >> editarPersona >> " + e.getMessage());
}
public JSONObject cambiarEstado(JSONObject datos) {
JSONObject respuesta = null;
try {
respuesta = service.cambiarEstado(datos);
} catch (Exception e) {
}
return respuesta;
return jsonReturn;
}
public JSONObject cambiarEstado(JSONObject datos) {
JSONObject respuesta = null;
try {
respuesta = dao.cambiarEstado(datos);
} catch (Exception e) {
System.out.println("Error PersonaService >> cambiarEstado >> " + e.getMessage());
}
return respuesta;
}
}
\ No newline at end of file
}
package demojsoncrud.services;
import demojsoncrud.beans.UbigeoBean;
import demojsoncrud.dao.DAOFactory;
import demojsoncrud.dao.UbigeoDAO;
import org.json.JSONObject;
public class UbigeoService {
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
UbigeoDAO service = daoFactory.getUbigeoDAO();
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
UbigeoDAO dao = daoFactory.getUbigeoDAO();
public JSONObject listarDepartamento() {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarDepartamento();
} catch (Exception e) {
}
return jsonReturn;
public JSONObject listarDepartamento() {
JSONObject jsonReturn = null;
try {
jsonReturn = dao.listarDepartamento();
} catch (Exception e) {
System.out.println("Error UbigeoService >> listarDepartamento >> " + e.getMessage());
}
return jsonReturn;
}
public JSONObject listarProvincia(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarProvincia(datos);
} catch (Exception e) {
}
return jsonReturn;
public JSONObject listarProvincia(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = dao.listarProvincia(datos);
} catch (Exception e) {
System.out.println("Error UbigeoService >> listarProvincia >> " + e.getMessage());
}
return jsonReturn;
}
public JSONObject listarDistrito(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarDistrito(datos);
} catch (Exception e) {
}
return jsonReturn;
public JSONObject listarDistrito(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = dao.listarDistrito(datos);
} catch (Exception e) {
System.out.println("Error UbigeoService >> listarDistrito >> " + e.getMessage());
}
return jsonReturn;
}
}
package demojsoncrud.servlets;
import demojsoncrud.services.PersonaService;
import static demojsoncrud.utilities.CustomHttpServletRequest.getBodyJsonObject;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
......@@ -12,79 +11,79 @@ import org.json.JSONObject;
public class PersonaServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("accion");
switch (param) {
case "listarPersona":
listarPersona(request, response);
break;
case "registrarPersona":
registrarPersona(request, response);
break;
case "editarPersona":
editarPersona(request, response);
break;
case "cambiarEstado":
cambiarEstado(request, response);
break;
default:
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
JSONObject respuesta = new JSONObject();
respuesta
.put("status", false)
.put("message", "No existe la url solicitada.")
.put("data", "");
pw.print(respuesta);
break;
}
}
private void listarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("accion");
switch (param) {
case "listarPersona":
listarPersona(request, response);
break;
case "registrarPersona":
registrarPersona(request, response);
break;
case "editarPersona":
editarPersona(request, response);
break;
case "cambiarEstado":
cambiarEstado(request, response);
break;
default:
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject respuesta = new JSONObject();
respuesta
.put("status", false)
.put("message", "No existe la url solicitada.")
.put("data", "");
pw.print(respuesta);
break;
}
}
String draw = request.getParameter("draw");
String start = request.getParameter("start");
String length = request.getParameter("length");
String search = request.getParameter("search");
private void listarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject json = service.listarPersona(search, draw, start, length);
pw.print(json);
}
String search = request.getParameter("search");
private void registrarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject datos = new JSONObject();
datos = getBodyJsonObject(request);
JSONObject respuesta = service.registrarPersona(datos.getJSONObject("json"));
pw.print(respuesta);
JSONObject datos = new JSONObject();
datos.put("draw", request.getParameter("draw"));
datos.put("start", request.getParameter("start"));
datos.put("length", request.getParameter("length"));
datos.put("search", search);
}
JSONObject json = service.listarPersona(datos);
pw.print(json);
}
private void editarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject datos = new JSONObject();
datos = getBodyJsonObject(request);
JSONObject respuesta = service.editarPersona(datos.getJSONObject("json"));
pw.print(respuesta);
}
private void registrarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.registrarPersona(datos);
pw.print(respuesta);
private void cambiarEstado(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject datos = new JSONObject();
datos = getBodyJsonObject(request);
JSONObject respuesta = service.cambiarEstado(datos.getJSONObject("json"));
System.out.println(respuesta);
pw.print(respuesta);
}
}
private void editarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.editarPersona(datos);
pw.print(respuesta);
}
private void cambiarEstado(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.cambiarEstado(datos);
System.out.println(respuesta);
pw.print(respuesta);
}
}
package demojsoncrud.servlets;
import demojsoncrud.services.UbigeoService;
import static demojsoncrud.utilities.CustomHttpServletRequest.getBodyJsonObject;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
......@@ -12,45 +11,59 @@ import org.json.JSONObject;
public class UbigeoServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("accion");
response.setCharacterEncoding("UTF-8");
if ("listarDepartamento".equals(param)) {
listarDepartamento(request, response);
} else if ("listarProvincia".equals(param)) {
listarProvincia(request, response);
} else if ("listarDistrito".equals(param)) {
listarDistrito(request, response);
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("accion");
response.setCharacterEncoding("UTF-8");
if (null != param) {
switch (param) {
case "listarDepartamento":
listarDepartamento(request, response);
break;
case "listarProvincia":
listarProvincia(request, response);
break;
case "listarDistrito":
listarDistrito(request, response);
break;
default:
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
JSONObject respuesta = new JSONObject();
respuesta
.put("status", false)
.put("message", "No existe la url solicitada.")
.put("data", "");
pw.print(respuesta);
break;
}
}
}
private void listarDepartamento(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService();
JSONObject json = service.listarDepartamento();
pw.print(json);
}
private void listarDepartamento(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService();
JSONObject json = service.listarDepartamento();
pw.print(json);
}
private void listarProvincia(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService();
JSONObject datos = new JSONObject();
datos = getBodyJsonObject(request);
JSONObject respuesta = service.listarProvincia(datos.getJSONObject("json"));
pw.print(respuesta);
}
private void listarProvincia(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService();
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.listarProvincia(datos);
pw.print(respuesta);
}
private void listarDistrito(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService();
JSONObject datos = new JSONObject();
datos = getBodyJsonObject(request);
JSONObject respuesta = service.listarDistrito(datos.getJSONObject("json"));
pw.print(respuesta);
}
private void listarDistrito(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService();
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.listarDistrito(datos);
pw.print(respuesta);
}
}
......@@ -8,275 +8,284 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PersonaSqlserverDAO implements PersonaDAO {
@Override
public JSONObject listarPersona(String search, String draw, String start, String length) {
JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray();
@Override
public JSONObject listarPersona(JSONObject datos) {
JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray();
PreparedStatement psListarPersona = null;
ResultSet rsListarPersona = null;
Connection connection = null;
PreparedStatement psListarPersona = null, psCantidadPersonas = null;
ResultSet rsListarPersona = null, rsCantidadPersonas = null;
Connection connection = null;
String base = "demojsoncrud";
String condicion = "";
String condiciones = " (a.nombres like '%" + search + "%' or a.apellidos like '%" + search + "%') ";
String base = "demojsoncrud";
String condicion = "";
int numeroFilas = Integer.parseInt(start) + 1; //Contador para el numero de filas a listar
int cantidadPersonas = 0;
int numeroFilas = Integer.parseInt(datos.getString("start")) + 1; //Contador para el numero de filas a listar
int cantidadPersonas = 1;
if (!search.equals("")) {
condicion = " and " + condiciones;
}
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select top " + length + " "
+ "a.codigo, "
+ "a.dni, "
+ "a.apellidos, "
+ "a.nombres, "
+ "a.edad, "
+ "a.correo, "
+ "a.estado "
+ "from persona a "
+ "where a.codigo not in (select top " + start + " b.codigo from persona b order by 1 desc) "
+ condicion + " "
+ "order by 1 desc";
psListarPersona = connection.prepareStatement(sql);
rsListarPersona = psListarPersona.executeQuery();
while (rsListarPersona.next()) {
PersonaBean personaBean = new PersonaBean();
int c = 1; //Contador para las columnas
personaBean.setCodigo(rsListarPersona.getString(c++));
personaBean.setDni(rsListarPersona.getString(c++));
personaBean.setApellidos(rsListarPersona.getString(c++));
personaBean.setNombres(rsListarPersona.getString(c++));
personaBean.setEdad(rsListarPersona.getString(c++));
personaBean.setCorreo(rsListarPersona.getString(c++));
personaBean.setEstado(rsListarPersona.getString(c++));
JSONObject obj = new JSONObject(personaBean);
data.put(obj);
}
if (!search.equals("")) {
condicion = " where " + condiciones;
}
String sqlCantidadPersonas = "select count(1) as cantidadPersonas from persona a " + condicion;
PreparedStatement psCantidadPersonas = connection.prepareStatement(sqlCantidadPersonas);
ResultSet rsCantidadPersonas = psCantidadPersonas.executeQuery();
rsCantidadPersonas.next();
cantidadPersonas = rsCantidadPersonas.getInt("cantidadPersonas");
jsonReturn.put("data", data);
jsonReturn.put("recordsFiltered", cantidadPersonas);
jsonReturn.put("recordsTotal", cantidadPersonas);
jsonReturn.put("draw", draw);
} catch (SQLException | JSONException e) {
jsonReturn.put("Error", "Error -> " + e.getMessage());
} finally {
try {
if (rsListarPersona != null) {
rsListarPersona.close();
}
if (psListarPersona != null) {
psListarPersona.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
jsonReturn.put("Error", "Error inesperado -> " + e.getMessage() + " [" + e.getErrorCode() + "]");
}
}
return jsonReturn;
if (!datos.getString("search").equals("")) {
condicion = " and (a.nombres like '%" + datos.getString("search") + "%' or a.apellidos like '%" + datos.getString("search") + "%') ";
}
@Override
public JSONObject registrarPersona(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = new JSONObject();
int resultDni = 0;
int resultPersona = 0;
String base = "demojsoncrud";
PreparedStatement psInsertarPersona = null;
Connection connection = null;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sqlGetDni = "select count(1) dni from persona where dni = ?";
PreparedStatement psGetDni = connection.prepareStatement(sqlGetDni);
psGetDni.setString(1, datos.getString("dni"));
ResultSet rsGetDni = psGetDni.executeQuery();
rsGetDni.next();
resultDni = rsGetDni.getInt("dni");
if (resultDni == 0) {
String sql
= "insert into persona (dni, apellidos, nombres, edad, correo, estado) values "
+ "(?,RTRIM(UPPER(?)),RTRIM(UPPER(?)),?,RTRIM(UPPER(?)),1)";
int c = 1; //contador para las columnas
psInsertarPersona = connection.prepareStatement(sql);
psInsertarPersona.setString(c++, datos.getString("dni"));
psInsertarPersona.setString(c++, datos.getString("apellidos"));
psInsertarPersona.setString(c++, datos.getString("nombres"));
psInsertarPersona.setString(c++, datos.getString("edad"));
psInsertarPersona.setString(c++, datos.getString("correo"));
resultPersona = psInsertarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Registro correcto!");
response.setStatus(true);
} else {
response.setMessage("Error al registrar");
response.setStatus(false); // ERROR
}
} else {
response.setMessage("El documento ya existe en mi base de datos. Prueba otro.");
response.setStatus(false); // DNI REPETIDO
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (connection != null) {
connection.close();
}
if (psInsertarPersona != null) {
psInsertarPersona.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
}
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select top " + datos.getString("length") + " "
+ "a.codigo, "
+ "a.dni, "
+ "a.apellidos, "
+ "a.nombres, "
+ "a.edad, "
+ "a.correo, "
+ "a.estado "
+ "from persona a "
+ "where a.codigo not in (select top " + datos.getString("start") + " b.codigo from persona b order by 1 desc) "
+ condicion + " "
+ "order by 1 desc";
System.out.println(sql);
psListarPersona = connection.prepareStatement(sql);
rsListarPersona = psListarPersona.executeQuery();
while (rsListarPersona.next()) {
PersonaBean personaBean = new PersonaBean();
int c = 1; //Contador para las columnas
personaBean.setCodigo(rsListarPersona.getString(c++));
personaBean.setDni(rsListarPersona.getString(c++));
personaBean.setApellidos(rsListarPersona.getString(c++));
personaBean.setNombres(rsListarPersona.getString(c++));
personaBean.setEdad(rsListarPersona.getString(c++));
personaBean.setCorreo(rsListarPersona.getString(c++));
personaBean.setEstado(rsListarPersona.getString(c++));
JSONObject obj = new JSONObject(personaBean);
obj.put("item", numeroFilas++);
data.put(obj);
}
String sqlCantidadPersonas = "select count(1) as cantidadPersonas from persona a where a.estado = 1 " + condicion;
System.out.println(sqlCantidadPersonas);
psCantidadPersonas = connection.prepareStatement(sqlCantidadPersonas);
rsCantidadPersonas = psCantidadPersonas.executeQuery();
rsCantidadPersonas.next();
cantidadPersonas = rsCantidadPersonas.getInt("cantidadPersonas");
jsonReturn.put("data", data);
jsonReturn.put("recordsFiltered", cantidadPersonas);
jsonReturn.put("recordsTotal", cantidadPersonas);
jsonReturn.put("draw", datos.getString("draw"));
} catch (SQLException e) {
jsonReturn.put("Error", "Error -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "]");
System.err.println("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (rsCantidadPersonas != null) {
rsCantidadPersonas.close();
}
jsonReturn = new JSONObject(response);
System.out.println(jsonReturn);
return jsonReturn;
if (rsListarPersona != null) {
rsListarPersona.close();
}
if (psCantidadPersonas != null) {
psCantidadPersonas.close();
}
if (psListarPersona != null) {
psListarPersona.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
@Override
public JSONObject editarPersona(JSONObject datos) {
JSONObject jsonReturn = new JSONObject();
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
int resultPersona = 0;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "update persona "
+ "set apellidos = RTRIM(UPPER(?)), "
+ "nombres = RTRIM(UPPER(?)), "
+ "edad = ?, "
+ "correo = RTRIM(UPPER(?)) "
+ "where codigo = ?";
psEditarPersona = connection.prepareStatement(sql);
int q = 1; // CONTADOR PARA LAS COLUMNAS
psEditarPersona.setString(q++, datos.getString("apellidos"));
psEditarPersona.setString(q++, datos.getString("nombres"));
psEditarPersona.setString(q++, datos.getString("edad"));
psEditarPersona.setString(q++, datos.getString("correo"));
psEditarPersona.setString(q++, datos.getString("codigo"));
resultPersona = psEditarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Se actualizo correctamente");
response.setStatus(true); // ACTUALIZO
} else {
response.setMessage("Error al actualizar");
response.setStatus(false); // ERROR
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (connection != null) {
connection.close();
}
if (psEditarPersona != null) {
psEditarPersona.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
}
return jsonReturn;
}
@Override
public JSONObject registrarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
int resultDni = 0;
int resultPersona = 0;
String base = "demojsoncrud";
PreparedStatement psInsertarPersona = null, psGetDni = null;
ResultSet rsGetDni = null;
Connection connection = null;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sqlGetDni = "select count(1) dni from persona where dni = ?";
psGetDni = connection.prepareStatement(sqlGetDni);
psGetDni.setString(1, datos.getString("dni"));
rsGetDni = psGetDni.executeQuery();
rsGetDni.next();
resultDni = rsGetDni.getInt("dni");
if (resultDni == 0) {
String sql
= "insert into persona (dni, apellidos, nombres, edad, correo, estado) values "
+ "(?,RTRIM(UPPER(?)),RTRIM(UPPER(?)),?,RTRIM(UPPER(?)),1)";
int c = 1; //contador para las columnas
psInsertarPersona = connection.prepareStatement(sql);
psInsertarPersona.setString(c++, datos.getString("dni"));
psInsertarPersona.setString(c++, datos.getString("apellidos"));
psInsertarPersona.setString(c++, datos.getString("nombres"));
psInsertarPersona.setString(c++, datos.getString("edad"));
psInsertarPersona.setString(c++, datos.getString("correo"));
resultPersona = psInsertarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Registro correcto!");
response.setStatus(true);
} else {
response.setMessage("No se pudo registrar a la persona");
response.setStatus(false); // ERROR
}
jsonReturn = new JSONObject(response);
} else {
response.setMessage("El documento ya existe en mi base de datos. Prueba otro.");
response.setStatus(false); // DNI REPETIDO
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
System.err.println("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (rsGetDni != null) {
rsGetDni.close();
}
if (psGetDni != null) {
psGetDni.close();
}
if (psInsertarPersona != null) {
psInsertarPersona.close();
}
if (connection != null) {
connection.close();
}
return jsonReturn;
} catch (SQLException e) {
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
@Override
public JSONObject cambiarEstado(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = new JSONObject();
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
int resultPersona = 0;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "UPDATE persona "
+ " SET estado = ? "
+ "WHERE codigo = ?;";
psEditarPersona = connection.prepareStatement(sql);
psEditarPersona.setString(1, datos.getString("estado").equals("1") ? "0" : "1");
psEditarPersona.setString(2, datos.getString("codigo"));
resultPersona = psEditarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Se actualizo correctamente");
response.setStatus(true); // ACTUALIZO
} else {
response.setMessage("Error al actualizar");
response.setStatus(false); // ERROR
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (connection != null) {
connection.close();
}
if (psEditarPersona != null) {
psEditarPersona.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject editarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
int resultPersona = 0;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "update persona "
+ "set apellidos = RTRIM(UPPER(?)), "
+ "nombres = RTRIM(UPPER(?)), "
+ "edad = ?, "
+ "correo = RTRIM(UPPER(?)) "
+ "where codigo = ?";
psEditarPersona = connection.prepareStatement(sql);
int q = 1; // CONTADOR PARA LAS COLUMNAS
psEditarPersona.setString(q++, datos.getString("apellidos"));
psEditarPersona.setString(q++, datos.getString("nombres"));
psEditarPersona.setString(q++, datos.getString("edad"));
psEditarPersona.setString(q++, datos.getString("correo"));
psEditarPersona.setString(q++, datos.getString("codigo"));
resultPersona = psEditarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Se actualizo correctamente");
response.setStatus(true); // ACTUALIZO
} else {
response.setMessage("Error al actualizar");
response.setStatus(false); // ERROR
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
System.err.println("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (connection != null) {
connection.close();
}
if (psEditarPersona != null) {
psEditarPersona.close();
}
} catch (SQLException e) {
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
jsonReturn = new JSONObject(response);
return jsonReturn;
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject cambiarEstado(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = null;
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
int resultPersona = 0;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "UPDATE persona "
+ " SET estado = ? "
+ "WHERE codigo = ?;";
psEditarPersona = connection.prepareStatement(sql);
psEditarPersona.setString(1, datos.getString("estado").equals("1") ? "0" : "1");
psEditarPersona.setString(2, datos.getString("codigo"));
resultPersona = psEditarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Se actualizo correctamente");
response.setStatus(true); // ACTUALIZO
} else {
response.setMessage("Error al actualizar");
response.setStatus(false); // ERROR
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
System.err.println("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (psEditarPersona != null) {
psEditarPersona.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
}
/*
* 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 demojsoncrud.sqlserverdao;
import demojsoncrud.beans.UbigeoBean;
......@@ -15,201 +10,193 @@ import java.sql.SQLException;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* @author Alonso
*/
public class UbigeoSqlserverDAO implements UbigeoDAO {
@Override
public JSONObject listarDepartamento() {
JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray();
PreparedStatement psListarDepartamento = null;
ResultSet rsListarDepartamento = null;
Connection connection = null;
String base = "ubigeo";
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select "
+ "codDepartamento as codigoDepartamento, "
+ "nombreDepartamento as nombreDepartamento "
+ "from ubigeo "
+ "group by codDepartamento, nombreDepartamento "
+ "order by nombreDepartamento";
psListarDepartamento = connection.prepareStatement(sql);
rsListarDepartamento = psListarDepartamento.executeQuery();
while (rsListarDepartamento.next()) {
UbigeoBean ubigeoBean = new UbigeoBean();
ubigeoBean.setCodigoDepartamento(rsListarDepartamento.getString("codigoDepartamento"));
ubigeoBean.setNombreDepartamento(rsListarDepartamento.getString("nombreDepartamento"));
JSONObject obj = new JSONObject(ubigeoBean);
data.put(obj);
}
JSONObject jsonData = new JSONObject();
jsonData.put("departamentos", data);
response.setData(jsonData);
response.setMessage("Listado correctamente!");
response.setStatus(true);
} catch (SQLException e) {
response.setMessage("Error al listarDepartamento -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
} finally {
try {
if (rsListarDepartamento != null) {
rsListarDepartamento.close();
}
if (psListarDepartamento != null) {
psListarDepartamento.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
response.setMessage("Error al listarDepartamento -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
}
@Override
public JSONObject listarDepartamento() {
JSONObject jsonReturn = null;
JSONArray data = new JSONArray();
PreparedStatement psListarDepartamento = null;
ResultSet rsListarDepartamento = null;
Connection connection = null;
String base = "ubigeo";
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select "
+ "codDepartamento as codigoDepartamento, "
+ "nombreDepartamento as nombreDepartamento "
+ "from ubigeo "
+ "group by codDepartamento, nombreDepartamento "
+ "order by nombreDepartamento";
psListarDepartamento = connection.prepareStatement(sql);
rsListarDepartamento = psListarDepartamento.executeQuery();
while (rsListarDepartamento.next()) {
UbigeoBean ubigeoBean = new UbigeoBean();
ubigeoBean.setCodigoDepartamento(rsListarDepartamento.getString("codigoDepartamento"));
ubigeoBean.setNombreDepartamento(rsListarDepartamento.getString("nombreDepartamento"));
JSONObject obj = new JSONObject(ubigeoBean);
data.put(obj);
}
JSONObject jsonData = new JSONObject();
jsonData.put("departamentos", data);
response.setData(jsonData);
response.setMessage("Listado correctamente!");
response.setStatus(true);
} catch (SQLException e) {
response.setMessage("Error al listarDepartamento -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
System.err.println("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (rsListarDepartamento != null) {
rsListarDepartamento.close();
}
if (psListarDepartamento != null) {
psListarDepartamento.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject listarProvincia(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray();
PreparedStatement psListarProvincia = null;
ResultSet rsListarProvincia = null;
Connection connection = null;
String base = "ubigeo";
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select "
+ "codProvincia as codigoProvincia, "
+ "nombreProvincia as nombreProvincia "
+ "from ubigeo "
+ "where codDepartamento = ? "
+ "group by codProvincia, nombreProvincia "
+ "order by nombreProvincia";
psListarProvincia = connection.prepareStatement(sql);
psListarProvincia.setInt(1, datos.getInt("codigoDepartamento"));
rsListarProvincia = psListarProvincia.executeQuery();
while (rsListarProvincia.next()) {
UbigeoBean ubigeoBean = new UbigeoBean();
ubigeoBean.setCodigoProvincia(rsListarProvincia.getString("codigoProvincia"));
ubigeoBean.setNombreProvincia(rsListarProvincia.getString("nombreProvincia"));
JSONObject obj = new JSONObject(ubigeoBean);
data.put(obj);
}
JSONObject jsonData = new JSONObject();
jsonData.put("provincias", data);
response.setData(jsonData);
response.setMessage("Listado correctamente!");
response.setStatus(true);
} catch (SQLException e) {
response.setMessage("Error al listarProvincia -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
} finally {
try {
if (rsListarProvincia != null) {
rsListarProvincia.close();
}
if (psListarProvincia != null) {
psListarProvincia.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
response.setMessage("Error al listarProvincia -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject listarProvincia(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = null;
JSONArray data = new JSONArray();
PreparedStatement psListarProvincia = null;
ResultSet rsListarProvincia = null;
Connection connection = null;
String base = "ubigeo";
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select "
+ "codProvincia as codigoProvincia, "
+ "nombreProvincia as nombreProvincia "
+ "from ubigeo "
+ "where codDepartamento = ? "
+ "group by codProvincia, nombreProvincia "
+ "order by nombreProvincia";
psListarProvincia = connection.prepareStatement(sql);
psListarProvincia.setInt(1, datos.getInt("codigoDepartamento"));
rsListarProvincia = psListarProvincia.executeQuery();
while (rsListarProvincia.next()) {
UbigeoBean ubigeoBean = new UbigeoBean();
ubigeoBean.setCodigoProvincia(rsListarProvincia.getString("codigoProvincia"));
ubigeoBean.setNombreProvincia(rsListarProvincia.getString("nombreProvincia"));
JSONObject obj = new JSONObject(ubigeoBean);
data.put(obj);
}
JSONObject jsonData = new JSONObject();
jsonData.put("provincias", data);
response.setData(jsonData);
response.setMessage("Listado correctamente!");
response.setStatus(true);
} catch (SQLException e) {
response.setMessage("Error al listarProvincia -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
System.err.println("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (rsListarProvincia != null) {
rsListarProvincia.close();
}
if (psListarProvincia != null) {
psListarProvincia.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject listarDistrito(JSONObject datos) {
JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray();
PreparedStatement psListarDistrito = null;
ResultSet rsListarDistrito = null;
Connection connection = null;
String base = "ubigeo";
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select "
+ "codDistrito as codigoDistrito, "
+ "nombreDistrito as nombreDistrito "
+ "from ubigeo "
+ "where codProvincia = ? and codDepartamento = ? "
+ "order by nombreDistrito";
psListarDistrito = connection.prepareStatement(sql);
psListarDistrito.setInt(1, datos.getInt("codigoProvincia"));
psListarDistrito.setInt(2, datos.getInt("codigoDepartamento"));
rsListarDistrito = psListarDistrito.executeQuery();
while (rsListarDistrito.next()) {
UbigeoBean ubigeoBean = new UbigeoBean();
ubigeoBean.setCodigoDistrito(rsListarDistrito.getString("codigoDistrito"));
ubigeoBean.setNombreDistrito(rsListarDistrito.getString("nombreDistrito"));
JSONObject obj = new JSONObject(ubigeoBean);
data.put(obj);
}
JSONObject jsonData = new JSONObject();
jsonData.put("distritos", data);
response.setData(jsonData);
response.setMessage("Listado correctamente!");
response.setStatus(true);
} catch (SQLException e) {
response.setMessage("Error al listarDistrito -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
} finally {
try {
if (rsListarDistrito != null) {
rsListarDistrito.close();
}
if (psListarDistrito != null) {
psListarDistrito.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
response.setMessage("Error al listarDistrito -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject listarDistrito(JSONObject datos) {
JSONObject jsonReturn = null;
JSONArray data = new JSONArray();
PreparedStatement psListarDistrito = null;
ResultSet rsListarDistrito = null;
Connection connection = null;
String base = "ubigeo";
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select "
+ "codDistrito as codigoDistrito, "
+ "nombreDistrito as nombreDistrito "
+ "from ubigeo "
+ "where codProvincia = ? and codDepartamento = ? "
+ "order by nombreDistrito";
psListarDistrito = connection.prepareStatement(sql);
psListarDistrito.setInt(1, datos.getInt("codigoProvincia"));
psListarDistrito.setInt(2, datos.getInt("codigoDepartamento"));
rsListarDistrito = psListarDistrito.executeQuery();
while (rsListarDistrito.next()) {
UbigeoBean ubigeoBean = new UbigeoBean();
ubigeoBean.setCodigoDistrito(rsListarDistrito.getString("codigoDistrito"));
ubigeoBean.setNombreDistrito(rsListarDistrito.getString("nombreDistrito"));
JSONObject obj = new JSONObject(ubigeoBean);
data.put(obj);
}
JSONObject jsonData = new JSONObject();
jsonData.put("distritos", data);
response.setData(jsonData);
response.setMessage("Listado correctamente!");
response.setStatus(true);
} catch (SQLException e) {
response.setMessage("Error al listarDistrito -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
System.err.println("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (rsListarDistrito != null) {
rsListarDistrito.close();
}
jsonReturn = new JSONObject(response);
return jsonReturn;
if (psListarDistrito != null) {
psListarDistrito.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
}
package demojsoncrud.utilities;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONObject;
public class CustomHttpServletRequest {
public static JSONObject getBodyJsonObject(HttpServletRequest request) throws IOException {
String body = "";
if (request.getMethod().equals("POST")) {
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = null;
bufferedReader = request.getReader(); // swallow silently -- can't get body, won't
char[] charBuffer = new char[128];
int bytesRead;
while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
sb.append(charBuffer, 0, bytesRead);
}
if (bufferedReader != null) {
bufferedReader.close(); // swallow silently -- can't get body, won't
}
body = sb.toString();
}
JSONObject respuesta = new JSONObject(body);
return respuesta;
}
}
......@@ -5,36 +5,41 @@ import org.json.JSONObject;
public class ResponseHelper implements Serializable {
private JSONObject data;
private boolean status;
private String message;
public ResponseHelper() {
}
public JSONObject getData() {
return data;
}
public boolean isStatus() {
return status;
}
public String getMessage() {
return message;
}
public void setData(JSONObject data) {
this.data = data;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setMessage(String message) {
this.message = message;
}
private JSONObject data;
private boolean status;
private String message;
public ResponseHelper() {
}
public ResponseHelper(JSONObject data, boolean status, String message) {
this.data = data;
this.status = status;
this.message = message;
}
public JSONObject getData() {
return data;
}
public boolean isStatus() {
return status;
}
public String getMessage() {
return message;
}
public void setData(JSONObject data) {
this.data = data;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setMessage(String message) {
this.message = message;
}
}
/**
* Facilita el uso de fetch
* @method fetchSo
* @param {String} url nombre de objeto
* @param {object} object mensaje a mostrar
* @returns {Promise} Promise retorna status, msg
*/
let fetchSo = (url, object) => {
return new Promise(
(resolve, reject) => {
let header = {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json; charset=utf-8'
}
let requestInfo = {
method: 'post',
headers: header,
body: JSON.stringify({json: object})
}
fetch(url, requestInfo)
.then((res) => {
return res.json()
})
.then((res) => {
if (res.status) {
resolve(res)
} else {
reject(res)
}
})
.catch((error) => {
reject(error)
})
}
)
}
/**
* Crea los elementos option del array que se pase como parametro
* @method createSelectOptions
* @param {JSONArray} obj array de objetos
......@@ -44,32 +7,32 @@ let fetchSo = (url, object) => {
* @returns {Promise} Promise retorna status, msg
*/
let createSelectOptions = (obj, valueName, textName) => {
let options = ''
obj.forEach((data) => {
options += `<option value="${data[valueName]}">${data[textName]}</option>`
})
return options
let options = ''
obj.forEach((data) => {
options += `<option value="${data[valueName]}">${data[textName]}</option>`
})
return options
}
let customSwal = {
alert (title, text, type) {
let colors = {
success: '#66BB6A',
error: '#EF5350',
warning: '#FF7043'
}
let btnColor = colors[type]
return new Promise((resolve, reject) => {
swal({
title: title,
text: text,
confirmButtonColor: btnColor,
type: type
}, (isConfirm) => {
resolve()
})
})
alert(title, text, type) {
let colors = {
success: '#66BB6A',
error: '#EF5350',
warning: '#FF7043'
}
let btnColor = colors[type]
return new Promise((resolve, reject) => {
swal({
title: title,
text: text,
confirmButtonColor: btnColor,
type: type
}, (isConfirm) => {
resolve()
})
})
}
}
/**
......@@ -81,46 +44,26 @@ let customSwal = {
*/
let getClosest = (elem, selector) => {
// Element.matches() polyfill
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function (s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1
}
}
// Get closest match
for (; elem && elem !== document; elem = elem.parentNode) {
if (elem.matches(selector)) return elem
}
return null
// Element.matches() polyfill
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function (s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length
while (--i >= 0 && matches.item(i) !== this) {
}
return i > -1
}
}
// Get closest match
for (; elem && elem !== document; elem = elem.parentNode) {
if (elem.matches(selector))
return elem
}
return null
}
// function imprimirAlerta (title, text, type) {
// var s_col =
// var e_col = '#EF5350'
// var w_col = '#FF7043'
// var btnCol
//
// if (type === 'error') {
// btnCol = e_col
// } else if (type === 'warning') {
// btnCol = w_col
// } else {
// btnCol = s_col
// }
//
// swal({
// title: title,
// text: text,
// confirmButtonColor: btnCol,
// type: type
// })
//
// }
\ No newline at end of file
let jqueryValidateConfig = () => {
function stripHtml (value) {
// remove html tags and space chars
return value.replace(/<.[^<>]*?>/g, ' ').replace(/&nbsp;|&#160;/gi, ' ')
// remove numbers and punctuation
.replace(/[0-9.(),;:!?%#$'"_+=\/-]*/g, '')
}
function stripHtml(value) {
// remove html tags and space chars
return value.replace(/<.[^<>]*?>/g, ' ').replace(/&nbsp;|&#160;/gi, ' ')
// remove numbers and punctuation
.replace(/[0-9.(),;:!?%#$'"_+=\/-]*/g, '')
}
jQuery.validator.addMethod('lettersonly', function (value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value)
}, 'Solo letras.')
jQuery.validator.setDefaults({
debug: true,
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-error-label',
successClass: 'validation-valid-label',
highlight: function (element, errorClass) {
$(element).removeClass(errorClass)
},
unhighlight: function (element, errorClass) {
$(element).removeClass(errorClass)
},
// Different components require proper error label placement
errorPlacement: function (error, element) {
jQuery.validator.addMethod('lettersonly', function (value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value)
}, 'Solo letras.')
jQuery.validator.setDefaults({
debug: true,
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-error-label',
successClass: 'validation-valid-label',
highlight: function (element, errorClass) {
$(element).removeClass(errorClass)
},
unhighlight: function (element, errorClass) {
$(element).removeClass(errorClass)
},
// Different components require proper error label placement
errorPlacement: function (error, element) {
// Styled checkboxes, radios, bootstrap switch
if (element.parents('div').hasClass('checker') || element.parents('div').hasClass('choice') || element.parent().hasClass('bootstrap-switch-container')) {
if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent().parent().parent())
} else {
error.appendTo(element.parent().parent().parent().parent().parent())
}
}
// Styled checkboxes, radios, bootstrap switch
if (element.parents('div').hasClass('checker') || element.parents('div').hasClass('choice') || element.parent().hasClass('bootstrap-switch-container')) {
if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent().parent().parent())
} else {
error.appendTo(element.parent().parent().parent().parent().parent())
}
}
// Unstyled checkboxes, radios
else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {
error.appendTo(element.parent().parent().parent())
}
// Unstyled checkboxes, radios
else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {
error.appendTo(element.parent().parent().parent())
}
// Input with icons and Select2
else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo(element.parent())
}
// Input with icons and Select2
else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo(element.parent())
}
// Inline checkboxes, radios
else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent())
}
// Inline checkboxes, radios
else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent())
}
// Input group, styled file input
else if (element.parent().hasClass('uploader') || element.parents().hasClass('input-group')) {
error.appendTo(element.parent().parent())
} else {
error.insertAfter(element)
}
}
})
// Input group, styled file input
else if (element.parent().hasClass('uploader') || element.parents().hasClass('input-group')) {
error.appendTo(element.parent().parent())
} else {
error.insertAfter(element)
}
}
})
}
let persona = {
listar () {
let txtCriterioBusqueda = $('#txt-busqueda').val().trim()
return new Promise((resolve) => {
$('#tbl-persona').DataTable().destroy()
$('#tbl-persona').DataTable({
language: {
paginate: {'next': '&rarr; ', 'previous': ' &larr;'},
emptyTable: 'No hay registros'
},
ajax: {
url: '../PersonaServlet?accion=listarPersona',
type: 'POST',
dataType: 'json',
data: {search: txtCriterioBusqueda}
},
columnDefs: [
{targets: 0, orderable: false, width: '5%', className: 'centrado'},
{targets: 1, orderable: false, width: '15%', className: 'centrado'},
{targets: 2, orderable: false, width: '30%', className: 'centrado'},
{targets: 3, orderable: false, width: '5%', className: 'centrado'},
{targets: 4, orderable: false, width: '25%', className: 'centrado'},
{targets: 5, orderable: false, width: '10%', className: 'centrado'},
{targets: 6, orderable: false, width: '10%', className: 'centrado'}
],
dom: '<"datatable-scroll"t><"datatable-footer"ip>',
fixedColumns: true,
processing: true,
serverSide: true,
responsive: true,
iDisplayLength: 10,
bSort: false,
bInfo: false,
searching: false,
bLengthChange: false,
bFilter: false,
aaSorting: [],
ordering: false,
scrollX: false,
ScrollCollapse: true,
columns: [
{data: 'codigo'},
{data: 'dni'},
{
data: null,
render: function (data, type, row) {
return data.apellidos + ', ' + data.nombres
}
},
{data: 'edad', className: 'text-center'},
{data: 'correo'},
{
data: 'estado',
className: 'text-center',
render: function (data, type, row) {
return data === '1' ? '<span class="label label-success">activo</span>' : '<span class="label label-danger">inactivo</span>'
}
},
{
data: null,
className: 'text-center',
render: function (data, type, row) {
// debugger
return `<ul class="icons-list">
listar() {
let txtCriterioBusqueda = $('#txt-busqueda').val().trim()
return new Promise((resolve) => {
$('#tbl-persona').DataTable().destroy()
$('#tbl-persona').DataTable({
language: {
paginate: {'next': '&rarr; ', 'previous': ' &larr;'},
emptyTable: 'No hay registros'
},
ajax: {
url: '../PersonaServlet?accion=listarPersona',
type: 'POST',
dataType: 'json',
data: {search: txtCriterioBusqueda}
},
columnDefs: [
{targets: 0, orderable: false, width: '5%', className: 'centrado'},
{targets: 1, orderable: false, width: '15%', className: 'centrado'},
{targets: 2, orderable: false, width: '30%', className: 'centrado'},
{targets: 3, orderable: false, width: '5%', className: 'centrado'},
{targets: 4, orderable: false, width: '25%', className: 'centrado'},
{targets: 5, orderable: false, width: '10%', className: 'centrado'},
{targets: 6, orderable: false, width: '10%', className: 'centrado'}
],
dom: '<"datatable-scroll"t><"datatable-footer"ip>',
fixedColumns: true,
processing: true,
serverSide: true,
responsive: true,
iDisplayLength: 10,
bSort: false,
bInfo: false,
searching: false,
bLengthChange: false,
bFilter: false,
aaSorting: [],
ordering: false,
scrollX: false,
ScrollCollapse: true,
columns: [
{data: 'codigo'},
{data: 'dni'},
{
data: null,
render: function (data, type, row) {
return data.apellidos + ', ' + data.nombres
}
},
{data: 'edad', className: 'text-center'},
{data: 'correo'},
{
data: 'estado',
className: 'text-center',
render: function (data, type, row) {
return data === '1' ? '<span class="label label-success">activo</span>' : '<span class="label label-danger">inactivo</span>'
}
},
{
data: null,
className: 'text-center',
render: function (data, type, row) {
// debugger
return `<ul class="icons-list">
<li title="Editar" data-toggle="modal" data-target="#modal_editar_persona" class="text-primary-600">
<a href="#" class="editarPersona"><i class="icon-pencil7"></i></a>
</li>
......@@ -127,241 +127,273 @@ let persona = {
<a href="#" class="estado"><i class="icon-switch2"></i></a>
</li>
</ul>`
}
}
],
'fnInitComplete': function (oSettings, json) {
resolve(json)
}
})
})
},
cambiarEstado (datos) {
return new Promise((resolve, reject) => {
fetchSo('../PersonaServlet?accion=cambiarEstado', datos)
.then((data) => {
resolve(data)
})
.catch((data) => {
reject(data)
})
})
},
registrar () {
let json = {
dni: $('#txt_numero_documento').val().trim(),
apellidos: $('#txt_apellidos').val().trim(),
nombres: $('#txt_nombres').val().trim(),
edad: $('#txt_edad').val().trim(),
correo: $('#txt_correo').val().trim()
}
}
],
'fnInitComplete': function (oSettings, json) {
resolve(json)
}
return new Promise((resolve, reject) => {
fetchSo('../PersonaServlet?accion=registrarPersona', json)
.then((data) => {
resolve(data)
})
.catch((data) => {
reject(data)
})
})
},
editar () {
let json = {
apellidos: $('#txt_apellidos_editar').val().trim(),
nombres: $('#txt_nombres_editar').val().trim(),
edad: $('#txt_edad_editar').val().trim(),
correo: $('#txt_correo_editar').val().trim(),
codigo: localStorage.getItem('codigoPersona')
})
})
},
cambiarEstado(datos) {
return new Promise((resolve, reject) => {
$.ajax({
url: '../PersonaServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'cambiarEstado',
json: JSON.stringify(datos)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al cambiar estado")
}
return new Promise((resolve, reject) => {
fetchSo('../PersonaServlet?accion=editarPersona', json)
.then((data) => {
resolve(data)
})
.catch((data) => {
reject(data)
})
})
})
},
registrar() {
let json = {
dni: $('#txt_numero_documento').val().trim(),
apellidos: $('#txt_apellidos').val().trim(),
nombres: $('#txt_nombres').val().trim(),
edad: $('#txt_edad').val().trim(),
correo: $('#txt_correo').val().trim()
}
return new Promise((resolve, reject) => {
$.ajax({
url: '../PersonaServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'registrarPersona',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al registrar personal")
}
})
fetchSo('../PersonaServlet?accion=registrarPersona', json)
.then((data) => {
resolve(data)
})
.catch((data) => {
reject(data)
})
})
},
editar() {
let json = {
apellidos: $('#txt_apellidos_editar').val().trim(),
nombres: $('#txt_nombres_editar').val().trim(),
edad: $('#txt_edad_editar').val().trim(),
correo: $('#txt_correo_editar').val().trim(),
codigo: localStorage.getItem('codigoPersona')
}
return new Promise((resolve, reject) => {
$.ajax({
url: '../PersonaServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'editarPersona',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al editar persona")
}
})
})
}
}
let obtenerDatosTabla = (fila) => {
return $('#tbl-persona').DataTable().row(fila).data()
return $('#tbl-persona').DataTable().row(fila).data()
}
let limpiarCajasTexto = () => {
$('#btn_agregar_persona').on('click', function () {
$('#txt_numero_documento').attr({
autofocus: true
}).val('')
$('#txt_apellidos').val('')
$('#txt_nombres').val('')
$('#txt_edad').val('')
$('#txt_correo').val('')
})
$('#btn_agregar_persona').on('click', function () {
$('#txt_numero_documento').attr({
autofocus: true
}).val('')
$('#txt_apellidos').val('')
$('#txt_nombres').val('')
$('#txt_edad').val('')
$('#txt_correo').val('')
})
}
let asignarEventos = () => {
$('#tbl-persona tbody').on('click', '.estado', (event) => {
let rowData = obtenerDatosTabla($(event.currentTarget).parents('tr'))
swal({
title: '¿Estás seguro?',
text: `¿Desea ${rowData.estado === '1' ? 'DESACTIVAR' : 'ACTIVAR'} a ${rowData.apellidos} ${rowData.nombres}?`,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#EF5350',
confirmButtonText: 'Si',
cancelButtonText: 'No',
closeOnConfirm: false,
closeOnCancel: true
}, (isConfirm) => {
if (isConfirm) {
persona.cambiarEstado(rowData)
.then((data) => {
customSwal
.alert('¡Exito!', 'Se actualizó con exito.', 'success')
.then(() => {
persona.listar()
})
})
.catch((data) => {
customSwal.alert('¡Error!', 'No se registró con exito.', 'error')
})
}
})
$('#tbl-persona tbody').on('click', '.estado', (event) => {
let rowData = obtenerDatosTabla($(event.currentTarget).parents('tr'))
swal({
title: '¿Estás seguro?',
text: `¿Desea ${rowData.estado === '1' ? 'DESACTIVAR' : 'ACTIVAR'} a ${rowData.apellidos} ${rowData.nombres}?`,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#EF5350',
confirmButtonText: 'Si',
cancelButtonText: 'No',
closeOnConfirm: false,
closeOnCancel: true
}, (isConfirm) => {
if (isConfirm) {
persona.cambiarEstado(rowData)
.then((data) => {
customSwal
.alert('¡Exito!', 'Se actualizó con exito.', 'success')
.then(() => {
persona.listar()
})
})
.catch((data) => {
customSwal.alert('¡Error!', 'No se registró con exito.', 'error')
})
}
})
})
document.querySelectorAll('.estado').forEach((e) => {
e.addEventListener('click', (ev) => {
console.log(getClosest(ev.target, 'tr').rowIndex - 1)
})
document.querySelectorAll('.estado').forEach((e) => {
e.addEventListener('click', (ev) => {
console.log(getClosest(ev.target, 'tr').rowIndex - 1)
})
})
$('#tbl-persona tbody').on('click', '.editarPersona', (event) => {
let rowData = obtenerDatosTabla($(event.currentTarget).parents('tr'))
$('#txt_numero_documento_editar').val(rowData.dni)
$('#txt_apellidos_editar').val(rowData.apellidos)
$('#txt_nombres_editar').val(rowData.nombres)
$('#txt_edad_editar').val(rowData.edad)
$('#txt_correo_editar').val(rowData.correo)
localStorage.setItem('codigoPersona', rowData.codigo)
})
$('#tbl-persona tbody').on('click', '.editarPersona', (event) => {
let rowData = obtenerDatosTabla($(event.currentTarget).parents('tr'))
$('#txt_numero_documento_editar').val(rowData.dni)
$('#txt_apellidos_editar').val(rowData.apellidos)
$('#txt_nombres_editar').val(rowData.nombres)
$('#txt_edad_editar').val(rowData.edad)
$('#txt_correo_editar').val(rowData.correo)
localStorage.setItem('codigoPersona', rowData.codigo)
})
$('#btn_registrar_persona').on('click', function () {
let validator = $('#form_registrar_persona').validate({
rules: {
txt_numero_documento: {required: true, digits: true, minlength: 8, maxlength: 8},
txt_apellidos: {required: true, lettersonly: true, maxlength: 50},
txt_nombres: {required: true, lettersonly: true, maxlength: 50},
txt_edad: {required: true, digits: true, maxlength: 2},
txt_correo: {required: true, email: true, maxlength: 50}
},
messages: {
txt_numero_documento: {
required: 'Ingresar número de documento.',
minlength: 'Ingresar 8 dígitos.',
maxlength: 'Ingresar 8 dígitos.',
digits: 'Ingresar solo números.'
},
txt_apellidos: {
required: 'Ingresar apellidos.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_nombres: {
required: 'Ingresar nombres.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_edad: {
required: 'Ingresar edad.',
maxlength: 'Ingresar 2 dígitos como máximo',
digits: 'Ingresar solo números'
},
txt_correo: {
required: 'Ingresar correo.',
maxlength: 'Ingresar 50 letras como máximo.',
email: 'Ingresar un correo válido'
}
}
})
let estado = validator.form()
if (estado) {
persona
.registrar()
.then((data) => {
customSwal
.alert('¡Exito!', data.message, 'success')
.then(() => {
$('#modal_registrar_persona').modal('hide')
})
.then(() => {
persona.listar()
})
})
.catch((data) => {
customSwal.alert('¡Error!', data.message, 'error')
})
$('#btn_registrar_persona').on('click', function () {
let validator = $('#form_registrar_persona').validate({
rules: {
txt_numero_documento: {required: true, digits: true, minlength: 8, maxlength: 8},
txt_apellidos: {required: true, lettersonly: true, maxlength: 50},
txt_nombres: {required: true, lettersonly: true, maxlength: 50},
txt_edad: {required: true, digits: true, maxlength: 2},
txt_correo: {required: true, email: true, maxlength: 50}
},
messages: {
txt_numero_documento: {
required: 'Ingresar número de documento.',
minlength: 'Ingresar 8 dígitos.',
maxlength: 'Ingresar 8 dígitos.',
digits: 'Ingresar solo números.'
},
txt_apellidos: {
required: 'Ingresar apellidos.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_nombres: {
required: 'Ingresar nombres.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_edad: {
required: 'Ingresar edad.',
maxlength: 'Ingresar 2 dígitos como máximo',
digits: 'Ingresar solo números'
},
txt_correo: {
required: 'Ingresar correo.',
maxlength: 'Ingresar 50 letras como máximo.',
email: 'Ingresar un correo válido'
}
}
})
$('#btn_editar_persona').on('click', function () {
let validator = $('#form_editar_persona').validate({
rules: {
txt_apellidos_editar: {required: true, lettersonly: true, maxlength: 50},
txt_nombres_editar: {required: true, lettersonly: true, maxlength: 50},
txt_edad_editar: {required: true, digits: true, maxlength: 2},
txt_correo_editar: {required: true, email: true, maxlength: 50}
},
messages: {
txt_apellidos_editar: {
required: 'Ingresar apellidos.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_nombres_editar: {
required: 'Ingresar nombres.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_edad_editar: {
required: 'Ingresar edad.',
maxlength: 'Ingresar 2 dígitos como máximo',
digits: 'Ingresar solo números'
},
txt_correo_editar: {
required: 'Ingresar correo.',
maxlength: 'Ingresar 50 letras como máximo.',
email: 'Ingresar un correo válido'
}
}
let estado = validator.form()
if (estado) {
persona
.registrar()
.then((data) => {
customSwal
.alert('¡Exito!', data.message, 'success')
.then(() => {
$('#modal_registrar_persona').modal('hide')
})
.then(() => {
persona.listar()
})
})
let estado = validator.form()
if (estado) {
persona
.editar()
.then((data) => {
customSwal
.alert('¡Exito!', data.message, 'success')
.then(() => {
$('#modal_editar_persona').modal('hide')
})
.then(() => {
persona.listar()
})
})
.catch((data) => {
customSwal.alert('¡Error!', data.message, 'error')
})
.catch((data) => {
customSwal.alert('¡Error!', data.message, 'error')
})
}
})
$('#btn_editar_persona').on('click', function () {
let validator = $('#form_editar_persona').validate({
rules: {
txt_apellidos_editar: {required: true, lettersonly: true, maxlength: 50},
txt_nombres_editar: {required: true, lettersonly: true, maxlength: 50},
txt_edad_editar: {required: true, digits: true, maxlength: 2},
txt_correo_editar: {required: true, email: true, maxlength: 50}
},
messages: {
txt_apellidos_editar: {
required: 'Ingresar apellidos.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_nombres_editar: {
required: 'Ingresar nombres.',
maxlength: 'Ingresar 50 letras como máximo.',
lettersonly: 'Ingresar solo letras'
},
txt_edad_editar: {
required: 'Ingresar edad.',
maxlength: 'Ingresar 2 dígitos como máximo',
digits: 'Ingresar solo números'
},
txt_correo_editar: {
required: 'Ingresar correo.',
maxlength: 'Ingresar 50 letras como máximo.',
email: 'Ingresar un correo válido'
}
}
})
let estado = validator.form()
if (estado) {
persona
.editar()
.then((data) => {
customSwal
.alert('¡Exito!', data.message, 'success')
.then(() => {
$('#modal_editar_persona').modal('hide')
})
.then(() => {
persona.listar()
})
})
.catch((data) => {
customSwal.alert('¡Error!', data.message, 'error')
})
}
})
$('#btn_buscar_criterio').on('click', function () {
persona.listar()
})
$('#btn_buscar_criterio').on('click', function () {
persona.listar()
})
$('#txt-busqueda').keyup(function (e) {
if (e.keyCode === 13) {
persona.listar()
}
})
$('#txt-busqueda').keyup(function (e) {
if (e.keyCode === 13) {
persona.listar()
}
})
}
jqueryValidateConfig()
......
let ubigeo = {
consultarDepartamento () {
return new Promise((resolve, reject) => {
fetchSo('../UbigeoServlet?accion=listarDepartamento')
.then((data) => {
resolve(data)
})
.catch((data) => {
reject(data)
})
})
},
consultarProvincia (codigoDepartamento) {
let json = {
codigoDepartamento: codigoDepartamento
consultarDepartamento() {
return new Promise((resolve, reject) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarDepartamento'
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar departamentos")
}
return new Promise((resolve, reject) => {
fetchSo('../UbigeoServlet?accion=listarProvincia', json)
.then((data) => {
resolve(data)
})
.catch((data) => {
reject(data)
})
})
},
consultarDistrito (codigoDepartamento, codigoProvincia) {
let json = {
codigoProvincia: codigoProvincia,
codigoDepartamento: codigoDepartamento
})
})
},
consultarProvincia(codigoDepartamento) {
let json = {
codigoDepartamento: codigoDepartamento
}
return new Promise((resolve, reject) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarProvincia',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar provincias")
}
return new Promise((resolve, reject) => {
fetchSo('../UbigeoServlet?accion=listarDistrito', json)
.then((data) => {
resolve(data)
})
.catch((data) => {
reject(data)
})
})
})
})
},
consultarDistrito(codigoDepartamento, codigoProvincia) {
let json = {
codigoProvincia: codigoProvincia,
codigoDepartamento: codigoDepartamento
}
return new Promise((resolve, reject) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarDistrito',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar distritos")
}
})
})
}
}
let asignarEventos = () => {
let slDepartamento = document.querySelector('#select_departamento')
let slProvincia = document.querySelector('#select_provincia')
let slDistrito = document.querySelector('#select_distrito')
slDepartamento.addEventListener('change', (e) => {
let codigoDepartamento = parseInt(e.target.value)
ubigeo.consultarProvincia(codigoDepartamento)
.then((data) => {
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.provincias, 'codigoProvincia', 'nombreProvincia')
slProvincia.innerHTML = opt
})
.then(() => {
$('#select_provincia').selectpicker('refresh')
})
})
slProvincia.addEventListener('change', (e) => {
let codigoDepartamento = parseInt(slDepartamento.value)
let codigoProvincia = parseInt(e.target.value)
ubigeo.consultarDistrito(codigoDepartamento, codigoProvincia)
.then((data) => {
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.distritos, 'codigoDistrito', 'nombreDistrito')
slDistrito.innerHTML = opt
})
.then(() => {
$('#select_distrito').selectpicker('refresh')
})
})
slDepartamento.addEventListener('change', (e) => {
let departamento = parseInt(e.target.value)
if (departamento === 0) {
slProvincia.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
slDistrito.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
} else {
slProvincia.value = 0
slDistrito.value = 0
}
let slDepartamento = document.querySelector('#select_departamento')
let slProvincia = document.querySelector('#select_provincia')
let slDistrito = document.querySelector('#select_distrito')
slDepartamento.addEventListener('change', (e) => {
let codigoDepartamento = parseInt(e.target.value)
ubigeo.consultarProvincia(codigoDepartamento)
.then((data) => {
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.provincias, 'codigoProvincia', 'nombreProvincia')
slProvincia.innerHTML = opt
})
.then(() => {
slDistrito.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
$('#select_distrito').selectpicker('refresh')
$('#select_provincia').selectpicker('refresh')
})
})
slProvincia.addEventListener('change', (e) => {
let codigoDepartamento = parseInt(slDepartamento.value)
let codigoProvincia = parseInt(e.target.value)
ubigeo.consultarDistrito(codigoDepartamento, codigoProvincia)
.then((data) => {
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.distritos, 'codigoDistrito', 'nombreDistrito')
slDistrito.innerHTML = opt
})
.then(() => {
$('#select_distrito').selectpicker('refresh')
})
})
})
slDepartamento.addEventListener('change', (e) => {
let departamento = parseInt(e.target.value)
if (departamento === 0) {
slProvincia.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
slDistrito.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
} else {
slProvincia.value = 0
slDistrito.value = 0
}
$('#select_provincia').selectpicker('refresh')
$('#select_distrito').selectpicker('refresh')
})
}
ubigeo
.consultarDepartamento()
.then((data) => {
let element = document.querySelector('#select_departamento')
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.departamentos, 'codigoDepartamento', 'nombreDepartamento')
element.innerHTML = opt
let element = document.querySelector('#select_departamento')
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.departamentos, 'codigoDepartamento', 'nombreDepartamento')
element.innerHTML = opt
})
.then(() => {
$('#select_departamento').selectpicker('refresh')
$('#select_departamento').selectpicker('refresh')
})
asignarEventos()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment