sistema web iglesia casa de gracia · 0 sistema web iglesia casa de gracia manual tecnico víctor...

94
0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web Junio 2018

Upload: others

Post on 21-Mar-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

0

Sistema Web Iglesia Casa De Gracia MANUAL TECNICO

Víctor Daniel Puch Sánchez

Adrián Donaldo Guevara Salomón

Diseño De Aplicaciones Web

Junio 2018

Page 2: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

1

Índice Indice .................................................................................................................................................. 1

Introducción ....................................................................................................................................... 2

Objetivo .............................................................................................................................................. 2

1. Requerimientos Técnicos: ....................................................................................................... 2

2. Herramientas utilizadas para el desarrollo: .......................................................................... 3

JAVA: .............................................................................................................................................. 3

JavaScript: ..................................................................................................................................... 3

JQuery ............................................................................................................................................ 4

MYSQL; .......................................................................................................................................... 4

APACHE ........................................................................................................................................ 4

NetBeans EE ................................................................................................................................. 5

JSP ................................................................................................................................................. 5

JSTL ............................................................................................................................................... 5

MySQL WorkBench ...................................................................................................................... 6

3. Instalación del Web Server ..................................................................................................... 7

4. Configuracion del Servidor ...................................................................................................... 9

5. Casos de Uso .......................................................................................................................... 10

6. Modelo Entidad Relación: ..................................................................................................... 13

7. Diccionario de Datos del Modelo Entidad Relación .......................................................... 13

Page 3: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

2

Tabla de Ilustraciones

Ilustración 1 Wamp Setup Wizard ...................................................................................... 7 Ilustración 2 License Agreement ........................................................................................ 7 Ilustración 3 Select Destination Location............................................................................ 8 Ilustración 4 Installing ........................................................................................................ 8 Ilustración 5 Installation Finished ....................................................................................... 9 Ilustración 6 Web app path ................................................................................................ 9 Ilustración 7 Caso de uso Administrador .......................................................................... 10 Ilustración 8 Uso Lider de Grupo ..................................................................................... 11 Ilustración 9 Uso Capturista ............................................................................................. 12 Ilustración 10 Modelo Entidad Relacion CDG .................................................................. 13

Tabla 1.- Attendance........................................................................................................ 13 Tabla 2 .- Congregants .................................................................................................... 14 Tabla 3 .- Events .............................................................................................................. 14 Tabla 4 .- Event Types ..................................................................................................... 15 Tabla 5 .- Groups ............................................................................................................. 15 Tabla 6 .- Id's ................................................................................................................... 15 Tabla 7 .- Membership ..................................................................................................... 15 Tabla 8 .- Users ............................................................................................................... 16

Page 4: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

2

Manual Tecnico

Introducción El presente documento técnico ha sido desarrollado con la finalidad de documentar el proceso de realización del Sistema para la iglesia Casa De Gracia, un proyecto realizado por dos estudiantes de Ingeniería Informá-tica de la Facultad de Ingeniería de la Universidad Veracruzana.

Este documento pretende mostrar las diferentes herramientas que se utilizaron para definir la planeación y realización del Sistema e informar acerca de las características de este Proyecto.

El manual técnico hacer referencia a información necesaria con el fin de orientar al personal en la concepción, planteamiento, programación e instalación del Sistema. Es de notar que este manual está orientado a perso-nal con conocimientos en sistemas y tecnologías de la información.

Objetivo Brindar la información necesaria para conocer la construcción del Sistema y realizar la correcta configuración del Sistema.

Representar la funcionalidad técnica de la estructura, diseño y definición del Sistema.

Definir claramente las herramientas necesarias para el correcto funcionamiento del Sistema.

Detallar la especificación de los requerimientos necesarios en hardware y software para la instalación del Sis-tema en el servidor.

Describir las herramientas utilizadas para el diseño y desarrollo del prototipo.

1. Requerimientos Técnicos:

Servidor:

Para el correcto funcionamiento del sistema ser requieren como mínimo las siguientes condiciones:

REQUERIMIENTOS MINIMOS DE HARDWARE

• Procesador 1 Core • Memoria RAM: 1GB • Disco Duro: 250Gb. • Conexión a Red Local

Page 5: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

3

Manual Tecnico

REQUERIMIENTOS MINIMOS DE SOFTWARE

• Privilegios de administrador • Sistema Operativo: Windows 7 en Adelante • Base de datos, Mysql 4.3 adelante • Estructura de la base de datos • Código fuente de la aplicación

Cliente:

Al ser un Sistema web, es compatible con cualquier Sistema operativo que cuente con soporte a un navega-dor web.

Se requiere Acceso a red local vía Wifi o Ethernet

Navegador Web Firefox/Explorer/Age/Safari

2. Herramientas utilizadas para el desarrollo:

JAVA: Java es un lenguaje de programación de propósito general, concurrente, orientado a objetos que fue diseñado específicamente para tener tan pocas dependencias de implementación como fuera posible. Su intención es permitir que los desarrolladores de aplicaciones escriban el programa una vez y lo ejecuten en cualquier dis-positivo (conocido en inglés como WORA, o "write once, run anywhere"), lo que quiere decir que el código que es ejecutado en una plataforma no tiene que ser recompilado para correr en otra. Java es, a partir de 2012, uno de los lenguajes de programación más populares en uso, particularmente para aplicaciones de cliente-servidor de web, con unos 10 millones de usuarios reportados

JavaScript: JavaScript (abreviado comúnmente JS) es un lenguaje de programación interpretado, dialecto del estándar ECMAScript. Se define como orientado a objetos,3 basado en prototipos, imperativo, débilmente tipado y diná-mico.

Se utiliza principalmente en su forma del lado del cliente (client-side), implementado como parte de un nave-gador web permitiendo mejoras en la interfaz de usuario y páginas web dinámicas4 aunque existe una forma de JavaScript del lado del servidor(Server-side JavaScript o SSJS). Su uso en aplicaciones externas a la web, por ejemplo en documentos PDF, aplicaciones de escritorio (mayoritariamente widgets) es también significa-tivo.

Page 6: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

4

Manual Tecnico

JQuery jQuery es una biblioteca multiplataforma de JavaScript, creada inicialmente por John Resig, que permite sim-plificar la manera de interactuar con los documentos HTML, manipular el árbol DOM, manejar eventos, desa-rrollar animaciones y agregar interacción con la técnica AJAX a páginas web. Fue presentada el 14 de enero de 2006 en el BarCamp NYC. jQuery es la biblioteca de JavaScript más utilizada.1

jQuery es software libre y de código abierto, posee un doble licenciamiento bajo la Licencia MIT y la Licencia Pública General de GNU v2, permitiendo su uso en proyectos libres y privados.2 jQuery, al igual que otras bi-bliotecas, ofrece una serie de funcionalidades basadas en JavaScript que de otra manera requerirían de mu-cho más código, es decir, con las funciones propias de esta biblioteca se logran grandes resultados en menos tiempo y espacio.

Las empresas Microsoft y Nokia anunciaron que incluirán la biblioteca en sus plataformas.3 Microsoft la aña-dirá en su IDE Visual Studio4 y la usará junto con los frameworks ASP.NET AJAX y ASP.NET MVC, mientras que Nokia los integrará con su plataforma Web Run-Time.

MYSQL; Es un manejador de Bases de Datos, el cual permite múltiples hilos y múltiples usuarios, fue desarrollado como software libre.

Aunque se puede usar sobre varias plataformas es muy utilizado sobre Windows. Es libre para uso en Servi-dores WEB.

Ofrece ventajas tales como fácil adaptación a diferentes entornos de desarrollo, Interacción con Lenguajes de Programación como JAVA, Java Script y fácil Integración con distintos sistemas operativos.

APACHE Es un Servidor WEB desarrollado por el grupo Apache. Su código fuente se puede distribuir y utilizar de forma libre. Está disponible para diferentes plataformas de Sistemas Operativos entre otros Windows, Linux, Mac y NetWare.

Ofrece ventajas tales como independencia de plataforma, haciendo posible el cambio de plataforma en cual-quier momento; creación de contenidos dinámicos, permitiendo crear sitios mediante lenguajes JAVA.

Además de ser libre su soporte técnico es accesible ya que existe una comunidad que está disponible en fo-ros y servidores de noticias, donde hay gran cantidad de usuarios disponibles para cuando surge algún pro-blema.

Page 7: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

5

Manual Tecnico

NetBeans EE NetBeans es un entorno de desarrollo integrado libre, hecho principalmente para el lenguaje de programación Java. Existe además un número importante de módulos para extenderlo. NetBeans IDE2 es un producto libre y gratuito sin restricciones de uso.

NetBeans es un proyecto de código abierto de gran éxito con una gran base de usuarios, una comunidad en constante crecimiento, y con cerca de 100 socios en todo el mundo. Sun MicroSystems fundó el proyecto de código abierto NetBeans en junio de 2000 y continúa siendo el patrocinador principal de los proyectos (Actual-mente Sun Microsystems es administrado por Oracle Corporation).

La plataforma NetBeans permite que las aplicaciones sean desarrolladas a partir de un conjunto de compo-nentes de software llamados módulos. Un módulo es un archivo Java que contiene clases de java escritas para interactuar con las APIs de NetBeans y un archivo especial (manifest file) que lo identifica como módulo. Las aplicaciones construidas a partir de módulos pueden ser extendidas agregándole nuevos módulos. De-bido a que los módulos pueden ser desarrollados independientemente, las aplicaciones basadas en la plata-forma NetBeans pueden ser extendidas fácilmente por otros desarrolladores de software.

JSP JavaServer Pages (JSP) es una tecnología que ayuda a los desarrolladores de software a crear páginas web dinámicas basadas en HTML y XML, entre otros tipos de documentos. JSP es similar a PHP, pero usa el len-guaje de programación Java.

Para desplegar y correr JavaServer Pages, se requiere un servidor web compatible con contenedores servlet como Apache Tomcat o Jetty.

TagLibs -> JSP -> Servidor Aplicaciones (Servlets) -> Cliente (Navegador)

El rendimiento de una página JSP es el mismo que tendría el servlet equivalente, ya que el código es compi-lado como cualquier otra clase Java. A su vez, la máquina virtual compilará dinámicamente a código de má-quina las partes de la aplicación que lo requieran. Esto hace que JSP tenga un buen desempeño y sea más eficiente que otras tecnologías web que ejecutan el código de una manera puramente interpretada.

