Commit 94d0c27c by Alonso Moreno Postigo

[EDIT] v0.1

parent ba1776aa
......@@ -2,12 +2,10 @@ package demojsoncrud.beans;
import java.io.Serializable;
/**
*
* @author Alonso
*/
public class PersonaBean implements Serializable {
private static final long serialVersionUID = 4594333294248399680L;
private String codigo;
private String dni;
private String apellidos;
......
......@@ -4,6 +4,8 @@ import java.io.Serializable;
public class UbigeoBean implements Serializable {
private static final long serialVersionUID = 4594333294248399680L;
private String codigoDepartamento;
private String nombreDepartamento;
private String codigoProvincia;
......@@ -11,6 +13,9 @@ public class UbigeoBean implements Serializable {
private String codigoDistrito;
private String nombreDistrito;
public UbigeoBean() {
}
public String getCodigoDepartamento() {
return codigoDepartamento;
}
......
/*
* 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;
......
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();
......
package demojsoncrud.services;
import demojsoncrud.beans.PersonaBean;
import demojsoncrud.dao.DAOFactory;
import demojsoncrud.dao.PersonaDAO;
import org.json.JSONObject;
......@@ -8,14 +7,14 @@ import org.json.JSONObject;
public class PersonaService {
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
PersonaDAO service = daoFactory.getPersonaDAO();
PersonaDAO dao = daoFactory.getPersonaDAO();
public JSONObject listarPersona(String search, String draw, String start, String length) {
public JSONObject listarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarPersona(search, draw, start, length);
jsonReturn = dao.listarPersona(datos);
} catch (Exception e) {
e.getMessage();
System.out.println("Error PersonaService >> listarPersona >> " + e.getMessage());
}
return jsonReturn;
}
......@@ -23,9 +22,9 @@ public class PersonaService {
public JSONObject registrarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.registrarPersona(datos);
jsonReturn = dao.registrarPersona(datos);
} catch (Exception e) {
e.getMessage();
System.out.println("Error PersonaService >> registrarPersona >> " + e.getMessage());
}
return jsonReturn;
}
......@@ -33,9 +32,9 @@ public class PersonaService {
public JSONObject editarPersona(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.editarPersona(datos);
jsonReturn = dao.editarPersona(datos);
} catch (Exception e) {
e.getMessage();
System.out.println("Error PersonaService >> editarPersona >> " + e.getMessage());
}
return jsonReturn;
}
......@@ -43,8 +42,9 @@ public class PersonaService {
public JSONObject cambiarEstado(JSONObject datos) {
JSONObject respuesta = null;
try {
respuesta = service.cambiarEstado(datos);
respuesta = dao.cambiarEstado(datos);
} catch (Exception e) {
System.out.println("Error PersonaService >> cambiarEstado >> " + e.getMessage());
}
return respuesta;
}
......
package demojsoncrud.services;
import demojsoncrud.beans.UbigeoBean;
import demojsoncrud.dao.DAOFactory;
import demojsoncrud.dao.UbigeoDAO;
import org.json.JSONObject;
......@@ -8,13 +7,14 @@ import org.json.JSONObject;
public class UbigeoService {
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
UbigeoDAO service = daoFactory.getUbigeoDAO();
UbigeoDAO dao = daoFactory.getUbigeoDAO();
public JSONObject listarDepartamento() {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarDepartamento();
jsonReturn = dao.listarDepartamento();
} catch (Exception e) {
System.out.println("Error UbigeoService >> listarDepartamento >> " + e.getMessage());
}
return jsonReturn;
}
......@@ -22,8 +22,9 @@ public class UbigeoService {
public JSONObject listarProvincia(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarProvincia(datos);
jsonReturn = dao.listarProvincia(datos);
} catch (Exception e) {
System.out.println("Error UbigeoService >> listarProvincia >> " + e.getMessage());
}
return jsonReturn;
}
......@@ -31,8 +32,9 @@ public class UbigeoService {
public JSONObject listarDistrito(JSONObject datos) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarDistrito(datos);
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;
......@@ -46,12 +45,15 @@ public class PersonaServlet extends HttpServlet {
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
String draw = request.getParameter("draw");
String start = request.getParameter("start");
String length = request.getParameter("length");
String search = request.getParameter("search");
JSONObject json = service.listarPersona(search, draw, start, length);
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);
}
......@@ -59,9 +61,8 @@ public class PersonaServlet extends HttpServlet {
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"));
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.registrarPersona(datos);
pw.print(respuesta);
}
......@@ -70,9 +71,8 @@ public class PersonaServlet extends HttpServlet {
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"));
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.editarPersona(datos);
pw.print(respuesta);
}
......@@ -80,9 +80,8 @@ public class PersonaServlet extends HttpServlet {
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"));
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;
......@@ -16,12 +15,28 @@ public class UbigeoServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("accion");
response.setCharacterEncoding("UTF-8");
if ("listarDepartamento".equals(param)) {
if (null != param) {
switch (param) {
case "listarDepartamento":
listarDepartamento(request, response);
} else if ("listarProvincia".equals(param)) {
break;
case "listarProvincia":
listarProvincia(request, response);
} else if ("listarDistrito".equals(param)) {
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;
}
}
}
......@@ -37,9 +52,8 @@ public class UbigeoServlet extends HttpServlet {
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"));
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.listarProvincia(datos);
pw.print(respuesta);
}
......@@ -47,9 +61,8 @@ public class UbigeoServlet extends HttpServlet {
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"));
JSONObject datos = new JSONObject(request.getParameter("json"));
JSONObject respuesta = service.listarDistrito(datos);
pw.print(respuesta);
}
......
......@@ -8,35 +8,33 @@ 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) {
public JSONObject listarPersona(JSONObject datos) {
JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray();
PreparedStatement psListarPersona = null;
ResultSet rsListarPersona = 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 + "%') ";
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;
if (!datos.getString("search").equals("")) {
condicion = " and (a.nombres like '%" + datos.getString("search") + "%' or a.apellidos like '%" + datos.getString("search") + "%') ";
}
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select top " + length + " "
= "select top " + datos.getString("length") + " "
+ "a.codigo, "
+ "a.dni, "
+ "a.apellidos, "
......@@ -45,10 +43,10 @@ public class PersonaSqlserverDAO implements PersonaDAO {
+ "a.correo, "
+ "a.estado "
+ "from persona a "
+ "where a.codigo not in (select top " + start + " b.codigo from persona b order by 1 desc) "
+ "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();
......@@ -63,32 +61,36 @@ public class PersonaSqlserverDAO implements PersonaDAO {
personaBean.setCorreo(rsListarPersona.getString(c++));
personaBean.setEstado(rsListarPersona.getString(c++));
JSONObject obj = new JSONObject(personaBean);
obj.put("item", numeroFilas++);
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();
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", draw);
jsonReturn.put("draw", datos.getString("draw"));
} catch (SQLException | JSONException e) {
jsonReturn.put("Error", "Error -> " + e.getMessage());
} 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();
}
if (rsListarPersona != null) {
rsListarPersona.close();
}
if (psCantidadPersonas != null) {
psCantidadPersonas.close();
}
if (psListarPersona != null) {
psListarPersona.close();
}
......@@ -96,7 +98,7 @@ public class PersonaSqlserverDAO implements PersonaDAO {
connection.close();
}
} catch (SQLException e) {
jsonReturn.put("Error", "Error inesperado -> " + e.getMessage() + " [" + e.getErrorCode() + "]");
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
......@@ -105,21 +107,21 @@ public class PersonaSqlserverDAO implements PersonaDAO {
@Override
public JSONObject registrarPersona(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = new JSONObject();
JSONObject jsonReturn = null;
int resultDni = 0;
int resultPersona = 0;
String base = "demojsoncrud";
PreparedStatement psInsertarPersona = null;
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 = ?";
PreparedStatement psGetDni = connection.prepareStatement(sqlGetDni);
psGetDni = connection.prepareStatement(sqlGetDni);
psGetDni.setString(1, datos.getString("dni"));
ResultSet rsGetDni = psGetDni.executeQuery();
rsGetDni = psGetDni.executeQuery();
rsGetDni.next();
resultDni = rsGetDni.getInt("dni");
......@@ -139,7 +141,7 @@ public class PersonaSqlserverDAO implements PersonaDAO {
response.setMessage("Registro correcto!");
response.setStatus(true);
} else {
response.setMessage("Error al registrar");
response.setMessage("No se pudo registrar a la persona");
response.setStatus(false); // ERROR
}
......@@ -151,28 +153,34 @@ public class PersonaSqlserverDAO implements PersonaDAO {
} 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 (connection != null) {
connection.close();
if (rsGetDni != null) {
rsGetDni.close();
}
if (psGetDni != null) {
psGetDni.close();
}
if (psInsertarPersona != null) {
psInsertarPersona.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al registrar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
jsonReturn = new JSONObject(response);
System.out.println(jsonReturn);
return jsonReturn;
}
@Override
public JSONObject editarPersona(JSONObject datos) {
JSONObject jsonReturn = new JSONObject();
JSONObject jsonReturn = null;
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
......@@ -209,6 +217,7 @@ public class PersonaSqlserverDAO implements PersonaDAO {
} 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) {
......@@ -218,8 +227,7 @@ public class PersonaSqlserverDAO implements PersonaDAO {
psEditarPersona.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
......@@ -231,7 +239,7 @@ public class PersonaSqlserverDAO implements PersonaDAO {
@Override
public JSONObject cambiarEstado(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = new JSONObject();
JSONObject jsonReturn = null;
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
......@@ -261,17 +269,18 @@ public class PersonaSqlserverDAO implements PersonaDAO {
} 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();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
System.err.println("Error: ha ocurrido un error al intentar cerrar las conexiones y/o liberacion de recursos -> " + e.getMessage());
}
}
......
/*
* 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,15 +10,11 @@ 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();
JSONObject jsonReturn = null;
JSONArray data = new JSONArray();
PreparedStatement psListarDepartamento = null;
ResultSet rsListarDepartamento = null;
......@@ -60,6 +51,7 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
} 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) {
......@@ -72,21 +64,19 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
connection.close();
}
} catch (SQLException e) {
response.setMessage("Error al listarDepartamento -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
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();
JSONObject jsonReturn = null;
JSONArray data = new JSONArray();
PreparedStatement psListarProvincia = null;
ResultSet rsListarProvincia = null;
......@@ -125,6 +115,7 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
} 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) {
......@@ -137,20 +128,18 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
connection.close();
}
} catch (SQLException e) {
response.setMessage("Error al listarProvincia -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
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();
JSONObject jsonReturn = null;
JSONArray data = new JSONArray();
PreparedStatement psListarDistrito = null;
ResultSet rsListarDistrito = null;
......@@ -189,6 +178,7 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
} 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) {
......@@ -201,14 +191,11 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
connection.close();
}
} catch (SQLException e) {
response.setMessage("Error al listarDistrito -> " + e.getMessage() + " Error code [" + e.getErrorCode() + "].");
response.setStatus(false);
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;
}
}
......@@ -10,7 +10,12 @@ public class ResponseHelper implements Serializable {
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() {
......
/**
* 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
......@@ -52,7 +15,7 @@ let createSelectOptions = (obj, valueName, textName) => {
}
let customSwal = {
alert (title, text, type) {
alert(title, text, type) {
let colors = {
success: '#66BB6A',
error: '#EF5350',
......@@ -92,35 +55,15 @@ let getClosest = (elem, selector) => {
function (s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length
while (--i >= 0 && matches.item(i) !== this) {}
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
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) {
function stripHtml(value) {
// remove html tags and space chars
return value.replace(/<.[^<>]*?>/g, ' ').replace(/&nbsp;|&#160;/gi, ' ')
// remove numbers and punctuation
......@@ -57,7 +57,7 @@ let jqueryValidateConfig = () => {
})
}
let persona = {
listar () {
listar() {
let txtCriterioBusqueda = $('#txt-busqueda').val().trim()
return new Promise((resolve) => {
$('#tbl-persona').DataTable().destroy()
......@@ -136,18 +136,26 @@ let persona = {
})
})
},
cambiarEstado (datos) {
cambiarEstado(datos) {
return new Promise((resolve, reject) => {
fetchSo('../PersonaServlet?accion=cambiarEstado', datos)
.then((data) => {
$.ajax({
url: '../PersonaServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'cambiarEstado',
json: JSON.stringify(datos)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
})
.catch((data) => {
reject(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al cambiar estado")
}
})
})
},
registrar () {
registrar() {
let json = {
dni: $('#txt_numero_documento').val().trim(),
apellidos: $('#txt_apellidos').val().trim(),
......@@ -156,6 +164,22 @@ let persona = {
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)
......@@ -165,7 +189,7 @@ let persona = {
})
})
},
editar () {
editar() {
let json = {
apellidos: $('#txt_apellidos_editar').val().trim(),
nombres: $('#txt_nombres_editar').val().trim(),
......@@ -174,12 +198,20 @@ let persona = {
codigo: localStorage.getItem('codigoPersona')
}
return new Promise((resolve, reject) => {
fetchSo('../PersonaServlet?accion=editarPersona', json)
.then((data) => {
$.ajax({
url: '../PersonaServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'editarPersona',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
})
.catch((data) => {
reject(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al editar persona")
}
})
})
}
......
let ubigeo = {
consultarDepartamento () {
consultarDepartamento() {
return new Promise((resolve, reject) => {
fetchSo('../UbigeoServlet?accion=listarDepartamento')
.then((data) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarDepartamento'
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
})
.catch((data) => {
reject(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar departamentos")
}
})
})
},
consultarProvincia (codigoDepartamento) {
consultarProvincia(codigoDepartamento) {
let json = {
codigoDepartamento: codigoDepartamento
}
return new Promise((resolve, reject) => {
fetchSo('../UbigeoServlet?accion=listarProvincia', json)
.then((data) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarProvincia',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
})
.catch((data) => {
reject(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar provincias")
}
})
})
},
consultarDistrito (codigoDepartamento, codigoProvincia) {
consultarDistrito(codigoDepartamento, codigoProvincia) {
let json = {
codigoProvincia: codigoProvincia,
codigoDepartamento: codigoDepartamento
}
return new Promise((resolve, reject) => {
fetchSo('../UbigeoServlet?accion=listarDistrito', json)
.then((data) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarDistrito',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
})
.catch((data) => {
reject(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar distritos")
}
})
})
}
......@@ -54,6 +78,8 @@ let asignarEventos = () => {
slProvincia.innerHTML = opt
})
.then(() => {
slDistrito.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
$('#select_distrito').selectpicker('refresh')
$('#select_provincia').selectpicker('refresh')
})
})
......
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