La principal ventaja de JSP frente a otros lenguajes es que el lenguaje Java es un lenguaje de propósito gene-ral que excede el mundo web y que es apto para crear clases que manejen lógica de negocio y acceso a da-tos de una manera prolija. Esto permite separar en niveles las aplicaciones web, dejando la parte encargada de generar el documento HTML en el archivo JSP.

JSTL La tecnología JavaServer Pages Standard Tag Library (JSTL) es un componente de Java EE. Extiende las ya conocidas JavaServer Pages (JSP) proporcionando cuatro bibliotecas de etiquetas (Tag Libraries) con utilida-des ampliamente utilizadas en el desarrollo de páginas web dinámicas.

Page 8: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

6

Manual Tecnico

Estas bibliotecas de etiquetas extienden de la especificación de JSP (la cual a su vez extiende de la especifi-cación de Servlet). Su API permite además desarrollar bibliotecas propias de etiquetas.

Las bibliotecas englobadas en JSTL son:

• core: iteraciones, condicionales, manipulación de URL y otras funciones generales. • xml: para la manipulación de XML y para XML-Transformation. • sql: para gestionar conexiones a bases de datos. • fmt: para la internacionalización y formateo de las cadenas de caracteres como cifras.

MySQL WorkBench MySQL Workbench es una herramienta visual de diseño de bases de datos que integra desarrollo de soft-ware, Administración de bases de datos, diseño de bases de datos, creación y mantenimiento para el sistema de base de datos MySQL. Es el sucesor de DBDesigner 4 de fabFORCE.net, y reemplaza el anterior conjunto de software, MySQL GUI Tools Bundle

.

Libros de Programación Patterns of enterprise application architecture / Martin Fowler.

Copyright © 2003 by Pearson Education, Inc.

Design Patterns: Elements of reusable object-oriented software / Gamma, E; Helm, R; Johnson, R; Vlissides, J.

Copyright © 2003 by Pearson Education, Inc,

Page 9: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

7

Manual Tecnico

3. Instalación del Web Server Instalar el wampserver el cual se encuentra en la página: http://sourceforge.net/ Projects/wampserver/ una vez descargado, dar clic sobre él para iniciar la instalación. La instalación se debe hacer con una cuenta de Administrador o con derechos de administrador.

La primera ventana que aparecerá es la de bienvenida al Setup Wizard de la instalación, pulsa el botón Insta-lación y administración WampServer para continuar

Ilustración 1 Wamp Setup Wizard

Ilustración 2 License Agreement

Page 10: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

8

Manual Tecnico

Durante el proceso de instalación aparece el explorador de archivos para que selecciones el navegador que vas a utilizar por defecto cada vez que algunas de las herramientas incluidas en WampServer, como por ejem-plo PhpMyAdmin, por defecto WampServer utilizara el navegador Internet Explorer de Microsoft.

Selecciona el destino de la instalación.

Ilustración 3 Select Destination Location

Pulsa el botón Instalación y administración WampServer para continuar.

Ilustración 4 Installing

Al finalizar aparecerá una pantalla como esta, que muestra las herramientas instaladas:

Page 11: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

9

Manual Tecnico

Ilustración 5 Installation Finished

4. Configuracion del Servidor

Se coloca la carpeta llamada CDGWebApplication en la ruta donde se encuentra instalado el servidor normal-mente es: C:\wamp\www

Ilustración 6 Web app path

Luego se configura la base de datos con los siguientes parámetros.

Configurar la base de datos

aplication\database.php

$db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'root'; $db['default']['password'] = '12345a'; $db['default']['database'] = 'SistemaConta'; $db['default']['dbdriver'] = 'mysql';

Page 12: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

10

Manual Tecnico

5. Casos de Uso

Para el sistema se va a definir tres roles o tipos de usuarios que interactuarán con el sistema de información de diferentes modos.

Administrador: Es el nivel de mayor jerarquía, es capaz de registrar, modificar y cambiar el estatus de los re-gistros (congregantes, grupos, eventos y usuarios) así como vista completa de estos, puede asignar otros usuarios administradores o de menor jerarquía.

Ilustración 7 Caso de uso Administrador

Page 13: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

11

Manual Tecnico

Líder de Grupo: Este nivel tiene acceso de registrar, modificar y cambiar el estatus de congregantes, tiene una vista completa de estos, es capaz de modificar el grupo que le fue asignado por el administrador, crear even-tos para su propio grupo, así como verlos y modificarlos además de modificar su usuario, pero siendo incapaz de alterar sus permisos.

Ilustración 8 Uso Lider de Grupo

Page 14: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

12

Manual Tecnico

Capturista: este nivel es el más limitado, se limita a registrar, modificar y cambiar el estatus de congregantes, tiene acceso a la vista completa de congregantes y es capaz de modificar su usuario, pero sin alterar sus per-misos.

Ilustración 9 Uso Capturista

Page 15: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

13

Manual Tecnico

6. Modelo Entidad Relación:

Ilustración 10 Modelo Entidad Relacion CDG

7. Diccionario de Datos del Modelo Entidad Relación A continuación, se presentan la definiciones y descripciones de los datos que van a ser utilizados en el sis-tema. Inicialmente se nombra cada entidad con su descripción y tabla con los campos y sus características especiales.

Tabla 1.- Attendance

Atributo Tipo de dato PK FK Obligatorio

attendance_id INT X X

event_id INT X X

congregant_id INT X X

Page 16: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

14

Manual Tecnico

Tabla 2 .- Congregants

Atributo Tipo de dato PK FK Obligatorio

congregant_id INT X X

status INT X

name VARCHAR(50) X

first_last_name VARCHAR(25) X

second_last_name VARCHAR(25)

address VARCHAR(100)

phone VARCHAR(15)

email VARCHAR(50)

birthday DATE

gender INT

civil_status INT

type INT X

baptized BOOLEAN

Tabla 3 .- Events

Atributo Tipo de dato PK FK Obligatorio

event_id INT X X

status INT X

date DATE X

group_id INT X

event_type_id INT X X

Page 17: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

15

Manual Tecnico

Tabla 4 .- Event Types

Atributo Tipo de dato PK FK Obligatorio

event_type_id INT X X

status INT X

name VARCHAR(50) X

Tabla 5 .- Groups

Atributo Tipo de dato PK FK Obligatorio

group_id INT X X

status INT X

name VARCHAR(50) X

Tabla 6 .- Id's

Atributo Tipo de dato PK FK Obligatorio

name VARCHAR(25) X X

next_id INT X

Tabla 7 .- Membership

Atributo Tipo de dato PK FK Obligatorio

membership_id INT X X

group_id INT X X

congregant_id INT X X

Page 18: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Sistema Web Casa De Gracia

16

Manual Tecnico

Tabla 8 .- Users

Atributo Tipo de dato PK FK Obligatorio

user_id INT X X

status INT X

name VARCHAR(45) X

password VARCHAR(45) X

level INT X

group_id INT X

Page 19: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

Codigo

PACKAGE PRESENTATIONpackage Presentation;

import DataSource.UserGateway;import java.io.IOException;import javax.servlet.RequestDispatcher;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

/** * * @author adrian */abstract class AbstractCommand implements WebCommand { protected ServletContext context; protected HttpServletRequest request; protected HttpServletResponse response;

@Override public void init(ServletContext context, HttpServletRequest request, HttpServletResponse response) { this.context = context; this.request = request; this.response = response; } protected void forward(String target) throws ServletException, IOException { RequestDispatcher dispatcher = context.getRequestDispatcher(target); dispatcher.forward(request, response); } protected boolean idIsPresent() { return request.getParameter("id") != null; } protected long getId(){ return Long.parseLong(request.getParameter("id")); } protected UserGateway getUser() { return (UserGateway) request.getSession().getAttribute("user"); }

Page 20: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

package Presentation;

import DataSource.DataSourceException;import Domain.CongregantService;import java.io.IOException;import java.util.Date;import java.text.ParseException;import java.text.SimpleDateFormat;import javax.servlet.ServletException;

/** * * @author adrian */class CreateOrModifyCongregantCommand extends StateChangeCommand {

@Override protected void performChanges() throws ServletException, IOException { createBuilder() .setName(request.getParameter("name")) .setFirstLastName(request.getParameter("firstLastName")) .setSecondLastName(request.getParameter("secondLastName")) .setAddress(request.getParameter("address")) .setPhone(request.getParameter("phone")) .setEmail (request.getParameter("email")) .setGender(Integer.parseInt(request.getParameter("gender"))) .setCivilStatus(Integer.parseInt(request.getParameter("civilStatus"))) .setType(Integer.parseInt(request.getParameter("type"))) .setBaptized(parseBaptized(request.getParameter("baptized"))) .setBirthday( parseBirthday(request.getParameter("birthday"))); } private CongregantService createBuilder() throws DataSourceException { if(idIsPresent()) return new CongregantService(getId()); else return new CongregantService(); } private Date parseBirthday(String birthdayParameter) throws IOException { try { return new Date(new SimpleDateFormat("yyyy-MM-dd").parse(birthdayParameter).getTime()); } catch (ParseException ex) { throw new IOException("Incorrect birthday format, expected format: yyyy-MM-dd");

Page 21: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

} } private boolean parseBaptized(String baptizedParameter){ return baptizedParameter!=null; }}

package Presentation;

import java.util.ArrayList;import java.util.List;

/** * * @author adrian */abstract class CreateOrModifyCongregantSetCommand extends StateChangeCommand { protected List<Long> congregantIds() { List<Long> memberIds = new ArrayList<>(); for(int congregantIndex = 0; congregantIndex < congregantListSize(); congregantIndex++) if(isInTheSet(congregantIndex)) memberIds.add(congregantId(congregantIndex)); return memberIds; }

private boolean isInTheSet(int congregantIndex) { return request.getParameter("congregant" + congregantIndex) != null; }

private long congregantId(int congregantIndex) { return Long.parseLong(request.getParameter("congregant" + congregantIndex)); }

private int congregantListSize() { return Integer.parseInt(request.getParameter("congregantListSize")); }}

package Presentation;

import DataSource.DataSourceException;import Domain.EventService;import java.io.IOException;import java.util.Date;import java.text.ParseException;import java.text.SimpleDateFormat;

Page 22: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

import javax.servlet.ServletException;

/** * * @author adrian */class CreateOrModifyEventCommand extends CreateOrModifyCongregantSetCommand {

@Override protected void performChanges() throws ServletException, IOException { createBuilder() .setDate(date()) .setAttendance(congregantIds()) .setGroupId(groupId()) .setType(type()); } private EventService createBuilder() throws DataSourceException { if(idIsPresent()) return new EventService(getId()); else return new EventService(); } private Date date() throws IOException { try { String date = request.getParameter("date"); return new Date(new SimpleDateFormat("yyyy-MM-dd").parse(date).getTime()); } catch (ParseException ex) { throw new IOException("Incorrect date format, expected format: yyyy-MM-dd"); } } private Long groupId() { if(request.getParameter("groupId") == null) return getUser().getGroupId(); String groupId = request.getParameter("groupId"); return Long.parseLong(groupId); } private int type() { String type = request.getParameter("type"); return Integer.parseInt(type); }}

package Presentation;

import DataSource.DataSourceException;

Page 23: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

import Domain.GroupService;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */class CreateOrModifyGroupCommand extends CreateOrModifyCongregantSetCommand {

@Override protected void performChanges() throws ServletException, IOException { createBuilder() .setName(groupName()) .setMemberships(congregantIds()); } private GroupService createBuilder() throws DataSourceException { if(idIsPresent()) return new GroupService(getId()); else return new GroupService(); } private String groupName() { return request.getParameter("name"); }}

package Presentation;

import DataSource.DataSourceException;import Domain.UserBuilder;import Domain.UserNotFound;import Domain.UsersService;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */class CreateOrModifyUserCommand extends StateChangeCommand {

@Override protected void performChanges() throws ServletException, IOException { try { new UsersService().findUser(userName()); request.getSession().setAttribute("error", "El usuario ya existe");

Page 24: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

response.sendRedirect("App?command=ViewAddOrEditUserForm"); } catch(UserNotFound ex) { saveUser(); response.sendRedirect("App?command=ViewAllOrSingleUser"); } } private void saveUser() throws DataSourceException { createBuilder() .setName(userName()) .setPassword(password()) .setGroupId(groupId()) .setLevel(level()); }

private UserBuilder createBuilder() throws DataSourceException { if(idIsPresent()) return new UserBuilder(getId()); else return new UserBuilder(); }

private String userName() { return request.getParameter("user"); }

private String password() { return request.getParameter("pass1"); }

private long groupId() { if(request.getParameter("grupo") == null) return 0; String groupId = request.getParameter("grupo"); return Long.parseLong(groupId); }

private int level() { String level = request.getParameter("level"); return Integer.parseInt(level); }}

package Presentation;

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

Page 25: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

/** * * @author adrian */public class DisableCongregantCommand extends StateChangeCommand {

@Override public void performChanges() throws ServletException, IOException { FindersFactory .congregantsFinder() .find(getId()) .setStatus(0); response.sendRedirect("App?command=ViewAllOrSingleCongregant"); }}

package Presentation;

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author victor-puch */public class DisableEventCommand extends StateChangeCommand{ @Override void performChanges() throws ServletException, IOException { FindersFactory .eventsFinder() .find(getId()) .setStatus(0); response.sendRedirect("App?command=ViewAllOrSingleEvent"); }}

package Presentation;

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */public class DisableGroupCommand extends StateChangeCommand {

Page 26: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

@Override void performChanges() throws ServletException, IOException { FindersFactory .groupsFinder() .find(getId()) .setStatus(0); response.sendRedirect("App?command=ViewAllOrSingleGroup"); }}

package Presentation;

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */public class DisableUserCommand extends StateChangeCommand {

@Override void performChanges() throws ServletException, IOException { FindersFactory .usersFinder() .find(getId()) .setStatus(0); response.sendRedirect("App?command=ViewAllOrSingleUser"); } }

package Presentation;

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */public class EnableCongregantCommand extends StateChangeCommand {

@Override void performChanges() throws ServletException, IOException { FindersFactory .congregantsFinder()

Page 27: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

.find(getId()) .setStatus(1); response.sendRedirect("App?command=ViewAllOrSingleCongregant"); }}package Presentation;

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author victor-puch */public class EnableEventCommand extends StateChangeCommand { @Override void performChanges() throws ServletException, IOException { FindersFactory .eventsFinder() .find(getId()) .setStatus(1); response.sendRedirect("App?command=ViewAllOrSingleEvent"); }}

package Presentation;

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */public class EnableGroupCommand extends StateChangeCommand {

@Override void performChanges() throws ServletException, IOException { FindersFactory .groupsFinder() .find(getId()) .setStatus(1); response.sendRedirect("App?command=ViewAllOrSingleGroup"); }}

package Presentation;

Page 28: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

import DataSource.FindersFactory;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */public class EnableUserCommand extends StateChangeCommand {

@Override void performChanges() throws ServletException, IOException { FindersFactory .usersFinder() .find(getId()) .setStatus(1); response.sendRedirect("App?command=ViewAllOrSingleUser"); }}

package Presentation;

import Domain.IncorrectPassword;import Domain.UserNotFound;import DataSource.DataSourceException;import DataSource.UserGateway;import Domain.UsersService;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */class LoginCommand extends AbstractCommand{

@Override public void process() throws ServletException, IOException { try { UsersService usersService = new UsersService(); UserGateway user = getUser(usersService); request.getSession().setAttribute("user", user); forward("/index.jsp"); } catch (DataSourceException ex) { request.getSession().setAttribute("error", "Error de la fuente de datos"); response.sendRedirect("App?command=ViewLoginForm"); } catch (UserNotFound ex) { request.getSession().setAttribute("error", "Usuario no encontrado");

Page 29: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

response.sendRedirect("App?command=ViewLoginForm"); } catch (IncorrectPassword ex) { request.getSession().setAttribute("error", "Contraseña Invalida"); response.sendRedirect("App?command=ViewLoginForm"); } } private UserGateway getUser(UsersService usersService) throws DataSourceException, UserNotFound, IncorrectPassword { String userName = request.getParameter("userName"); String password = request.getParameter("password"); return usersService.findValidUser(userName, password); }}

package Presentation;

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpSession;

/** * * @author victor-puch */class LogoutCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) session.invalidate(); forward("/index.jsp"); }}

package Presentation;

import DataSource.AppSesionManager;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */abstract class StateChangeCommand extends AbstractCommand {

@Override

Page 30: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public void process() throws ServletException, IOException { performChanges(); AppSesionManager.getUnitOfWork().commit(); } abstract void performChanges() throws ServletException, IOException; }

package Presentation;

import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */public class UnknownCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { forward("/WEB-INF/unknown.jsp"); }}

package Presentation;

import DataSource.CongregantGateway;import DataSource.DataSourceException;import Domain.CongregantService;import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */class ViewAddOrEditCongregantFormCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { if(idIsPresent()) { request.setAttribute("congregant", getCongregant()); forward("/WEB-INF/editCongregantForm.jsp"); } else forward("/WEB-INF/addCongregantForm.jsp"); }

Page 31: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

private CongregantGateway getCongregant() throws DataSourceException { return new CongregantService(getId()).getCongregant(); }}

package Presentation;

import DataSource.CongregantGateway;import DataSource.DataSourceException;import DataSource.EventGateway;import DataSource.FindersFactory;import Domain.EventService;import Domain.GroupService;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;

/** * * @author adrian */public class ViewAddOrEditEventFormCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { if(idIsPresent()) { EventService eventService = new EventService(getId()); EventGateway event = eventService.getEvent(); List<CongregantGateway> assistans = eventService.getAssistans(); List<CongregantGateway> noAssistans = eventService.getNoAssistans(); int congregantListSize = assistans.size() + noAssistans.size(); request.setAttribute("event", event); request.setAttribute("congregantList1", assistans); request.setAttribute("congregantList2", noAssistans); request.setAttribute("congregantListSize", congregantListSize); forward("/WEB-INF/editEventForm.jsp"); } else { List<CongregantGateway> congregantList = getCongregantList(); int congregantListSize = congregantList.size(); request.setAttribute("congregantList", congregantList); request.setAttribute("congregantListSize", congregantListSize); forward("/WEB-INF/addEventForm.jsp"); } } private List<CongregantGateway> getCongregantList() throws DataSourceException { Long groupId = getUser().getGroupId(); if(groupId == null) return getAllCongregant();

Page 32: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

else return getMembers(groupId); } private List<CongregantGateway> getMembers(long groupId) throws DataSourceException { return new GroupService(groupId).getMembers(); } private List<CongregantGateway> getAllCongregant() throws DataSourceException { return FindersFactory.congregantsFinder().findAll(); }}

package Presentation;

import DataSource.CongregantGateway;import DataSource.FindersFactory;import DataSource.GroupGateway;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import Domain.CongregantsFinder;import Domain.GroupService;

/** * * @author adrian */class ViewAddOrEditGroupFormCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { if(idIsPresent()) { GroupService groupService = new GroupService(getId()); GroupGateway group = groupService.getGroup(); List<CongregantGateway> members = groupService.getMembers(); List<CongregantGateway> noMembers = groupService.getNoMembers(); int congregantListSize = members.size() + noMembers.size(); request.setAttribute("group", group); request.setAttribute("congregantList1", members); request.setAttribute("congregantList2", noMembers); request.setAttribute("congregantListSize", congregantListSize); forward("/WEB-INF/editGroupForm.jsp"); } else { CongregantsFinder congregnatFinder = FindersFactory.congregantsFinder(); List<CongregantGateway> congregantList = congregnatFinder.findAll(); int congregantListSize = congregantList.size(); request.setAttribute("congregantList", congregantList); request.setAttribute("congregantListSize", congregantListSize);

Page 33: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

forward("/WEB-INF/addGroupForm.jsp"); } }}

package Presentation;

import DataSource.DataSourceException;import DataSource.FindersFactory;import DataSource.GroupGateway;import DataSource.UserGateway;import Domain.GroupsFinder;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;

/** * * @author adrian */class ViewAddOrEditUserFormCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { if(idIsPresent()) { GroupsFinder groupsFinder = FindersFactory.groupsFinder(); List<GroupGateway> groupList = groupsFinder.findAll(); request.setAttribute("groupList", groupList); request.setAttribute("user", getUser(getId())); forward("/WEB-INF/editUserForm.jsp"); } else{ GroupsFinder groupsFinder = FindersFactory.groupsFinder(); List<GroupGateway> groupList = groupsFinder.findAll(); request.setAttribute("groupList", groupList); forward("/WEB-INF/addUserForm.jsp"); } } private UserGateway getUser(long id) throws DataSourceException { return FindersFactory .usersFinder() .find(id); }}

package Presentation;

import DataSource.CongregantGateway;import DataSource.DataSourceException;

Page 34: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

import DataSource.FindersFactory;import Domain.CongregantService;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;

/** * * @author adrian */class ViewAllOrSingleCongregantCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { if(idIsPresent()) { request.setAttribute("singleCongregant", getCongregant()); forward("/WEB-INF/singleCongregant.jsp"); } else { request.setAttribute("congregantList", getCongregants()); forward("/WEB-INF/allCongregants.jsp"); } } private CongregantGateway getCongregant() throws DataSourceException { return new CongregantService(getId()).getCongregant(); } private List<CongregantGateway> getCongregants() throws DataSourceException { return FindersFactory.congregantsFinder().findAll(); }}

package Presentation;

import DataSource.EventGateway;import Domain.EventsFinder;import DataSource.FindersFactory;import Domain.EventService;import Domain.GroupService;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;/** * * @author victor-puch */public class ViewAllOrSingleEventCommand extends AbstractCommand{ @Override

Page 35: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public void process() throws ServletException, IOException { if(idIsPresent()) { EventService eventService = new EventService(getId()); request.setAttribute("singleEvent", eventService.getEvent()); request.setAttribute("congregantList", eventService.getAssistans()); forward("/WEB-INF/singleEvent.jsp"); } else { EventsFinder eventsFinder = FindersFactory.eventsFinder(); List<EventGateway> eventList = eventsFinder.findAll(); request.setAttribute("eventList", eventList); forward("/WEB-INF/allEvents.jsp"); } }}

package Presentation;

import DataSource.EventGateway;import Domain.EventsFinder;import DataSource.FindersFactory;import Domain.EventService;import Domain.GroupService;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;/** * * @author victor-puch */public class ViewAllOrSingleEventCommand extends AbstractCommand{ @Override public void process() throws ServletException, IOException { if(idIsPresent()) { EventService eventService = new EventService(getId()); request.setAttribute("singleEvent", eventService.getEvent()); request.setAttribute("congregantList", eventService.getAssistans()); forward("/WEB-INF/singleEvent.jsp"); } else { EventsFinder eventsFinder = FindersFactory.eventsFinder(); List<EventGateway> eventList = eventsFinder.findAll(); request.setAttribute("eventList", eventList); forward("/WEB-INF/allEvents.jsp"); } }}

package Presentation;

Page 36: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

import DataSource.FindersFactory;import DataSource.UserGateway;import Domain.UsersFinder;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;

/** * * @author victor-puch */class ViewAllOrSingleUserCommand extends AbstractCommand { @Override public void process() throws ServletException, IOException { UsersFinder usersFinder = FindersFactory.usersFinder(); List<UserGateway> usersList = usersFinder.findAll(); request.setAttribute("userList", usersList); forward("/WEB-INF/allUsers.jsp"); } }

package Presentation;

import java.io.IOException;import javax.servlet.ServletException;

/** * * @author adrian */class ViewLoginFormCommand extends AbstractCommand {

@Override public void process() throws ServletException, IOException { forward("/WEB-INF/loginForm.jsp"); }}

package Presentation;

import java.io.IOException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

Page 37: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

/** * * @author adrian */interface WebCommand {

void init(ServletContext context, HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException; void process()throws ServletException, IOException; }

package Presentation;

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

/** * * @author adrian */@WebServlet(name = "WebHandler", urlPatterns = {"/App"})public class WebHandler extends HttpServlet {

/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebCommand command = getCommand(request); command.init(getServletContext(), request, response); command.process(); } private WebCommand getCommand(HttpServletRequest request) throws ServletException { try { return (WebCommand) getCommandClass(request).newInstance(); } catch (IllegalAccessException | InstantiationException ex) {

Page 38: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

throw new ServletException("Unable to instanciate the command", ex); } } private Class getCommandClass(HttpServletRequest request) { try { return Class.forName(getCommandClassPath(request)); } catch(ClassNotFoundException ex) { return UnknownCommand.class; } } private String getCommandClassPath(HttpServletRequest request) { return "Presentation." + getCommandName(request) + "Command"; } private String getCommandName(HttpServletRequest request) { return request.getParameter("command"); }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left toedit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

Page 39: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

/** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }

PACKAGE DOMAIN

package Domain;

import DataSource.AttendanceGateway;import DataSource.DataSourceException;import DataSource.RowFinder;import java.util.List;

/** * * @author adrian */public interface AttendanceFinder extends RowFinder<AttendanceGateway> {

List<AttendanceGateway> findByCongregant(long congregantId) throws DataSourceException; List<AttendanceGateway> findByEvent(long eventId) throws DataSourceException;}

package Domain;

import DataSource.CongregantGateway;import DataSource.DataSourceException;import DataSource.FindersFactory;import DataSource.RowsFactory;import java.util.Date;

/** * * @author adrian */public class CongregantService { private CongregantGateway congregant;

Page 40: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public CongregantService(long congregantId) throws DataSourceException { congregant = FindersFactory.congregantsFinder().find(congregantId); } public CongregantService() throws DataSourceException { congregant = RowsFactory.congregantRow(1, "", "", "", "", "", "", new Date(), 0, 0, 0, false); }

public CongregantService setName(String name) { congregant.setName(name); return this; }

public CongregantService setFirstLastName(String firstLastName) { congregant.setFirstLastName(firstLastName); return this; }

public CongregantService setSecondLastName(String secondLastName) { congregant.setSecondLastName(secondLastName); return this; }

public CongregantService setAddress(String address) { congregant.setAddress(address); return this; }

public CongregantService setPhone(String phone) { congregant.setPhone(phone); return this; }

public CongregantService setEmail(String email) { congregant.setEmail(email); return this; }

public CongregantService setBirthday(Date birthday) { congregant.setBirthday(birthday); return this; }

public CongregantService setGender(int gender) { congregant.setGender(gender); return this; }

public CongregantService setCivilStatus(int civilStatus) {

Page 41: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

congregant.setCivilStatus(civilStatus); return this; } public CongregantService setType(int type) { congregant.setType(type); return this; } public CongregantService setBaptized(boolean baptized) { congregant.setBaptized(baptized); return this; }

public CongregantGateway getCongregant() { return congregant; }}

package Domain;

import DataSource.CongregantGateway;import DataSource.DataRowFinder;import DataSource.DataSourceException;import java.util.List;

/** * * @author adrian */public interface CongregantsFinder extends DataRowFinder<CongregantGateway> { List<CongregantGateway> findByGroup(long groupId) throws DataSourceException; List<CongregantGateway> findByEvent(long eventId) throws DataSourceException; }

package Domain;

/** * * @author adrian */public class DomainException extends Exception {

public DomainException() { }

public DomainException(String message) { super(message);

Page 42: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

public DomainException(String message, Throwable cause) { super(message, cause); }

public DomainException(Throwable cause) { super(cause); }

public DomainException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }

package Domain;

import DataSource.CongregantGateway;import DataSource.DataSourceException;import DataSource.EventGateway;import DataSource.FindersFactory;import DataSource.RowsFactory;import java.util.Date;import java.util.List;

/** * * @author adrian */public class EventService { private EventGateway event; public EventService(long eventId) throws DataSourceException { event = FindersFactory.eventsFinder().find(eventId); } public EventService() throws DataSourceException { event = RowsFactory.eventRow(1, new Date(), null, 1); }

public EventService setDate(Date date) { event.setDate(date); return this; }

public EventService setGroupId(Long groupId) {

Page 43: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

event.setGroupId(groupId); return this; }

public EventService setType(int type) { event.setType(type); if(type != 2) event.setGroupId(null); return this; } public EventGateway getEvent() throws DataSourceException { return event; } public List<CongregantGateway> getAssistans() throws DataSourceException { return FindersFactory .congregantsFinder() .findByEvent(event.getId()); } public List<CongregantGateway> getNoAssistans() throws DataSourceException { List<CongregantGateway> noAttendance = FindersFactory .congregantsFinder() .findAll(); noAttendance.removeAll(getAssistans()); return noAttendance; } public EventService setAttendance(List<Long> congregantIds) throws DataSourceException { removeOldAttendance(); createNewAttendance(congregantIds); return this; } private void removeOldAttendance() throws DataSourceException { FindersFactory .attendanceFinder() .findByEvent(event.getId()) .forEach(attendance -> attendance.remove()); } private void createNewAttendance(List<Long> congregantIds) throws DataSourceException { for(Long congregantId : congregantIds) RowsFactory.attendanceRow(event.getId(), congregantId); }}

package Domain;

Page 44: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

import DataSource.DataRowFinder;import DataSource.DataSourceException;import DataSource.EventGateway;import java.util.List;

/** * * @author adrian */public interface EventsFinder extends DataRowFinder<EventGateway> { List<EventGateway> findByCongregant(long congregantId) throws DataSourceException; }

package Domain;

import DataSource.CongregantGateway;import DataSource.DataSourceException;import DataSource.FindersFactory;import DataSource.GroupGateway;import DataSource.RowsFactory;import java.util.List;

/** * * @author adrian */public class GroupService { private GroupGateway group; public GroupService(long groupId) throws DataSourceException { group = FindersFactory.groupsFinder().find(groupId); } public GroupService() throws DataSourceException { group = RowsFactory.groupRow(1, ""); }

public GroupService setName(String name) { group.setName(name); return this; } public GroupGateway getGroup() throws DataSourceException { return FindersFactory .groupsFinder()

Page 45: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

.find(group.getId()); } public List<CongregantGateway> getMembers() throws DataSourceException { return FindersFactory .congregantsFinder() .findByGroup(group.getId()); } public List<CongregantGateway> getNoMembers() throws DataSourceException { List<CongregantGateway> noMembers = FindersFactory .congregantsFinder() .findAll(); noMembers.removeAll(getMembers()); return noMembers; } public GroupService setMemberships(List<Long> memberIds) throws DataSourceException { removeOldMemberships(); createNewMemberships(memberIds); return this; } private void removeOldMemberships() throws DataSourceException { FindersFactory .membershipsFinder() .findByGroup(group.getId()) .forEach(membership -> membership.remove()); } private void createNewMemberships(List<Long> memberIds) throws DataSourceException { for(Long memberId : memberIds) RowsFactory.membershipRow(group.getId(), memberId); }}

package Domain;

import DataSource.DataRowFinder;import DataSource.DataSourceException;import DataSource.GroupGateway;import java.util.List;

/** * * @author adrian */public interface GroupsFinder extends DataRowFinder<GroupGateway> {

Page 46: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

List<GroupGateway> findByCongregant(long congregantId) throws DataSourceException; }

package Domain;

/** * * @author adrian */public class IncorrectPassword extends DomainException {

public IncorrectPassword() { }

public IncorrectPassword(String message) { super(message); }

public IncorrectPassword(String message, Throwable cause) { super(message, cause); }

public IncorrectPassword(Throwable cause) { super(cause); }

public IncorrectPassword(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }

package Domain;

import DataSource.DataSourceException;import DataSource.MembershipsGateway;import DataSource.RowFinder;import java.util.List;

/** * * @author adrian */public interface MembershipsFinder extends RowFinder<MembershipsGateway> { List<MembershipsGateway> findByCongregant(long congregantId) throws DataSourceException;

Page 47: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

List<MembershipsGateway> findByGroup(long groupId) throws DataSourceException; }

package Domain;

import DataSource.DataSourceException;import DataSource.FindersFactory;import DataSource.RowsFactory;import DataSource.UserGateway;

/** * * @author adrian */public class UserBuilder { private UserGateway user; public UserBuilder(long userId) throws DataSourceException { user = FindersFactory.usersFinder().find(userId); } public UserBuilder() throws DataSourceException { user = RowsFactory.userRow(1, "", "", 0, null); }

public UserBuilder setPassword(String password) { user.setPassword(password); return this; }

public UserBuilder setLevel(int level) { user.setLevel(level); if(level != 3) user.setGroupId(null); return this; }

public UserBuilder setGroupId(long groupId) { user.setGroupId(groupId); user.setLevel(3); return this; } public UserBuilder setName(String name) { user.setName(name); return this; }

Page 48: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

package Domain;

/** * * @author adrian */public class UserNotFound extends DomainException {

public UserNotFound() { }

public UserNotFound(String message) { super(message); }

public UserNotFound(String message, Throwable cause) { super(message, cause); }

public UserNotFound(Throwable cause) { super(cause); }

public UserNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }

package Domain;

import DataSource.DataRowFinder;import DataSource.UserGateway;

/** * * @author adrian */public interface UsersFinder extends DataRowFinder<UserGateway> { }

Page 49: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

package Domain;

import DataSource.DataSourceException;import DataSource.FindersFactory;import DataSource.UserGateway;

/** * * @author adrian */public class UsersService { public UserGateway findValidUser(String userName, String password) throws UserNotFound, DataSourceException, IncorrectPassword { UserGateway user = findUser(userName); if(isPasswordValid(user, password)) return user; throw new IncorrectPassword(); } public UserGateway findUser(String userName) throws UserNotFound, DataSourceException { for(UserGateway user : FindersFactory.usersFinder().findAll()) if(user.getName().equalsIgnoreCase(userName)) return user; throw new UserNotFound(); } private boolean isPasswordValid(UserGateway user, String password) { return user.getPassword().equals(password); } public void removeUser(long userId) throws DataSourceException { FindersFactory.usersFinder().find(userId).remove(); }}

Page 50: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

PACKAGE DATA SOURCE

package DataSource;

import java.util.ArrayList;import java.util.List;

/** * * @author adrian */abstract class AbstractFinder<T extends RowDataGateway> implements RowFinder<T> { private DataSource dataSource; private IdentityMap idMap; private UnitOfWork uof;

public AbstractFinder(DataSource dataSource, IdentityMap idMap, UnitOfWork uof) { this.dataSource = dataSource; this.idMap = idMap; this.uof = uof; } @Override public List<T> findAll() throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return selectAllSql(); }

@Override public Object[] parameters() { return new Object[0]; } }); } protected List<T> findMany(StatementSource source) throws DataSourceException { return findInDatabase(source, this::loadMany); } abstract protected String selectAllSql();

Page 51: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

private <T> T findInDatabase(StatementSource source, DataLoader<T> loader) throws DataSourceException { try(Connection conn = dataSource.createConnection()) { try(Statement stmt = conn.createStatement(source.sql())) { source.fillStatement(stmt); try(ResultSet rs = stmt.executeQuery()) { return loader.load(rs); } } } } private List<T> loadMany(ResultSet rs) throws DataSourceException { List<T> result = new ArrayList<>(); while(rs.next()) result.add(load(rs)); return result; } private T load(ResultSet rs) throws DataSourceException { long id = rs.getLong(); try { return findInIdentityMap(id, idMap); } catch(RowNotFound ex) { T result = doLoad(id, uof, rs); idMap.addDataRow(result); return result; } } abstract protected T findInIdentityMap(long id, IdentityMap idMap) throws RowNotFound; abstract protected T doLoad(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException; @Override public T find(long id) throws DataSourceException { try { return findInIdentityMap(id, idMap); } catch(RowNotFound ex) { return findInDatabase(new StatementSource() { @Override public String sql() { return selectSql(); }

@Override public Object[] parameters() { return new Object[] { id

Page 52: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}; } }, this::loadSingle); } } private T loadSingle(ResultSet rs) throws DataSourceException { if(rs.next()) return load(rs); throw new RowNotFound("ResutSet is empty"); } abstract protected String selectSql();}

package DataSource;

/** * * @author adrian */public class AppSesionManager { private static ThreadLocal<AppSesionManager> current = new ThreadLocal<AppSesionManager>(){ @Override protected AppSesionManager initialValue() { return new AppSesionManager(); } }; private AppSesionManager() {} private IdentityMap idenMap = new IdentityMap(); private DataSource dataSource = new DataSource(); private UnitOfWork uof = new UnitOfWork(dataSource); private static AppSesionManager getCurrent() { return current.get(); }

static IdentityMap getIdentityMap() { return getCurrent().idenMap; }

static DataSource getDataSource() { return getCurrent().dataSource; }

public static UnitOfWork getUnitOfWork() {

Page 53: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

return getCurrent().uof; }}

package DataSource;

import java.util.List;import Domain.AttendanceFinder;

/** * * @author adrian */class AttendanceFinderImpl extends AbstractFinder<AttendanceGateway> implements AttendanceFinder{

public AttendanceFinderImpl(DataSource dataSource, IdentityMap idMap, UnitOfWork uof) { super(dataSource, idMap, uof); }

@Override protected String selectAllSql() { return "SELECT * FROM `attendance`"; }

@Override protected AttendanceGateway findInIdentityMap(long id, IdentityMap idMap) throws RowNotFound { return idMap.getAttendance(id); }

@Override protected AttendanceGateway doLoad(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { return new AttendanceGateway(id, uof, rs); }

@Override protected String selectSql() { return "SELECT * FROM `attendance` WHERE `attendance_id` = ?"; }

@Override public List<AttendanceGateway> findByCongregant(long congregantId) throws DataSourceException { return findMany(new StatementSource() { @Override

Page 54: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public String sql() { return "SELECT * FROM `attendance` WHERE `congregant_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { congregantId }; } }); }

@Override public List<AttendanceGateway> findByEvent(long eventId) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `attendance` WHERE `event_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { eventId }; } }); }}

package DataSource;

/** * * @author adrian */public class AttendanceGateway extends RowDataGateway { private long eventId; private long congregantId; AttendanceGateway(long id, UnitOfWork uof, long eventId, long congregantId) { super(id, uof); this.eventId = eventId; this.congregantId = congregantId; markNew(); }

AttendanceGateway(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException {

Page 55: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

super(id, uof); eventId = rs.getLong(); congregantId = rs.getLong(); }

public long getEventId() { return eventId; }

public void setEventId(long eventId) { this.eventId = eventId; markDirty(); }

public long getCongregantId() { return congregantId; }

public void setCongregantId(long congregantId) { this.congregantId = congregantId; markDirty(); }

@Override StatementSource insertSource() { return new StatementSource() { @Override public String sql() { return "INSERT INTO `attendance` (`attendance_id`, `event_id`, `congregant_id`) VALUES (?, ?, ?)"; } @Override public Object[] parameters() { return new Object[] { getId(), eventId, congregantId }; } }; }

@Override StatementSource updateSource() { return new StatementSource () { @Override public String sql() {

Page 56: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

return "UPDATE `attendance` SET `event_id` = ?, `congregant_id` = ? WHERE `attendance_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { eventId, congregantId, getId() }; } }; }

@Override StatementSource deleteSource() { return new StatementSource() { @Override public String sql() { return "DELETE FROM `attendance` WHERE `attendance_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { getId() }; } }; }}

package DataSource;

import java.util.Date;

/** * * @author adrian */public class CongregantGateway extends RowDataGateway { private int status; private String name; private String firstLastName; private String secondLastName; private String address; private String phone;

Page 57: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

private String email; private Date birthday; private int gender; private int civilStatus; private int type; private boolean baptized;

CongregantGateway(long id, UnitOfWork uof, int status, String name, String firstLastName, String secondLastName, String address, String phone, String email, Date birthday, int gender, int civilStatus, int type, boolean baptized) { super(id, uof); this.status = status; this.name = name; this.firstLastName = firstLastName; this.secondLastName = secondLastName; this.address = address; this.phone = phone; this.email = email; this.birthday = birthday; this.gender = gender; this.civilStatus = civilStatus; this.type = type; this.baptized = baptized; markNew(); }

CongregantGateway(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { super(id, uof); status = rs.getInt(); name = rs.getString(); firstLastName = rs.getString(); secondLastName = rs.getString(); address = rs.getString(); phone = rs.getString(); email = rs.getString(); birthday = rs.getDate(); gender = rs.getInt(); civilStatus = rs.getInt(); type = rs.getInt(); baptized = rs.getBoolean(); }

public int getStatus() { return status; }

public void setStatus(int status) { this.status = status; markDirty();

Page 58: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

public String getName() { return name; }

public void setName(String name) { this.name = name; markDirty(); }

public String getFirstLastName() { return firstLastName; }

public void setFirstLastName(String firstLastName) { this.firstLastName = firstLastName; markDirty(); }

public String getSecondLastName() { return secondLastName; }

public void setSecondLastName(String secondLastName) { this.secondLastName = secondLastName; markDirty(); }

public String getAddress() { return address; }

public void setAddress(String address) { this.address = address; markDirty(); }

public String getPhone() { return phone; }

public void setPhone(String phone) { this.phone = phone; markDirty(); }

public String getEmail() { return email;

Page 59: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

public void setEmail(String email) { this.email = email; markDirty(); }

public Date getBirthday() { return birthday; }

public void setBirthday(Date birthday) { this.birthday = birthday; markDirty(); }

public int getGender() { return gender; }

public void setGender(int gender) { this.gender = gender; markDirty(); }

public int getCivilStatus() { return civilStatus; }

public void setCivilStatus(int civilStatus) { this.civilStatus = civilStatus; markDirty(); }

public int getType() { return type; }

public void setType(int type) { this.type = type; markDirty(); }

public boolean isBaptized() { return baptized; }

public void setBaptized(boolean baptized) { this.baptized = baptized;

Page 60: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

markDirty(); }

@Override StatementSource insertSource() { return new StatementSource() { @Override public String sql() { return "INSERT INTO `congregants` " + "(`congregant_id`, `status`, `name`, `first_last_name`, " + "`second_last_name`, `address`, `phone`, `email`, `birthday`, " + "`gender`, `civil_status`, `type`, `baptized`) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; } @Override public Object[] parameters() { return new Object[] { getId(), status, name, firstLastName, secondLastName, address, phone, email, birthday, gender, civilStatus, type, baptized }; } }; }

@Override StatementSource updateSource() { return new StatementSource() { @Override public String sql() { return "UPDATE `congregants` SET " + "`status` = ?, `name` = ?, `first_last_name` = ?, `second_last_name` = ?, " + "`address` = ?, `phone` = ?, `email` = ?, `birthday` = ?, " + "`gender` = ?, `civil_status` = ?, `type` = ?, `baptized` = ? " + "WHERE `congregant_id` = ?"; } @Override

Page 61: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public Object[] parameters() { return new Object[] { status, name, firstLastName, secondLastName, address, phone, email, birthday, gender, civilStatus, type, baptized, getId() }; } }; }

@Override StatementSource deleteSource() { return new StatementSource() { @Override public String sql() { return "DELETE FROM `congregants` WHERE `congregant_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { getId() }; } }; }}

package DataSource;

import java.util.List;import Domain.CongregantsFinder;

/** * * @author adrian */class CongregantsFinderImpl extends AbstractFinder<CongregantGateway> implements CongregantsFinder {

Page 62: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

CongregantsFinderImpl(DataSource dataSource, IdentityMap idMap, UnitOfWork uof) { super(dataSource, idMap, uof); }

@Override public List<CongregantGateway> findByGroup(long groupId) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `congregants` " + "JOIN `memberships` " + "ON `congregants`.`congregant_id` = `memberships`.`congregant_id` " + "WHERE `memberships`.`group_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { groupId }; } }); }

@Override public List<CongregantGateway> findByEvent(long eventId) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `congregants` " + "JOIN `attendance` " + "ON `congregants`.`congregant_id` = `attendance`.`congregant_id` " + "WHERE `attendance`.`event_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { eventId }; } }); } @Override public List<CongregantGateway> findByStatus(int status) throws DataSourceException { return findMany(new StatementSource() { @Override

Page 63: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public String sql() { return "SELECT * FROM `congregants` " + "WHERE `status` = ?"; }

@Override public Object[] parameters() { return new Object[] { status }; } }); }

@Override protected String selectAllSql() { return "SELECT * FROM `congregants`"; }

@Override protected CongregantGateway findInIdentityMap(long id, IdentityMap idMap) throws RowNotFound { return idMap.getCongregant(id); }

@Override protected CongregantGateway doLoad(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { return new CongregantGateway(id, uof, rs); }

@Override protected String selectSql() { return "SELECT * FROM `congregants` WHERE `congregant_id` = ?"; }}

package DataSource;

import java.sql.DriverManager;import java.sql.SQLException;

/** * * @author adrian */class Connection implements AutoCloseable{ private java.sql.Connection conn;

Page 64: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public Connection(String driver, String database, String user, String password) throws DataSourceException{ try{ tryLoadDriver(driver); conn = tryEstablishConnection(database, user, password); }catch(ClassNotFoundException | InstantiationException | IllegalAccessException ex) { throw new DataSourceException("Driver: "+driver+" not loaded", ex); }catch(SQLException ex){ throw new DataSourceException("Connection failure to database: "+database, ex); } } private void tryLoadDriver(String driver) throws ClassNotFoundException, InstantiationException, IllegalAccessException{ Class.forName(driver).newInstance(); }

private java.sql.Connection tryEstablishConnection(String database, String user, String password) throws SQLException{ return DriverManager.getConnection(database, user, password); } public Statement createStatement(String sql) throws DataSourceException{ try{ return new Statement(conn.prepareStatement(sql)); }catch(SQLException ex){ throw new DataSourceException("Unable to create statemtent", ex); } }

public boolean isClosed() throws DataSourceException{ try{ return conn.isClosed(); }catch(SQLException ex){ throw new DataSourceException("Unable to check if the connection is closed", ex); } } public boolean isOpen() throws DataSourceException{ return !isClosed(); }

@Override public void close() throws DataSourceException{ try{ conn.close(); }catch(SQLException ex){ throw new DataSourceException("Unable to close connection", ex); }

Page 65: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

public void setAutoCommit(boolean autoCommit) throws DataSourceException { try{ conn.setAutoCommit(false); }catch(SQLException ex){ throw new DataSourceException("Unable to turn off autocommit database", ex); } }

public void commit() throws DataSourceException { try{ conn.commit(); }catch(SQLException ex){ throw new DataSourceException("Unable to commit database", ex); } }}

package DataSource;

/** * * @author adrian */interface DataLoader<T> { T load(ResultSet rs) throws DataSourceException; }

package DataSource;

import java.util.List;

/** * * @author adrian * @param <T> */public interface DataRowFinder<T extends RowDataGateway> extends RowFinder<T> { List<T> findByStatus(int status) throws DataSourceException; }

package DataSource;

/**

Page 66: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

* * @author adrian */class DataSource { // URL fields of the database private static final String DBMS = "mysql"; private static final String DBMS_API = "jdbc"; private static final String DB_SERVER = "localhost"; private static final String DB_PORT_NUMBER = "3306"; private static final String DB_NAME = "cdg_db"; // Driver name and database URL private static final String DB_DRIVER = "com."+DBMS+"."+DBMS_API+".Driver"; private static final String DB_URL = DBMS_API+":"+DBMS+"://"+DB_SERVER+":"+DB_PORT_NUMBER+"/"+DB_NAME; // Database credentials private static final String DB_USER = "root"; private static final String DB_PASS = "1234"; public Connection createConnection() throws DataSourceException { return new Connection(DB_DRIVER, DB_URL, DB_USER, DB_PASS); }}

package DataSource;

import java.io.IOException;

/** * * @author adrian */public class DataSourceException extends IOException{

public DataSourceException() { }

public DataSourceException(String message) { super(message); }

public DataSourceException(String message, Throwable cause) { super(message, cause); }

public DataSourceException(Throwable cause) { super(cause); } }

Page 67: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

package DataSource;

/** * * @author adrian */class Database { private Connection conn;

Database(Connection conn) { this.conn = conn; }

void performChange(StatementSource source) throws DataSourceException { try(Statement stmt = conn.createStatement(source.sql())) { source.fillStatement(stmt); stmt.executeUpdate(); } }}

package DataSource;

/** * * @author adrian */class Database { private Connection conn;

Database(Connection conn) { this.conn = conn; }

void performChange(StatementSource source) throws DataSourceException { try(Statement stmt = conn.createStatement(source.sql())) { source.fillStatement(stmt); stmt.executeUpdate(); } }}

package DataSource;

import java.util.List;import Domain.EventsFinder;

Page 68: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

/** * * @author adrian */class EventsFinderImpl extends AbstractFinder<EventGateway> implements EventsFinder {

EventsFinderImpl(DataSource dataSource, IdentityMap idMap, UnitOfWork uof) { super(dataSource, idMap, uof); }

@Override protected String selectAllSql() { return "SELECT * FROM `events`"; }

@Override protected EventGateway findInIdentityMap(long id, IdentityMap idMap) throws RowNotFound { return idMap.getEvent(id); }

@Override protected EventGateway doLoad(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { return new EventGateway(id, uof, rs); }

@Override protected String selectSql() { return "SELECT * FROM `events` WHERE `event_id` = ?"; }

@Override public List<EventGateway> findByCongregant(long congregantId) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `events` " + "JOIN `attendance` " + "ON `events`.`event_id` = `attendance`.`event_id` " + "WHERE `attendance`.`congregant_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { congregantId }; }

Page 69: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}); }

@Override public List<EventGateway> findByStatus(int status) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `events` " + "WHERE `status` = ?"; }

@Override public Object[] parameters() { return new Object[] { status }; } }); }}

package DataSource;

import Domain.AttendanceFinder;import Domain.MembershipsFinder;import Domain.UsersFinder;import Domain.CongregantsFinder;import Domain.EventsFinder;import Domain.GroupsFinder;

/** * * @author adrian */public class FindersFactory { public static AttendanceFinder attendanceFinder() { return new AttendanceFinderImpl(AppSesionManager.getDataSource(), AppSesionManager.getIdentityMap(), AppSesionManager.getUnitOfWork()); } public static CongregantsFinder congregantsFinder() { return new CongregantsFinderImpl(AppSesionManager.getDataSource(), AppSesionManager.getIdentityMap(), AppSesionManager.getUnitOfWork()); } public static EventsFinder eventsFinder() {

Page 70: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

return new EventsFinderImpl(AppSesionManager.getDataSource(), AppSesionManager.getIdentityMap(), AppSesionManager.getUnitOfWork()); } public static GroupsFinder groupsFinder() { return new GroupsFinderImpl(AppSesionManager.getDataSource(), AppSesionManager.getIdentityMap(), AppSesionManager.getUnitOfWork()); } public static MembershipsFinder membershipsFinder() { return new MembershipsFinderImpl(AppSesionManager.getDataSource(), AppSesionManager.getIdentityMap(), AppSesionManager.getUnitOfWork()); } public static UsersFinder usersFinder() { return new UsersFinderImpl(AppSesionManager.getDataSource(), AppSesionManager.getIdentityMap(), AppSesionManager.getUnitOfWork()); }}

package DataSource;

/** * * @author adrian */public class GroupGateway extends RowDataGateway { private int status; private String name;

GroupGateway(long id, UnitOfWork uof, int status, String name) { super(id, uof); this.status = status; this.name = name; markNew(); }

GroupGateway(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { super(id, uof); status = rs.getInt(); name = rs.getString(); }

public int getStatus() { return status; }

public void setStatus(int status) { this.status = status;

Page 71: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

markDirty(); }

public String getName() { return name; }

public void setName(String name) { this.name = name; markDirty(); }

@Override StatementSource insertSource() { return new StatementSource() { @Override public String sql() { return "INSERT INTO `groups` " + "(`group_id`, `status`, `name`) " + "VALUES (?, ?, ?)"; } @Override public Object[] parameters() { return new Object[] { getId(), status, name }; } }; }

@Override StatementSource updateSource() { return new StatementSource() { @Override public String sql() { return "UPDATE `groups` SET " + "`status` = ?, `name` = ? " + "WHERE `group_id` = ?"; } @Override public Object[] parameters() { return new Object[] { status, name, getId()

Page 72: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}; } }; }

@Override StatementSource deleteSource() { return new StatementSource() { @Override public String sql() { return "DELETE FROM `groups` WHERE `group_id` = ?"; } @Override public Object[] parameters() { return new Object[] { getId() }; } }; }}

package DataSource;

import java.util.List;import Domain.GroupsFinder;

/** * * @author adrian */class GroupsFinderImpl extends AbstractFinder<GroupGateway> implements GroupsFinder {

GroupsFinderImpl(DataSource dataSource, IdentityMap idMap, UnitOfWork uof) { super(dataSource, idMap, uof); }

@Override protected String selectAllSql() { return "SELECT * FROM groups"; }

@Override protected GroupGateway findInIdentityMap(long id, IdentityMap idMap) throws RowNotFound { return idMap.getGroup(id); }

@Override

Page 73: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

protected GroupGateway doLoad(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { return new GroupGateway(id, uof, rs); }

@Override protected String selectSql() { return "SELECT * FROM groups WHERE group_id = ?"; }

@Override public List<GroupGateway> findByCongregant(long congregantId) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * " + "FROM `groups` " + "JOIN `memberships` " + "ON `groups`.`group_id` = `memberships`.`group_id` " + "WHERE `memberships`.`congregant_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { congregantId }; } }); }

@Override public List<GroupGateway> findByStatus(int status) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `groups` " + "WHERE `status` = ?"; }

@Override public Object[] parameters() { return new Object[] { status }; } }); }}

Page 74: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

package DataSource;

/** * * @author adrian */class IdGenerator { private DataSource dataSource; private String idName; private long nextId; private long maxId; private int incrementBy;

public IdGenerator(DataSource dataSource, String idName, int incrementBy) { this.dataSource = dataSource; this.idName = idName; this.incrementBy = incrementBy; } public synchronized long nextId() throws DataSourceException { if(nextId == maxId) reserveIds(); return nextId++; } private void reserveIds() throws DataSourceException { long newNextId; long newMaxId; try(Connection conn = dataSource.createConnection()) { conn.setAutoCommit(false); try(Statement stmt = conn.createStatement("SELECT next_id FROM ids WHERE name = ? FOR UPDATE")){ stmt.setString(idName); try(ResultSet rs = stmt.executeQuery()) { rs.next(); newNextId = rs.getLong(); } } newMaxId = newNextId + incrementBy; try(Statement stmt = conn.createStatement("UPDATE ids SET next_id = ? WHERE name = ?")) { stmt.setLong(newMaxId); stmt.setString(idName); stmt.executeUpdate(); } conn.commit(); } nextId = newNextId;

Page 75: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

maxId = newMaxId; }}

package DataSource;

import java.util.HashMap;import java.util.Map;

/** * * @author adrian */class IdentityMap { private Map<Long, CongregantGateway> congregants = new HashMap<>(); private Map<Long, MembershipsGateway> memberships = new HashMap<>(); private Map<Long, AttendanceGateway> attendance = new HashMap<>(); private Map<Long, EventGateway> events = new HashMap<>(); private Map<Long, GroupGateway> groups = new HashMap<>(); private Map<Long, UserGateway> users = new HashMap<>(); public <T extends RowDataGateway> void addDataRow(T row) { getMapFor(row).put(row.getId(), row); } private <T> Map<Long, T> getMapFor(T row) { if(row instanceof CongregantGateway) return (Map<Long, T>) congregants; if(row instanceof EventGateway) return (Map<Long, T>) events; if(row instanceof GroupGateway) return (Map<Long, T>) groups; if(row instanceof UserGateway) return (Map<Long, T>) users; if(row instanceof AttendanceGateway) return (Map<Long, T>) attendance; if(row instanceof MembershipsGateway) return (Map<Long, T>) memberships; throw new UnsupportedOperationException("Map for class: "+row.getClass()+" not available yet"); } private <T> T getRow(Map<Long, T> map, long id) throws RowNotFound { if(!map.containsKey(id)) throw new RowNotFound("Data row with id: "+id+" not found in identity map"); return map.get(id); }

Page 76: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public CongregantGateway getCongregant(long id) throws RowNotFound { return getRow(congregants, id); } public EventGateway getEvent(long id) throws RowNotFound { return getRow(events, id); } public GroupGateway getGroup(long id) throws RowNotFound { return getRow(groups, id); } public UserGateway getUser(long id) throws RowNotFound { return getRow(users, id); } public AttendanceGateway getAttendance(long id) throws RowNotFound { return getRow(attendance, id); } public MembershipsGateway getMembership(long id) throws RowNotFound { return getRow(memberships, id); }}

package DataSource;

import java.util.List;import Domain.MembershipsFinder;

/** * * @author adrian */class MembershipsFinderImpl extends AbstractFinder<MembershipsGateway> implements MembershipsFinder {

MembershipsFinderImpl(DataSource dataSource, IdentityMap idMap, UnitOfWork uof) { super(dataSource, idMap, uof); }

@Override protected String selectAllSql() { return "SELECT * FROM `memberships`"; }

@Override protected MembershipsGateway findInIdentityMap(long id, IdentityMap idMap) throws RowNotFound {

Page 77: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

return idMap.getMembership(id); }

@Override protected MembershipsGateway doLoad(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { return new MembershipsGateway(id, uof, rs); }

@Override protected String selectSql() { return "SELECT * FROM `memberships` WHERE `membership_id` = ?"; }

@Override public List<MembershipsGateway> findByCongregant(long congregantId) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `memberships` WHERE `congregant_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { congregantId }; } }); }

@Override public List<MembershipsGateway> findByGroup(long groupId) throws DataSourceException { return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `memberships` WHERE `group_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { groupId }; } }); } }

Page 78: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

package DataSource;

/** * * @author adrian */public class MembershipsGateway extends RowDataGateway { private long groupId; private long congregantId;

MembershipsGateway(long id, UnitOfWork uof, long groupId, long congregantId) { super(id, uof); this.groupId = groupId; this.congregantId = congregantId; markNew(); } MembershipsGateway(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { super(id, uof); groupId = rs.getLong(); congregantId = rs.getLong(); }

public long getGroupId() { return groupId; }

public void setGroupId(long groupId) { this.groupId = groupId; markDirty(); }

public long getCongregantId() { return congregantId; }

public void setCongregantId(long congregantId) { this.congregantId = congregantId; markDirty(); } @Override StatementSource insertSource() { return new StatementSource() { @Override public String sql() { return "INSERT INTO `memberships` (`membership_id`, `group_id`, `congregant_id`) VALUES (?, ?, ?)";

Page 79: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

} @Override public Object[] parameters() { return new Object[] { getId(), groupId, congregantId }; } }; }

@Override StatementSource updateSource() { return new StatementSource () { @Override public String sql() { return "UPDATE `memberships` SET `group_id` = ?, `congregant_id` = ? WHERE `membership_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { groupId, congregantId, getId() }; } }; }

@Override StatementSource deleteSource() { return new StatementSource() { @Override public String sql() { return "DELETE FROM `memberships` WHERE `membership_id` = ?"; }

@Override public Object[] parameters() { return new Object[] { getId() }; } }; }

Page 80: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

package DataSource;

import java.util.Date;import java.sql.SQLException;

/** * * @author adrian */class ResultSet implements AutoCloseable{ private final java.sql.ResultSet rs; private int index;

protected ResultSet(java.sql.ResultSet resultSet) { this.rs = resultSet; }

@Override public void close() throws DataSourceException { try{ rs.close(); }catch(SQLException ex){ throw new DataSourceException(ex); } }

public boolean next() throws DataSourceException { index = 0; try{ return rs.next(); }catch(SQLException ex){ throw new DataSourceException(ex); } }

public String getString(String columnLabel) throws DataSourceException { try{ return rs.getString(columnLabel); }catch(SQLException ex){ throw new DataSourceException(ex); } }

public int getInt(String columnLabel) throws DataSourceException { try{ return rs.getInt(columnLabel); }catch(SQLException ex){

Page 81: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

throw new DataSourceException(ex); } }

public long getLong(String columnLabel) throws DataSourceException { try{ return rs.getLong(columnLabel); }catch(SQLException ex){ throw new DataSourceException(ex); } } public boolean getBoolean(String columnLabel) throws DataSourceException { try{ return rs.getBoolean(columnLabel); }catch(SQLException ex){ throw new DataSourceException(ex); } }

public Date getDate(String columnLabel) throws DataSourceException { try{ return rs.getDate(columnLabel); }catch(SQLException ex){ throw new DataSourceException(ex); } }

public String getString() throws DataSourceException { try{ return rs.getString(++index); }catch(SQLException ex){ throw new DataSourceException(ex); } }

public int getInt() throws DataSourceException { try{ return rs.getInt(++index); }catch(SQLException ex){ throw new DataSourceException(ex); } }

public Date getDate() throws DataSourceException { try{ return rs.getDate(++index); }catch(SQLException ex) { throw new DataSourceException(ex);

Page 82: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

} }

public boolean getBoolean() throws DataSourceException { try{ return rs.getBoolean(++index); }catch(SQLException ex) { throw new DataSourceException(ex); } } public long getLong() throws DataSourceException { try{ return rs.getLong(++index); }catch(SQLException ex) { throw new DataSourceException(ex); } }

}

package DataSource;

/** * * @author adrian */public abstract class RowDataGateway { private long id; private UnitOfWork uof; RowDataGateway(long id, UnitOfWork uof) { this.id = id; this.uof = uof; } public final long getId() { return id; }

protected final void markNew() { uof.registerNew(this); }

protected final void markDirty() { uof.registerDirty(this); }

Page 83: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public final void remove() { uof.registerRemoved(this); }

void insert(Database database) throws DataSourceException { database.performChange(insertSource()); } abstract StatementSource insertSource();

void update(Database database) throws DataSourceException { database.performChange(updateSource()); } abstract StatementSource updateSource();

final void delete(Database database) throws DataSourceException { database.performChange(deleteSource()); } abstract StatementSource deleteSource();}

package DataSource;

import java.util.List;

/** * * @author adrian * @param <T> */public interface RowFinder<T extends RowDataGateway> { T find(long id) throws DataSourceException; List<T> findAll() throws DataSourceException; }

package DataSource;

/** * * @author adrian */public class RowFinderFactory { private IdentityMap identityMap = new IdentityMap();

Page 84: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

private DataSource dataSource = new DataSource(); private static ThreadLocal<RowFinderFactory> current = new ThreadLocal<RowFinderFactory>(){ @Override protected RowFinderFactory initialValue() { return new RowFinderFactory(); } }; private RowFinderFactory() {} public static void newCurrent() { setCurrent(new RowFinderFactory()); } public static void setCurrent(RowFinderFactory rowFinderFactory) { current.set(rowFinderFactory); } public static RowFinderFactory getCurrent() { return current.get(); } }

package DataSource;

/** * * @author adrian */public class RowNotFound extends DataSourceException {

public RowNotFound() { }

public RowNotFound(String message) { super(message); }

public RowNotFound(String message, Throwable cause) { super(message, cause); }

public RowNotFound(Throwable cause) { super(cause); }

Page 85: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

package DataSource;

import java.util.Date;

/** * * @author adrian */public class RowsFactory { private static IdGenerator attendanceIdGen = new IdGenerator(AppSesionManager.getDataSource(),"attendance_id", 25); private static IdGenerator congregantIdGen = new IdGenerator(AppSesionManager.getDataSource(),"congregant_id", 5); private static IdGenerator eventIdGen = new IdGenerator(AppSesionManager.getDataSource(), "event_id", 2); private static IdGenerator groupIdGen = new IdGenerator(AppSesionManager.getDataSource(), "group_id", 2); private static IdGenerator membershipIdGen = new IdGenerator(AppSesionManager.getDataSource(), "membership_id", 25); private static IdGenerator userIdGen = new IdGenerator(AppSesionManager.getDataSource(), "user_id", 2); public static AttendanceGateway attendanceRow(long eventId, long congregantId) throws DataSourceException { return new AttendanceGateway(attendanceIdGen.nextId(), AppSesionManager.getUnitOfWork(), eventId, congregantId); } public static CongregantGateway congregantRow(int status, String name, String firstLastName, String secondLastName, String address, String phone, String email, Date birthday, int gender, int civilStatus, int type, boolean baptized) throws DataSourceException { return new CongregantGateway(congregantIdGen.nextId(), AppSesionManager.getUnitOfWork(), status, name, firstLastName, secondLastName, address, phone, email, birthday, gender, civilStatus, type, baptized); } public static EventGateway eventRow(int status, Date date, Long groupId, int typeId) throws DataSourceException { return new EventGateway(eventIdGen.nextId(), AppSesionManager.getUnitOfWork(), status, date, groupId, typeId); } public static GroupGateway groupRow(int status, String name) throws DataSourceException { return new GroupGateway(groupIdGen.nextId(), AppSesionManager.getUnitOfWork(), status, name); }

Page 86: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

public static MembershipsGateway membershipRow(long groupId, long congregantId) throws DataSourceException { return new MembershipsGateway(membershipIdGen.nextId(), AppSesionManager.getUnitOfWork(), groupId, congregantId); } public static UserGateway userRow(int status, String name, String password, int level, Long groupId) throws DataSourceException { return new UserGateway(userIdGen.nextId(), AppSesionManager.getUnitOfWork(), status, name, password, level, groupId); }}

package DataSource;

import java.sql.*;

/** * * @author adrian */class Statement implements AutoCloseable{ private final PreparedStatement preparedStatement; int index;

protected Statement(PreparedStatement preparedStatement) { this.preparedStatement = preparedStatement; } public ResultSet executeQuery() throws DataSourceException{ index = 0; try{ return new ResultSet(preparedStatement.executeQuery()); }catch(SQLException ex){ throw new DataSourceException(ex); } } public void executeUpdate() throws DataSourceException{ index = 0; try{ preparedStatement.executeUpdate(); }catch(SQLException ex){ throw new DataSourceException(ex); } } public boolean isClosed() throws DataSourceException{

Page 87: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

try{ return preparedStatement.isClosed(); }catch(SQLException ex){ throw new DataSourceException(ex); } }

@Override public void close() throws DataSourceException { try{ preparedStatement.close(); }catch(SQLException ex) { throw new DataSourceException(ex); } }

public void setInt(int value) throws DataSourceException { try{ preparedStatement.setInt(++index, value); }catch(SQLException ex){ throw new DataSourceException("Unable to set int, parameterIndex: "+index+", value: "+value, ex); } } public void setLong(long value) throws DataSourceException { try{ preparedStatement.setLong(++index, value); }catch(SQLException ex){ throw new DataSourceException("Unable to set long, parameterIndex: "+index+", value: "+value, ex); } }

public void setString(String value) throws DataSourceException { try{ preparedStatement.setString(++index, value); }catch(SQLException ex){ throw new DataSourceException("Unable to set string, parameterIndex: "+index+", value: "+value, ex); } }

public void setDate(Date value) throws DataSourceException { try{ preparedStatement.setDate(++index, value); }catch(SQLException ex){ throw new DataSourceException("Unable to set date, parameterIndex: "+index+", value: "+value, ex);

Page 88: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

} }

public void setBoolean(boolean value) throws DataSourceException { try{ preparedStatement.setBoolean(++index, value); }catch(SQLException ex){ throw new DataSourceException("Unable to set boolean, parameterIndex: "+index+", value: "+value, ex); } }

public void setObject(Object value) throws DataSourceException { try{ preparedStatement.setObject(++index, value); }catch(SQLException ex){ throw new DataSourceException("Unable to set object, parameterIndex: "+index+", value: "+value, ex); } } }

package DataSource;

/** * * @author adrian */interface StatementSource {

String sql();

Object[] parameters(); default void fillStatement(Statement stmt) throws DataSourceException { for(Object parameter : parameters()) stmt.setObject(parameter); }}

package DataSource;

import java.util.Collection;import java.util.ArrayList;

/** *

Page 89: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

* @author adrian */public class UnitOfWork { private final Collection<RowDataGateway> newRows = new ArrayList<>(); private final Collection<RowDataGateway> dirtyRows = new ArrayList<>(); private final Collection<RowDataGateway> removedRows = new ArrayList<>(); private final DataSource dataSource;

UnitOfWork(DataSource dataSource) { this.dataSource = dataSource; } void registerNew(RowDataGateway gateway) { if(!newRows.contains(gateway)) newRows.add(gateway); } void registerDirty(RowDataGateway gateway){ if(!newRows.contains(gateway) && !dirtyRows.contains(gateway)) dirtyRows.add(gateway); } void registerRemoved(RowDataGateway gateway) { if(newRows.remove(gateway)) return; if(!removedRows.contains(gateway)) { dirtyRows.remove(gateway); removedRows.add(gateway); } } public void commit() throws DataSourceException { try(Connection conn = dataSource.createConnection()){ conn.setAutoCommit(false); performChanges(new Database(conn)); conn.commit(); } } private void performChanges(Database database) throws DataSourceException { insertNew(database); updateDirty(database); deleteRemoved(database); } private void insertNew(Database database) throws DataSourceException { for(RowDataGateway row : newRows) row.insert(database); }

Page 90: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

private void updateDirty(Database database) throws DataSourceException { for(RowDataGateway row : dirtyRows) row.update(database); } private void deleteRemoved(Database database) throws DataSourceException { for(RowDataGateway row : removedRows) row.delete(database); }}

package DataSource;

/** * * @author adrian */public class UserGateway extends RowDataGateway { private int status; private String name; private String password; private int level; private Long groupId;

UserGateway(long id, UnitOfWork uof, int status, String name, String password, int level, Long groupId) { super(id, uof); this.status = status; this.name = name; this.password = password; this.level = level; this.groupId = groupId; markNew(); }

UserGateway(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException { super(id, uof); status = rs.getInt(); name = rs.getString(); password = rs.getString(); level = rs.getInt(); groupId = rs.getLong(); if(groupId == 0) groupId = null; }

public int getStatus() { return status;

Page 91: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

}

public void setStatus(int status) { this.status = status; markDirty(); }

public String getName() { return name; }

public void setName(String name) { this.name = name; markDirty(); }

public String getPassword() { return password; }

public void setPassword(String password) { this.password = password; markDirty(); }

public int getLevel() { return level; }

public void setLevel(int level) { this.level = level; markDirty(); }

public Long getGroupId() { return groupId; }

public void setGroupId(Long groupId) { this.groupId = groupId; markDirty(); } @Override StatementSource insertSource() { return new StatementSource() { @Override public String sql() { return "INSERT INTO `users` "

Page 92: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

+ "(`user_id`, `status`, `name`, `password`, `level`, `group_id`) " + "VALUES (?, ?, ?, ?, ?, ?)"; } @Override public Object[] parameters() { return new Object[] { getId(), status, name, password, level, groupId }; } }; }

@Override StatementSource updateSource() { return new StatementSource() { @Override public String sql() { return "UPDATE `users` SET " + "`status` = ?, `name` = ?, `password` = ?, `level` = ?, `group_id` = ? " + "WHERE `user_id` = ?"; } @Override public Object[] parameters() { return new Object[] { status, name, password, level, groupId, getId() }; } }; }

@Override StatementSource deleteSource() { return new StatementSource() { @Override public String sql() { return "DELETE FROM `users` WHERE `user_id` = ?"; }

Page 93: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

@Override public Object[] parameters() { return new Object[] { getId() }; } }; }}

package DataSource;

import Domain.UsersFinder;import java.util.List;

/** * * @author adrian */class UsersFinderImpl extends AbstractFinder<UserGateway> implements UsersFinder {

UsersFinderImpl(DataSource dataSource, IdentityMap idMap, UnitOfWork uof) { super(dataSource, idMap, uof); }

@Override protected String selectAllSql() { return "SELECT * FROM `users`"; }

@Override protected UserGateway findInIdentityMap(long id, IdentityMap idMap) throws RowNotFound { return idMap.getUser(id); }

@Override protected UserGateway doLoad(long id, UnitOfWork uof, ResultSet rs) throws DataSourceException{ return new UserGateway(id, uof, rs); }

@Override protected String selectSql() { return "SELECT * FROM `users` WHERE `user_id` = ?"; }

@Override public List<UserGateway> findByStatus(int status) throws DataSourceException {

Page 94: Sistema Web Iglesia Casa De Gracia · 0 Sistema Web Iglesia Casa De Gracia MANUAL TECNICO Víctor Daniel Puch Sánchez Adrián Donaldo Guevara Salomón Diseño De Aplicaciones Web

return findMany(new StatementSource() { @Override public String sql() { return "SELECT * FROM `users` " + "WHERE `status` = ?"; }

@Override public Object[] parameters() { return new Object[] { status }; } }); }}