Proyecto Final Modelo

38
INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA JORGE DUCHITANGA, MARIELA JIMBO REDES DE CÓMPUTO I GRUPO: 1 1 PROYECTO FINAL 1. INTRODUCCIÓN En la actualidad existen muchas empresas las cuales se manejan a través de las redes de computadoras para poder enviarse información solicitada unas a otras, como la base de datos de varios clientes. Además en esta época es muy utilizado la tecnología móvil para usarlo de diferentes maneras y con varias aplicaciones por ende mucha información podría ser enviada o receptada desde un teléfono móvil Como un plus para el proyecto presentado se verá la realización del envío y recepción de la información de los diferentes de una computadora hacia un celular y viceversa en donde se aplicará la comunicación mediante redes. 2. MARCO TEÓRICO WAMP Es un entorno de desarrollo web de Windows. Que permite crear aplicaciones web con Apache2, PHP y base de datos MySQL. Además PhpMyAdmin permite fácilmente administrar la base de datos. El WAMP proporciona lenguajes de programación para el desarrollo de aplicaciones web. Para simplificar la tarea de instalar Apache + PHP + MySQL en Windows, existen los llamados paquetes WAMP que instalan y configuran automáticamente dichas aplicaciones para Windows y que proporcionan: Servidor Web Apache Base de datos MySQL Lenguaje de programación PHP Accesos directos para el arranque y la parada de los servicios Gestores web para MySQL, configurar el servidor Apache… Otros servicios De estos paquetes podemos destacar: Easyphp XAMPP AppServ WampServer Un servidor WAMP nos permite instalar aplicaciones web accesibles desde nuestra red local. Si abrimos el puerto correspondiente en el router podemos acceder desde Internet. Un servidor WAMP es la base donde podemos instalar infinidad de aplicaciones como: Gestores de contenidos: Joomla, Drupal. Plataformas educativas: Moodle, Claroline, Dokeos, etc Blogs: WordPress, Serendipity, etc Wikis: DokuWiki, TikiWiki , MediaWiki, etc Foros: phpBB, myBB, etc Galerías de imágenes: Coppermine, Gallery, etc

Transcript of Proyecto Final Modelo

Page 1: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

1

PROYECTO FINAL

1. INTRODUCCIÓN

En la actualidad existen muchas empresas las cuales se manejan a través de las

redes de computadoras para poder enviarse información solicitada unas a otras,

como la base de datos de varios clientes.

Además en esta época es muy utilizado la tecnología móvil para usarlo de

diferentes maneras y con varias aplicaciones por ende mucha información podría

ser enviada o receptada desde un teléfono móvil

Como un plus para el proyecto presentado se verá la realización del envío y

recepción de la información de los diferentes de una computadora hacia un celular

y viceversa en donde se aplicará la comunicación mediante redes.

2. MARCO TEÓRICO

WAMP Es un entorno de desarrollo web de Windows. Que permite crear aplicaciones web con Apache2, PHP y base de datos MySQL. Además PhpMyAdmin permite fácilmente administrar la base de datos. El WAMP proporciona lenguajes de programación para el desarrollo de aplicaciones web. Para simplificar la tarea de instalar Apache + PHP + MySQL en Windows, existen los llamados paquetes WAMP que instalan y configuran automáticamente dichas aplicaciones para Windows y que proporcionan:

Servidor Web Apache

Base de datos MySQL

Lenguaje de programación PHP

Accesos directos para el arranque y la parada de los servicios

Gestores web para MySQL, configurar el servidor Apache…

Otros servicios De estos paquetes podemos destacar:

Easyphp

XAMPP

AppServ

WampServer Un servidor WAMP nos permite instalar aplicaciones web accesibles desde nuestra red local. Si abrimos el puerto correspondiente en el router podemos acceder desde Internet. Un servidor WAMP es la base donde podemos instalar infinidad de aplicaciones como:

Gestores de contenidos: Joomla, Drupal.

Plataformas educativas: Moodle, Claroline, Dokeos, etc

Blogs: WordPress, Serendipity, etc

Wikis: DokuWiki, TikiWiki , MediaWiki, etc

Foros: phpBB, myBB, etc

Galerías de imágenes: Coppermine, Gallery, etc

Page 2: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

2

APPINVENTOR Fue creada a mediados del 2009 el profesor Harold Abelson del MIT, la aplicación se puso a disposición del público el 12 de julio de 2010 y está dirigida a personas que no están familiarizadas con la programación informática. Es una aplicación creada por google para que las personas con interés se puedan crear su propia aplicación móvil de software, ya sea este para su hogar, empresa u otros intereses, esta aplicación se usa con el sistema operativo Android. El usuario se puede crear la aplicación con herramientas básicas, en donde se puede ir enlazando una serie de bloques para crear la aplicación. El sistema de AppInventor es gratuito y se puede descargar fácilmente de la web, para lo cual gracias a su simplicidad de uso se podrían generar nuevas aplicaciones para la tecnología Android El editor de bloques de la aplicación utiliza la librería Open Blocks de Java para crear un lenguaje visual a partir de bloques. Estas librerías están distribuidas por Massachusetts Institute of Technology ( MIT ) bajo su licencia libre (MIT License). El compilador que traduce el lenguaje visual de los bloques para la aplicación en Android utiliza Kawa como lenguaje de programación, distribuido como parte del sistema operativo GNU de la Free Software Foundation NETBEANS

El IDE NetBeans es un entorno de desarrollo integrado, una herramienta para programadores pensada para escribir, compilar, depurar y ejecutar programas. Está escrito en Java, pero puede servir para cualquier otro lenguaje de programación. El NetBeans IDE es un IDE de código abierto escrito completamente en Java usando la plataforma NetBeans. El NetBeans IDE soporta el desarrollo de todos los tipos de aplicación Java (J2SE, web, EJB y aplicaciones móviles). Entre sus características se encuentra un sistema de proyectos basado en Ant, control de versiones y refactoring. NetBeans es un entorno de desarrollo integrado libre, hecho principalmente para el lenguaje de programación Java, NetBeans IDE1 es un producto libre y gratuito sin restricciones de uso. La plataforma NetBeans permite que las aplicaciones sean desarrolladas a partir de un conjunto de componentes 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. Debido a que los módulos pueden ser desarrollados independientemente, las aplicaciones basadas en la plataforma NetBeans pueden ser extendidas fácilmente por otros desarrolladores de software. La plataforma ofrece servicios comunes a las aplicaciones de escritorio, permitiéndole al desarrollador enfocarse en la lógica específica de su aplicación. Entre las características de la plataforma están:

Administración de las interfaces de usuario (ej. menús y barras de herramientas)

Administración de las configuraciones del usuario

Page 3: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

3

Administración del almacenamiento (guardando y cargando cualquier tipo de dato)

Administración de ventanas

Framework basado en asistentes (diálogos paso a paso) BLUETOOTH Bluetooth es una tecnología de comunicación inalámbrica de corto alcance que se utiliza para comunicarse entre dispositivos a una distancia aproximada de 8 metros. Los dispositivos Bluetooth más comunes son los auriculares para realizar llamadas o escuchar música, los equipos de manos libres para automóviles y otros dispositivos portátiles, incluidas las computadoras portátiles.

Bluetooth es una especificación industrial para Redes Inalámbricas de Área Personal (WPAN) que posibilita la transmisión de voz y datos entre diferentes dispositivos mediante un enlace por radiofrecuencia en la banda ISM de los 2,4 GHz.

Los principales objetivos que se pretenden conseguir con esta norma son:

Facilitar las comunicaciones entre equipos móviles y fijos.

Eliminar los cables y conectores entre éstos. Ofrecer la posibilidad de crear pequeñas redes inalámbricas y facilitar la

sincronización de datos entre equipos personales.

3. DESARROLLO

En la siguiente figura se verá el esquema que se realiza para este proyecto en el

cual se comunicarán los dos servidores mutuamente en donde el servidor A tiene

la información del cliente y el servidor B la información de la cuenta bancaria del

mismo, además se podrá enviar la información solicitada hacia un celular en donde

se verá el tiempo transcurrido, el monto y algunos datos del cliente.

Figura1. Esquema del Proyecto

Page 4: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

4

Para que los dos servidores se comuniquen entre sí se ha hecho mediante un cable de

red y con el servidor WAMP, para así poder conocer los IP de cada uno. En cuanto la

conexión entre el un servidor y el celular con tecnología Android se ha realizado por

vía Bluetooth en donde se conocerá el MAC de cada una.

Figura2. Conexión entre hosts y celular

Cada servidor tendrá distinta información de un mismo cliente para lo que se ha hecho

un programa en NetBeans - JAVA, para que nos permita ingresar, editar y visualizar

los datos presentes en la Figura3.

Para la aplicación en el celular se ha hecho en AppInventor en donde nos permite

visualizar los datos del cliente, el débito bancario y el tiempo comprado.

Page 5: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

5

FIGURA3. Clases y Atributos del servidor y cliente

INSTALAR EL SERVIDOR WAMP

Comenzamos la instalación en un sistema Windows 7 SP1. Descargamos WampServer de wampserver.com.

El firewall de Windows nos avisará para permitir o denegar el acceso del programa a la red. Nosotros lo permitimos.

Page 6: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

6

WampServer nos preguntará el servidor SMTP y la dirección de correo usada para la función mail(). Nosotros lo dejamos por defecto.

Una vez finalizada la instalación abrimos el navegador web y comprobamos el acceso local al servidor entrando en http:// localhost/

Abajo tenemos un menú de herramientas con un acceso directo a phpmyadmin y a la función phpinfo() de php.

Abrimos phpinfo() para comprobar que php funciona correctamente.

Page 7: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

7

Configuración del servidor WAMP En la barra de tareas de Windows tendremos un nuevo icono con el símbolo de WAMP. Su color nos indica el estado del servidor. Cuando se hace click saldrá un menú contextual desde el que podemos parar o reiniciar los servicios.

Desde el menú de administración de WampServer, empezando de arriba hacia abajo, podremos saber cada una de las opciones:

Localhost: mediante la opción localhost accedemos con el navegador a los contenidos del servidor web, también podemos visualizarlo mediante la dirección IP 127.0.0.1

phpMyAdmin: Es un administrador de bases de datos. Se accede de la siguiente forma http://localhost/phpmyadmin.

directorio www: En esta carpeta es donde debemos copiar las aplicaciones que deseemos instalar.

Apache: Sirve para acceder a la configuración de Apache. PHP: Sirve para acceder a la configuración de PHP. MySQL: Sirve para acceder a la configuración de MySQL. Iniciar los servicios: permite iniciar Apache y MySQL. Detener los servicios: permite detener Apache y MySQL Reiniciar los servicios: permite Reiniciar Apache y MySQL, es útil si hemos

realizado alguna modificación en la configuración y queremos aplicar los cambios.

Desde el menú de configuración de Apache, podemos acceder a diferentes opciones:

Page 8: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

8

Versión: permite elegir la versión de Apache. Podemos tener instaladas varias versiones y activar la versión que nos interese en un momento dado. Esto es útil si alguna aplicación necesita versiones antiguas para funcionar, pero habitualmente trabajaremos con la última versión de Apache.

Service: permite iniciar o detener el servicio. También permite instalar o desinstalar Apache como servicio del sistema

Módulos de Apache: permite activar o desactivar los módulos de Apache sin necesidad de editar el archivo de configuración httpd.conf.

Directorios Alias: permite alias en Apache sin necesidad de editar el archivo de configuración httpd.conf.

httpd.conf: permite editar el archivo de configuración httpd.conf. Si se hace algún cambio en la configuración, hay que reiniciar Apache para que los cambios tomen efecto.

Apache error log: permite visualizar el archivo de registro de errores de Apache. Resulta útil para investigar las causas cuando algo no funciona.

Apache access log: permite visualizar las peticiones de páginas que realizan los usuarios.

Desde el menú de configuración de PHP, podemos acceder a diferentes opciones:

Versión: permite elegir la versión de PHP. Podemos tener instaladas varias versiones y activar la versión que nos interese en un momento dado. Esto es útil si alguna aplicación necesita versiones antiguas para funcionar, pero habitualmente trabajaremos con la última versión de PHP.

Configuración de PHP: permite activar o desactivar los parámetros más usuales de la configuración de PHP, sin necesidad de editar el archivo de configuración php.ini.

Extensiones de PHP: permite activar o desactivar las extensiones de PHP sin necesidad de editar el archivo de configuración php.ini

php.ini: permite editar el archivo de configuración php.ini. Si se hace algún cambio en la configuración, hay que reiniciar Apache para que los cambios tomen efecto.

PHP error log: permite visualizar el archivo de registro de errores de PHP. Útil para investigar las causas cuando algo no funciona.

Page 9: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

9

Desde el menú de configuración de MySQL, podemos acceder a diferentes opciones:

Versión: permite elegir la versión de MySQL. Podemos tener instaladas varias versiones y activar la versión que nos interese en un momento dado. Esto es útil si alguna aplicación necesita versiones antiguas para funcionar, pero habitualmente trabajaremos con la última versión de MySQL.

Service: permite iniciar o detener el servicio. También permite instalar o desinstalar Apache como servicio del sistema.

Consola de MySQL: abre el cliente de mysql en modo texto. Es necesario conocer el lenguaje SQL para utilizarlo.

my.ini: permite editar el archivo de configuración my.ini. Para hacer un uso normal, no es necesario realizar ninguna modificación en este archivo.

MySQL log: permite visualizar el archivo de registro de MySQL. Útil para investigar las causas cuando algo no funciona.

COMO CREAR LA BASE DE DATOS EN SERVIDOR WAMP

Lo que se verá en las siguientes figuras será para la creación de base de datos para el

servidor A ya que para el servidor B se realizarán los mismos pasos sino que con

diferentes variables.

1. Se Ingresó a http://localhost/phpmyadmin/ que corresponde al servidor WAMP del

primer servidor en este caso el servidor A el cual va a contener en su base de

datos el numero de cedula, nombres, apellidos, dirección, placas, modelo, año y

color

2. Se ha creado la base de datos “servidor_a” :

Page 10: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

10

3. Se ha creado la tabla “datos_servidora”, el cual va a contener todas las variables

ya mencionadas (numero de cedula, nombres, apellidos, dirección, placas, modelo,

año y color)

4. Se le asignará los nombres a cada columna

Page 11: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

11

5. Le asignamos el tipo de variable a cada una:

6. Definimos la longitud de cada variable:

Page 12: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

12

7. En la primera variable “id_clt2 “ la de finimos como la variable principal para esta

base de datos modificando el índice y el autoincremento(A_I).

8. Una vez realizado todos los pasos anteriormente vistos damos click en guardar.

Page 13: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

13

9. Comprobamos que se ha creado la base de datos con lo cual seleccionamos a la

izquierda la base de datos creada dato_servidora, y luego le damos click en

Estructura para ver nuestra tabla de dicha base de datos:

Page 14: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

14

PROGRAMA NETBEANS APLICACIÓN JAVA PARA LOS SERVIDORES A Y B Para el desarrollo de la aplicación utilizamos NetBeans 7.2.1

Creamos un Nuevo Proyecto:

Creamos 2 clases las cuales se van a encargar de comunicarse con los servidores A y

B, es decir con las bases de datos MySQL creadas anteriormente.

A continuación se presenta la clase encargada de enlazar los datos del servidor A, la

clase tiene por nombre ConexionServerA, la cual como principal característica debe

tener la IP del servidor en el cual se ha alojado la base de datos servidor_a

anteriormente creada con WAMP:

Page 15: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

15

De igual manera para enlazarme con el servidor B tenemos la siguiente clase que es

ConexionServerB, la cual de igual forma contiene la IP donde se ingreso la base de

datos servidor_b creada en WAMP:

Por último para la interfaz gráfica con los usuarios de los servidores hemos creado un

formulario java, en el cual podemos ingresar los clientes, editar sus datos, buscar los

clientes ya ingresados y visualizar los datos de todos los clientes registrados en

nuestras bases de datos.

Page 16: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

16

Por los requerimientos del docente mediante el servidor A se ingresa solamente la

cédula, nombres, apellidos, dirección (datos de cliente), la placa, modelo, año y color

(datos del vehículo).

También desde el servidor A establecemos la comunicación con el dispositivo

inalámbrico, con lo cual hemos creado un botón en donde habilitamos dicha conexión

Bluetooth.

Para crear la tabla en donde se ingresan los datos se seleccionará las diferentes

opciones para el programa.

Como se observa en esta figura usando los distintos bloques, podemos obtener como

se verá nuestra pantalla del servidor cuando este arranque.

El código fuente de dicho formulario contiene las clases necesarias para la

comunicación con los dos servidores A y B, dado lo extenso del código lo hemos

dejado como Anexo # 1 al final de este documento, lo importante de este formulario es

que enlaza los datos de ambos servidores correspondientes a cada cliente, y con la

comunicación Bluetooth permite que un usuario mediante un dispositivo inalámbrico

acceda a sus datos mediante su cedula y a su vez iniciar el servicio tarifado por

tiempo, el cual cada que se acceda a este servicio debitara automáticamente el saldo

de cada cliente y se actualizará en los servidores.

DESCRIPCION Y FUNCIONAMIENTO

Page 17: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

17

Para ingresar un usuario le damos click en el botón Nuevo:

A continuación ingresamos todos los datos correspondientes al cliente y presionamos

Guardar:

Por último se verá la visualización de los datos creado tanto en el servidor A, como en

el servidor B.

Page 18: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

18

APPINVENTOR

1. Se ingresó a http://appinventor.mit.edu/ en donde se podrá escoger diferentes

opciones, para nuestro caso se escogerá “Invent” el cual nos sirve para crear

nuevas aplicaciones para el celular.

2. Se seleccionará las diferentes herramientas que se necesita para la aplicación

que se verá en el celular como: label, text, button, etc.

Page 19: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

19

3. La pantalla que se verá en la aplicación celular es la siguiente la cual hay que

descargarse haciendo click en “Open the Blocks Editor”.

Para la programación de esta aplicación abrimos el editor de bloques y realizamos las

siguientes instrucciones.

Page 20: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

20

Una vez concluida la programación de la interfaz gráfica y la del editor de bloques

procedemos a generar el archivo .apk, el cual posteriormente se instalará en el móvil

con sistema operativo Android. Para realizar esta acción presionamos en “Package to

Phone”.

Page 21: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

21

Una vez generado el archivo .apk lo instalamos en el móvil y tendremos la aplicación

siguiente:

Page 22: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

22

A continuación se presenta la interfaz de la aplicación en el cual para conectarnos al

servidor presionamos Conectar Servidor, al hacer esto establecemos la conexión

Bluetooth con el servidor A:

Una vez conectados al servidor ingresamos un número de cédula registrado en

nuestros servidores:

Page 23: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

23

Ahora presionamos Enviar CI y esperamos a que el servidor nos devuelva nuestra

información:

Page 24: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

24

Como podemos observar la aplicación nos permite visualizar nuestra información, a continuación podemos presionar Debitar Monto con lo que accederemos a tiempo tarifado. Una vez presionado dicho botón comenzará a correr un tiempo ya establecido descendentemente hasta llegar a 00:00; al mismo tiempo me debitará automáticamente 2 dólares del monto de mi cuenta:

Una vez concluido el tiempo se activara una alarma, y al mismo tiempo un mensaje de advertencia. Para volver acceder al tiempo tarifado podemos presionar nuevamente Debitar Monto o presionaremos Reset, si queremos ingresar con otro usuario.

Page 25: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

25

4. CONCLUSIONES

Al realizar la conexión de los servidores de datos A y B se pudo observar la

interacción de los mismos mediante su respectivas aplicaciones JAVA, además se

ha observado que desde los dos servidores podemos visualizar todos los datos de

los clientes con la restricción que solo se pueden modificar o ingresar las variables

que estén asignadas para dichos servidores; para el caso del servidor A los datos

del cliente y vehículo y para el servidor B la información de su cuenta bancaria.

El cliente puede acceder a sus datos por medio de una aplicación de celular, en

dicha aplicación ingresamos el número de cédula respectivo y el servidor A nos

responde con nuestros datos para que tengamos conocimiento de nuestro estado

bancario y tener acceso al servicio por tiempo tarifado que se encuentra en dicha

aplicación; todo este proceso de comunicación se realiza por Bluetooth.

Realizamos la aplicación del celular en AppInventor, el cual es un programador

grafico mediante internet, para celulares que tengan un sistema operativo Android;

así también se hizo uso java para elaborar las interfaces de los servidores es decir

sus ventanas, siendo esta programación solo la elección de herramientas y

librerías para componer dicha interfaz gráfica, siendo una de las principales

herramientas la librería mysql-connector-java-5.1.16-bin.jar que es el conector

entre JAVA y la base de datos MySQL del servidor WAMP.

5. BIBLIOGRAFÍA

[1]http://beta.appinventor.mit.edu/

[2] http://www.wampserver.com/

[3]http://www.trucoteca.com/trucoswindows/Windows2003Server/configuracion-

basica-del-sitio-web 1041.html

[4]http://www.herramientasparapymes.com/wampserver-5

[5]http://es.wikipedia.org/wiki/WAMP

Page 26: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

26

ANEXOS

ANEXO I

SERVIDOR A

package Formularios;

import BaseDatos.ConexionServerB;

import BaseDatos.ConexionServerA;

import giovynet.serial.Baud;

import giovynet.serial.Com;

import giovynet.serial.Parameters;

import java.awt.Color;

import java.awt.ComponentOrientation;

import java.sql.*;

import java.util.ResourceBundle;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JOptionPane;

import javax.swing.table.DefaultTableModel;

public class Clientes extends javax.swing.JFrame {

DefaultTableModel modelo;

/** Creates new form Clientes */

public String montostring="";

public String clt="";

public int montoentero;

public String cedulastring="";

public String numstring="";

public String bancostring="";

public Clientes() {

initComponents();

CargarTablaClientes("");

inhabilitar(); }

void CargarTablaClientes(String valor) {

String[] titulos = {"ID", "Cédula", "Nombres",

"Apellidos", "Dirección", "Placa", "Modelo", "Año",

"Color", "Cedula", "Numero Cuenta", "Monto", "Banco"};

String[] registro = new String[13];

String sSQL = "";

String sSQL2 = "";

modelo = new DefaultTableModel(null, titulos);

//Conectar con el servidor A

ConexionServerA mysql = new ConexionServerA();

Connection cn = mysql.Conectar();

//Conectar con el servidor B

ConexionServerB mysql2 = new ConexionServerB();

Connection cn2 = mysql2.Conectar();

//Base de Datos Servidor A

sSQL = "SELECT id_clt2, cedula2, nombres, apellidos,

direccion, placa, modelo, año, color FROM datos_servidora

" +

"WHERE CONCAT(cedula2, ' ',nombres, '

',apellidos, ' ',direccion, ' ',placa, ' ',modelo, ' ',año, ' ',color)

LIKE '%"+valor+"%'";

//Base de Datos Servidor B

sSQL2 = "SELECT id_clt, cedula, num_cuenta, monto,

banco FROM datos_servidorb " +

"WHERE CONCAT(cedula, ' ',num_cuenta, ' ',monto, '

',banco) LIKE '%"+valor+"%'";

try {

//Servidor A

Statement st = cn.createStatement();

ResultSet rs = st.executeQuery(sSQL);

//Servidor B

Statement st2 = cn2.createStatement();

ResultSet rs2 = st2.executeQuery(sSQL2);

while(rs.next() && rs2.next()) {

registro[0] = rs.getString("id_clt2");

registro[1] = rs.getString("cedula2");

registro[2] = rs.getString("nombres");

registro[3] = rs.getString("apellidos");

registro[4] = rs.getString("direccion");

registro[5] = rs.getString("placa");

registro[6] = rs.getString("modelo");

registro[7] = rs.getString("año");

registro[8] = rs.getString("color");

registro[9] = rs2.getString("cedula");

registro[10] = rs2.getString("num_cuenta");

registro[11] = rs2.getString("monto");

registro[12] = rs2.getString("banco");

modelo.addRow(registro); }

tblConsultaEmpleado.setModel(modelo); }

catch (SQLException ex) {

JOptionPane.showMessageDialog(null, ex);} }

String id_actualizar = "";

void SerialCargarTablaClientes(String valor) {

String[] titulos = {"ID", "Cédula", "Nombres",

"Apellidos", "Dirección", "Placa", "Modelo", "Año",

"Color", "Cedula", "Numero Cuenta", "Monto", "Banco"};

String[] registro2 = new String[13];

String sSQL = "";

String sSQL2 = "";

modelo = new DefaultTableModel(null, titulos);

//Conectar con el servidor A

ConexionServerA mysql = new ConexionServerA();

Connection cn = mysql.Conectar();

//Conectar con el servidor B

ConexionServerB mysql2 = new ConexionServerB();

Connection cn2 = mysql2.Conectar();

//Base de Datos Servidor A

sSQL = "SELECT id_clt2, cedula2, nombres, apellidos,

direccion, placa, modelo, año, color FROM datos_servidora

" +

"WHERE CONCAT(cedula2, ' ',nombres, '

',apellidos, ' ',direccion, ' ',placa, ' ',modelo, ' ',año, ' ',color)

LIKE '%"+valor+"%'";

//Base de Datos Servidor B

sSQL2 = "SELECT id_clt, cedula, num_cuenta, monto,

banco FROM datos_servidorb " +

"WHERE CONCAT(cedula, ' ',num_cuenta, ' ',monto, '

',banco) LIKE '%"+valor+"%'";

try {

//Servidor A

Statement st = cn.createStatement();

ResultSet rs = st.executeQuery(sSQL);

//Servidor B

Statement st2 = cn2.createStatement();

ResultSet rs2 = st2.executeQuery(sSQL2);

while(rs.next() && rs2.next()) {

registro2[0] = rs.getString("id_clt2");

registro2[1] = rs.getString("cedula2");

registro2[2] = rs.getString("nombres");

registro2[3] = rs.getString("apellidos");

Page 27: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

27

registro2[4] = rs.getString("direccion");

registro2[5] = rs.getString("placa");

registro2[6] = rs.getString("modelo");

registro2[7] = rs.getString("año");

registro2[8] = rs.getString("color");

registro2[9] = rs2.getString("cedula");

registro2[10] = rs2.getString("num_cuenta");

registro2[11] = rs2.getString("monto");

registro2[12] = rs2.getString("banco");

modelo.addRow(registro2); }

tblConsultaEmpleado.setModel(modelo); }

catch (SQLException ex) {

JOptionPane.showMessageDialog(null, ex);}

//Manadar los datos al celular

try {

Parameters parameters = new Parameters(); //Create a

parameter object

parameters.setPort("COM9");//assigns the first port

found

parameters.setBaudRate(Baud._19200);//assigns

baud rate

parameters.setByteSize("8");// assigns byte size

parameters.setParity("N");// assigns parity

Com com = new Com(parameters);// With the

"parameters" creates a "Com"

com.sendString("Cedula: "+ registro2[1]+"\n"+"Cliente:

"+registro2[3]+" "+registro2[2]+"\n"+"\n"+"Modelo:

"+registro2[6]+"\n"+"Placa:

"+registro2[5]+"\n"+"\n"+"Banco:

"+registro2[12]+"\n"+"Monto: "+registro2[11]+" dolares");

clt=registro2[0];

cedulastring=registro2[1];

numstring=registro2[10];

bancostring=registro2[12];

montostring=registro2[11];

montoentero= Integer.parseInt (montostring);

montoentero=montoentero-2;

montostring=Integer.toString(montoentero);}

void BuscarClienteEditar(String id) {

String sSQL = "";

String ced = "", nom = "", ape = "", dir = "", pla= "",

mod = "", año = "", col = "";

ConexionServerA mysql = new ConexionServerA();

Connection cn = mysql.Conectar();

sSQL = "SELECT id_clt2, cedula2, nombres, apellidos,

direccion, placa, modelo, año, color FROM datos_servidora

" +

"WHERE id_clt2 = "+id;

try {

Statement st = cn.createStatement();

ResultSet rs = st.executeQuery(sSQL);

while(rs.next()) {

ced = rs.getString("cedula2");

nom = rs.getString("nombres");

ape = rs.getString("apellidos");

dir = rs.getString("direccion");

pla = rs.getString("placa");

mod = rs.getString("modelo");

año = rs.getString("año");

col = rs.getString("color"); }

txtCedula.setText(ced);

txtNombres.setText(nom);

txtApellidos.setText(ape);

txtDireccion.setText(dir);

txtPlaca.setText(pla);

txtModelo.setText(mod);

txtAño.setText(año);

txtColor.setText(col);

id_actualizar = id; }

catch (SQLException ex) {

JOptionPane.showMessageDialog(null, ex); } }

void serialport(){

try {

//Create a parameter object

Parameters parameters = new Parameters();//Create a

parameter object parameters.set

Port("COM9");//assigns the first port found

parameters.setBaudRate(Baud._19200);//assigns

baud rate

parameters.setByteSize("8");// assigns byte size

parameters.setParity("N");// assigns parity

Com com = new Com(parameters);// With the

"parameters" creates a "Com"

String j;

String k;

int i;

j="";

k="";

i=0;

String data;

while(true){

data=com.receiveSingleString();

System.out.println(data);

j=j+data;

System.out. println("CI: "+j);

if(j.endsWith("exit")){

break; //salir si se desconecta el dispositivo}

if(j.endsWith("play")){

// System.out.println(k) ;

ModificarMonto();

j=""; }

i=j.length();

if(i==10){

txtDato.setText(j);

//com.sendString(j);

com.close();

SerialCargarTablaClientes(j);

k=j;

j="";

i=0; } } //endif

com.close();

} catch (Exception ex) {

Logger.getLogger(Clientes.class.getName()).log(Level.SEV

ERE, null, ex); }

// String dato3 = txtDato.getText();

// SerialCargarTablaClientes(dato3); }

private void initComponents() {

mnEditar.setText("Modificar");

mnEditar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

mnEditarActionPerformed(evt); } });

jPopupMenu1.add(mnEditar);

setDefaultCloseOperation(javax.swing.WindowConstants.E

XIT_ON_CLOSE);

setCursor(new

java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

addKeyListener(new java.awt.event.KeyAdapter() {

public void keyPressed(java.awt.event.KeyEvent

evt) {

formKeyPressed(evt); } });

Page 28: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

28

jPanel1.setBorder(javax.swing.BorderFactory.createTitledB

order("Ingreso Datos Servidor A"));

jLabel1.setText("# Cédula :");

txtCedula.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtCedulaActionPerformed(evt); } });

jLabel2.setText("Nombres : ");

txtNombres.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtNombresActionPerformed(evt); } });

jLabel3.setText("Apellidos : ");

txtApellidos.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtApellidosActionPerformed(evt); } });

jLabel4.setText("Dirección : ");

txtDireccion.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtDireccionActionPerformed(evt); } });

btnNuevo.setText("Nuevo");

btnNuevo.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

btnNuevoActionPerformed(evt); } });

btnGuardar.setText("Guardar");

btnGuardar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

btnGuardarActionPerformed(evt); } });

btnCancelar.setText("Cancelar");

btnCancelar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

btnCancelarActionPerformed(evt); } });

btnSalir.setText("Salir");

btnSalir.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

btnSalirActionPerformed(evt); } });

txtColor.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtColorActionPerformed(evt); } });

jLabel5.setText("Color : ");

jLabel6.setText("Año : ");

txtAño.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtAñoActionPerformed(evt); } });

txtModelo.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtModeloActionPerformed(evt); } });

jLabel8.setText("Modelo : ");

jLabel9.setText("Placa :");

txtPlaca.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

txtPlacaActionPerformed(evt); } });

javax.swing.GroupLayout jPanel1Layout = new

javax.swing.GroupLayout(jPanel1);

jPanel1.setLayout(jPanel1Layout);

jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayo

ut.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(30, 30, 30)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.TRAILING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel4)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtDireccion,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel3)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtApellidos,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel2)

redGap(javax.swing.LayoutStyle.ComponentPlacement.UN

RELATED)

.addComponent(txtNombres,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))

addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel1)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtCedula,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel5)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtColor,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel6)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

Page 29: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

29

.addComponent(txtAño,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel8)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtModelo,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(jPanel1Layout.createSequentialGroup()

.addComponent(jLabel9)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtPlaca,

javax.swing.GroupLayout.PREFERRED_SIZE, 158,

javax.swing.GroupLayout.PREFERRED_SIZE))))

.addGroup(jPanel1Layout.createSequentialGroup()

.addContainerGap()

.addComponent(btnNuevo)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addComponent(btnGuardar)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addComponent(btnCancelar)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(btnSalir)))

.addContainerGap(23, Short.MAX_VALUE)) );

jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayo

ut.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addContainerGap()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(txtCedula,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel2)

.addComponent(txtNombres,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel3)

.addComponent(txtApellidos,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel4)

.addComponent(txtDireccion,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel9)

.addComponent(txtPlaca,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel8)

.addComponent(txtModelo,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel6)

.addComponent(txtAño,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel5)

.addComponent(txtColor,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.RELATED,

javax.swing.GroupLayout.DEFAULT_SIZE,

Short.MAX_VALUE)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(btnNuevo)

.addComponent(btnGuardar)

.addComponent(btnCancelar)

.addComponent(btnSalir))

.addContainerGap()) );

jPanel2.setBorder(javax.swing.BorderFactory.createTitledB

order("Consulta de Datos"));

tblConsultaEmpleado.setModel(new

javax.swing.table.DefaultTableModel(

new Object [][] { {}, {}, {}, {} },

new String [] { } ));

tblConsultaEmpleado.setComponentPopupMenu(jPopupMe

nu1);

jScrollPane1.setViewportView(tblConsultaEmpleado);

Page 30: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

30

jLabel7.setText("Buscar Cliente : ");

btnBuscar.setText("Buscar");

btnBuscar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

btnBuscarActionPerformed(evt);

}

});

btnBuscar1.setText("Actualizar");

btnBuscar1.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

btnBuscar1ActionPerformed(evt);

}

});

javax.swing.GroupLayout jPanel2Layout = new

javax.swing.GroupLayout(jPanel2);

jPanel2.setLayout(jPanel2Layout);

jPanel2Layout.setHorizontalGroup(

jPanel2Layout.createParallelGroup(javax.swing.GroupLayo

ut.Alignment.LEADING)

.addGroup(jPanel2Layout.createSequentialGroup()

.addContainerGap()

.addComponent(jScrollPane1,

javax.swing.GroupLayout.DEFAULT_SIZE, 1153,

Short.MAX_VALUE)

.addContainerGap())

.addGroup(jPanel2Layout.createSequentialGroup()

.addGap(316, 316, 316)

.addComponent(jLabel7)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtBuscar,

javax.swing.GroupLayout.PREFERRED_SIZE, 145,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(btnBuscar)

.addGap(18, 18, 18)

.addComponent(btnBuscar1)

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SI

ZE, Short.MAX_VALUE))

);

jPanel2Layout.setVerticalGroup(

jPanel2Layout.createParallelGroup(javax.swing.GroupLayo

ut.Alignment.LEADING)

.addGroup(jPanel2Layout.createSequentialGroup()

.addContainerGap()

.addGroup(jPanel2Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.BASELINE)

.addComponent(jLabel7)

.addComponent(txtBuscar,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(btnBuscar)

.addComponent(btnBuscar1))

.addGap(18, 18, 18)

.addComponent(jScrollPane1,

javax.swing.GroupLayout.PREFERRED_SIZE, 269,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(14, Short.MAX_VALUE))

);

jLabel10.setBackground(new java.awt.Color(0, 102,

255));

jLabel10.setFont(new java.awt.Font("Tahoma", 0, 48));

// NOI18N

jLabel10.setForeground(new java.awt.Color(255, 0,

0));

jLabel10.setText(" SERVIDOR A");

jLabel10.setBorder(javax.swing.BorderFactory.createLineB

order(new java.awt.Color(0, 0, 0)));

jLabel10.setHorizontalTextPosition(javax.swing.SwingCons

tants.CENTER);

jPanel3.setBorder(javax.swing.BorderFactory.createTitledB

order(javax.swing.BorderFactory.createTitledBorder("Comu

nicación Movil")));

jbtnHabilitar.setText("Habilitar Bluetooth");

jbtnHabilitar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent evt) {

jbtnHabilitarActionPerformed(evt);

}

});

javax.swing.GroupLayout jPanel3Layout = new

javax.swing.GroupLayout(jPanel3);

jPanel3.setLayout(jPanel3Layout);

jPanel3Layout.setHorizontalGroup(

jPanel3Layout.createParallelGroup(javax.swing.GroupLayo

ut.Alignment.LEADING)

.addGroup(jPanel3Layout.createSequentialGroup()

.addContainerGap()

.addGroup(jPanel3Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.LEADING)

.addComponent(txtDato,

javax.swing.GroupLayout.PREFERRED_SIZE, 121,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jbtnHabilitar,

javax.swing.GroupLayout.PREFERRED_SIZE, 137,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addContainerGap(58, Short.MAX_VALUE))

);

jPanel3Layout.setVerticalGroup(

jPanel3Layout.createParallelGroup(javax.swing.GroupLayo

ut.Alignment.LEADING)

.addGroup(jPanel3Layout.createSequentialGroup()

.addComponent(jbtnHabilitar)

Page 31: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

31

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlac

ement.UNRELATED)

.addComponent(txtDato,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(0, 0, Short.MAX_VALUE))

);

javax.swing.GroupLayout layout = new

javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Align

ment.LEADING)

.addComponent(jPanel2,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

Short.MAX_VALUE)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILIN

G, layout.createSequentialGroup()

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SI

ZE, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLa

yout.Alignment.LEADING)

.addComponent(jLabel10,

javax.swing.GroupLayout.PREFERRED_SIZE, 325,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addGroup(layout.createSequentialGroup()

.addComponent(jPanel1,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(54, 54, 54)

.addComponent(jPanel3,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)))

.addGap(271, 271, 271))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Align

ment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jLabel10,

javax.swing.GroupLayout.PREFERRED_SIZE, 79,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(28, 28, 28)

.addGroup(layout.createParallelGroup(javax.swing.GroupLa

yout.Alignment.LEADING)

.addComponent(jPanel1,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

Short.MAX_VALUE)

.addComponent(jPanel3,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

Short.MAX_VALUE))

.addGap(29, 29, 29)

.addComponent(jPanel2,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap())

);

jPanel2.getAccessibleContext().setAccessibleName("Consul

ta de Empleado");

setBounds(550, 250, 1201, 763);

}// </editor-fold>

private void

btnSalirActionPerformed(java.awt.event.ActionEvent evt) {

this.dispose();

}

private void

btnNuevoActionPerformed(java.awt.event.ActionEvent evt)

{

habilitar();

}

private void

btnCancelarActionPerformed(java.awt.event.ActionEvent

evt) {

inhabilitar();

}

private void

txtCedulaActionPerformed(java.awt.event.ActionEvent evt)

{

txtCedula.transferFocus();

}

private void

txtNombresActionPerformed(java.awt.event.ActionEvent

evt) {

txtNombres.transferFocus();

}

private void

txtApellidosActionPerformed(java.awt.event.ActionEvent

evt) {

txtApellidos.transferFocus();

}

private void

txtDireccionActionPerformed(java.awt.event.ActionEvent

evt) {

txtDireccion.transferFocus();

}

String accion = "Insertar";

private void

btnGuardarActionPerformed(java.awt.event.ActionEvent

evt) {

ConexionServerA mysql = new ConexionServerA();

Connection cn = mysql.Conectar();

String ced, nom, ape, dir, pla, mod, año, col;

String sSQL = "";

String mensaje = "";

ced = txtCedula.getText();

Page 32: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

32

nom = txtNombres.getText();

ape = txtApellidos.getText();

dir = txtDireccion.getText();

pla = txtPlaca.getText();

mod = txtModelo.getText();

año = txtAño.getText();

col = txtColor.getText();

if(accion.equals("Insertar"))

{

sSQL = "INSERT INTO datos_servidora(cedula2,

nombres, apellidos, direccion, placa, modelo, año, color)" +

"VALUES(?, ?, ?, ?, ?, ?, ?, ?)";

mensaje = "Los datos se han Insertado de Manera

Satisfactoria...";

}

else if(accion.equals("Modificar"))

{

sSQL = "UPDATE datos_servidora " +

"SET cedula2 = ?," +

"nombres = ?," +

"apellidos = ?," +

"direccion = ?," +

"placa = ?," +

"modelo = ?," +

"año = ?," +

"color = ? " +

"WHERE id_clt2 = "+id_actualizar;

mensaje = "Los datos se han Modificado Correctamente...";

accion = "Insertar"; }

try {

PreparedStatement pst =

cn.prepareStatement(sSQL);

pst.setString(1, ced);

pst.setString(2, nom);

pst.setString(3, ape);

pst.setString(4, dir);

pst.setString(5, pla);

pst.setString(6, mod);

pst.setString(7, año);

pst.setString(8, col);

int n = pst.executeUpdate();

if(n > 0) {

JOptionPane.showMessageDialog(null, mensaje);

CargarTablaClientes(""); } }

catch (SQLException ex) {

JOptionPane.showMessageDialog(null, ex); }

}

void ModificarMonto(){

ConexionServerB mysql = new ConexionServerB();

Connection cn = mysql.Conectar();

String ced,num, banco;

String mont="";

String sSQL = "";

String mensaje = "";

ced=cedulastring;

num=numstring;

banco=bancostring;

mont=montostring;

System.out.println(clt);

sSQL = "UPDATE datos_servidorb " +

"SET cedula = ?," +

"num_cuenta = ?," +

"monto = ?," +

"banco = ? " +

"WHERE id_clt = "+clt;

mensaje = "Los datos se han Modificado de Manera

Satisfactoria...";

accion = "Insertar";

// }

try {

PreparedStatement pst =

cn.prepareStatement(sSQL);

pst.setString(1, ced);

pst.setString(2, num);

pst.setString(3, mont);

pst.setString(4, banco);

int n = pst.executeUpdate(); }

catch (SQLException ex) {

JOptionPane.showMessageDialog(null, ex); } }

SERVIDOR B

package Formularios; // librerias

import BaseDatos.ConexionServerA;

import BaseDatos.ConexionServerB;

import java.sql.*;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JOptionPane;

import javax.swing.table.DefaultTableModel;

Public class Clientes extends

javax.swing.JFrame {

DefaultTableModel modelo;

/** Creates new form Clientes */

public Clientes() {

initComponents();

CargarTablaClientes("");

inhabilitar(); }

void CargarTablaClientes(String valor) {

String[] titulos = {"ID", "Cédula",

"Número Cuenta", "Monto", "Banco", "Cédula",

"Nombres", "Apellidos", "Dirección", "Placa",

"Modelo", "Año", "Color"};

String[] registro = new String[13];

String sSQL = "";

String sSQL2 = "";

modelo = new DefaultTableModel(null,

titulos);

//Conectar con el servidor A

ConexionServerA mysql2 = new

ConexionServerA();

Connection cn2 = mysql2.Conectar();

//Conectar con el servidor B

ConexionServerB mysql = new

ConexionServerB();

Connection cn = mysql.Conectar();

//Base de Datos Servidor B

sSQL = "SELECT id_clt, cedula,

num_cuenta, monto, banco FROM

datos_servidorb " +

"WHERE CONCAT(cedula, '

',num_cuenta, ' ',monto, ' ',banco) LIKE

'%"+valor+"%'";

//Base de Datos Servidor A

Page 33: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

33

sSQL2 = "SELECT id_clt2, cedula2,

nombres, apellidos, direccion, placa, modelo,

año, color FROM datos_servidora " +

"WHERE CONCAT(cedula2, '

',nombres, ' ',apellidos, ' ',direccion, ' ',placa, '

',modelo, ' ',año, ' ',color) LIKE '%"+valor+"%'";

try {

//Servidor B

Statement st = cn.createStatement();

ResultSet rs = st.executeQuery(sSQL);

//Servidor A

Statement st2 = cn2.createStatement();

ResultSet rs2 =

st2.executeQuery(sSQL2);

while(rs.next() && rs2.next()) {

registro[0] = rs.getString("id_clt");

registro[1] = rs.getString("cedula");

registro[2] =

rs.getString("num_cuenta");

registro[3] = rs.getString("monto");

registro[4] = rs.getString("banco");

registro[5] = rs2.getString("cedula2");

registro[6] =

rs2.getString("nombres");

registro[7] =

rs2.getString("apellidos");

registro[8] =

rs2.getString("direccion");

registro[9] = rs2.getString("placa");

registro[10] =

rs2.getString("modelo");

registro[11] = rs2.getString("año");

registro[12] = rs2.getString("color");

modelo.addRow(registro) }

tblConsultaEmpleado.setModel(modelo); }

catch (SQLException ex) {

JOptionPane.showMessageDialog(null,

ex); } }

String id_actualizar = "";

void BuscarClienteEditar(String id) {

String sSQL = "";

String ap1 = "", ap2 = "", nom1 = "", nom2

= "", fn = "", gen = "";

ConexionServerB mysql = new

ConexionServerB();

Connection cn = mysql.Conectar();

sSQL = "SELECT id_clt, cedula,

num_cuenta, monto, banco FROM

datos_servidorb " +

"WHERE id_clt = "+id;

try {

Statement st = cn.createStatement();

ResultSet rs = st.executeQuery(sSQL);

while(rs.next()) {

ap1 = rs.getString("cedula");

ap2 = rs.getString("num_cuenta");

nom1 = rs.getString("monto");

nom2 = rs.getString("banco");

//fn = rs.getString("fecha_nac");

//gen = rs.getString("genero");

}

txtCedula.setText(ap1);

txtCuenta.setText(ap2);

txtMonto.setText(nom1);

txtBanco.setText(nom2);

id_actualizar = id; }

catch (SQLException ex) {

JOptionPane.showMessageDialog(null,

ex); } }

void habilitar() // HABILITA CUANDO SE

PULSA NUEVO Y DEJA EN BLANCO LOS

TEXT {

txtCedula.setEnabled(true);

txtCuenta.setEnabled(true);

txtMonto.setEnabled(true);

txtBanco.setEnabled(true);

txtCedula.setText("");

txtCuenta.setText("");

txtMonto.setText("");

txtBanco.setText("");

btnGuardar.setEnabled(true);

btnCancelar.setEnabled(true);

txtCedula.requestFocus(); }

void inhabilitar() {

txtCedula.setEnabled(false);

txtCuenta.setEnabled(false);

txtMonto.setEnabled(false);

txtBanco.setEnabled(false);

txtCedula.setText("");

txtCuenta.setText("");

txtMonto.setText("");

txtBanco.setText("");

btnGuardar.setEnabled(false);

btnCancelar.setEnabled(false); }

private void initComponents() {

jPopupMenu1 = new

javax.swing.JPopupMenu();

mnEditar = new javax.swing.JMenuItem();

jLabel10 = new javax.swing.JLabel();

jPanel1 = new javax.swing.JPanel();

jLabel1 = new javax.swing.JLabel();

txtCedula = new javax.swing.JTextField();

jLabel2 = new javax.swing.JLabel();

txtCuenta = new javax.swing.JTextField();

jLabel3 = new javax.swing.JLabel();

txtMonto = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

txtBanco = new javax.swing.JTextField();

btnNuevo = new javax.swing.JButton();

btnGuardar = new javax.swing.JButton();

btnCancelar = new javax.swing.JButton();

btnSalir = new javax.swing.JButton();

jPanel2 = new javax.swing.JPanel();

jScrollPane1 = new

javax.swing.JScrollPane();

tblConsultaEmpleado = new

javax.swing.JTable();

jLabel7 = new javax.swing.JLabel();

Page 34: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

34

txtBuscar = new javax.swing.JTextField();

btnBuscar = new javax.swing.JButton();

btnBuscar1 = new javax.swing.JButton();

jLabel11 = new javax.swing.JLabel();

mnEditar.setText("Modificar");

mnEditar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

mnEditarActionPerformed(evt);

} });

jPopupMenu1.add(mnEditar);

jLabel10.setBackground(new

java.awt.Color(0, 102, 255));

jLabel10.setFont(new

java.awt.Font("Tahoma", 0, 48)); // NOI18N

jLabel10.setForeground(new

java.awt.Color(255, 0, 0));

jLabel10.setText(" SERVIDOR A");

jLabel10.setBorder(javax.swing.BorderFactory.

createLineBorder(new java.awt.Color(0, 0, 0)));

jLabel10.setHorizontalTextPosition(javax.swing

.SwingConstants.CENTER);

setDefaultCloseOperation(javax.swing.Window

Constants.EXIT_ON_CLOSE);

setCursor(new

java.awt.Cursor(java.awt.Cursor.DEFAULT_C

URSOR));

jPanel1.setBorder(javax.swing.BorderFactory.cr

eateTitledBorder("Ingreso Datos Servidor B"));

jLabel1.setText("# Cédula :");

txtCedula.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

txtCedulaActionPerformed(evt);

} });

jLabel2.setText("Número Cuenta : ");

txtCuenta.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

txtCuentaActionPerformed(evt);

} });

jLabel3.setText("Monto : ");

txtMonto.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

txtMontoActionPerformed(evt);

} });

jLabel4.setText("Banco : ");

txtBanco.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

txtBancoActionPerformed(evt);

} });

btnNuevo.setText("Nuevo");

btnNuevo.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

btnNuevoActionPerformed(evt);

} });

btnGuardar.setText("Guardar");

btnGuardar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

btnGuardarActionPerformed(evt);

} });

btnCancelar.setText("Cancelar");

btnCancelar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

btnCancelarActionPerformed(evt);

} });

btnSalir.setText("Salir");

btnSalir.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

btnSalirActionPerformed(evt);

} });

javax.swing.GroupLayout jPanel1Layout =

new javax.swing.GroupLayout(jPanel1);

jPanel1.setLayout(jPanel1Layout);

jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addGroup(jPanel1Layout.createParallelGroup(j

avax.swing.GroupLayout.Alignment.LEADING

)

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addGap(30, 30, 30)

.addGroup(jPanel1Layout.createParallelGroup(j

Page 35: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

35

avax.swing.GroupLayout.Alignment.TRAILIN

G)

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addComponent(jLabel4)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.UNRELATED)

.addComponent(txtBanco,

javax.swing.GroupLayout.PREFERRED_SIZE,

158,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addComponent(jLabel3)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.UNRELATED)

.addComponent(txtMonto,

javax.swing.GroupLayout.PREFERRED_SIZE,

158,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addComponent(jLabel2)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.UNRELATED)

.addComponent(txtCuenta,

javax.swing.GroupLayout.PREFERRED_SIZE,

158,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addComponent(jLabel1)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.UNRELATED)

.addComponent(txtCedula,

javax.swing.GroupLayout.PREFERRED_SIZE,

158,

javax.swing.GroupLayout.PREFERRED_SIZE)

)))

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addContainerGap()

.addComponent(btnNuevo)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.RELATED)

.addComponent(btnGuardar)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.RELATED)

.addComponent(btnCancelar)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.UNRELATED)

.addComponent(btnSalir)))

.addContainerGap(18,

Short.MAX_VALUE)) );

jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGrou

p()

.addContainerGap()

addGroup(jPanel1Layout.createParallelGroup(ja

vax.swing.GroupLayout.Alignment.BASELINE

)

.addComponent(jLabel1)

.addComponent(txtCedula,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(j

avax.swing.GroupLayout.Alignment.BASELIN

E)

.addComponent(jLabel2)

.addComponent(txtCuenta,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(j

avax.swing.GroupLayout.Alignment.BASELIN

E)

.addComponent(jLabel3)

.addComponent(txtMonto,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.RELATED)

.addGroup(jPanel1Layout.createParallelGroup(j

Page 36: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

36

avax.swing.GroupLayout.Alignment.BASELIN

E)

.addComponent(jLabel4)

.addComponent(txtBanco,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.RELATED, 37,

Short.MAX_VALUE)

.addGroup(jPanel1Layout.createParallelGroup(j

avax.swing.GroupLayout.Alignment.BASELIN

E)

.addComponent(btnNuevo)

.addComponent(btnGuardar)

.addComponent(btnCancelar)

.addComponent(btnSalir))

.addContainerGap()) );

jPanel2.setBorder(javax.swing.BorderFactory.cr

eateTitledBorder("Consulta de Datos"));

tblConsultaEmpleado.setModel(new

javax.swing.table.DefaultTableModel(

new Object [][] { {},

{}, {}, {} },

new String [] { } ));

tblConsultaEmpleado.setComponentPopupMen

u(jPopupMenu1);

jScrollPane1.setViewportView(tblConsultaEmp

leado);

jLabel7.setText("Buscar Cliente : ");

btnBuscar.setText("Buscar");

btnBuscar.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

btnBuscarActionPerformed(evt);

} });

btnBuscar1.setText("Actualizar");

btnBuscar1.addActionListener(new

java.awt.event.ActionListener() {

public void

actionPerformed(java.awt.event.ActionEvent

evt) {

btnBuscar1ActionPerformed(evt);

} });

javax.swing.GroupLayout jPanel2Layout =

new javax.swing.GroupLayout(jPanel2);

jPanel2.setLayout(jPanel2Layout);

jPanel2Layout.setHorizontalGroup(

jPanel2Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.LEADING)

.addGroup(jPanel2Layout.createSequentialGrou

p()

.addContainerGap()

.addComponent(jScrollPane1,

javax.swing.GroupLayout.DEFAULT_SIZE,

1134, Short.MAX_VALUE)

.addContainerGap())

.addGroup(javax.swing.GroupLayout.Alignmen

t.TRAILING,

jPanel2Layout.createSequentialGroup()

.addContainerGap(javax.swing.GroupLayout.D

EFAULT_SIZE, Short.MAX_VALUE)

.addComponent(jLabel7)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.UNRELATED)

.addComponent(txtBuscar,

javax.swing.GroupLayout.PREFERRED_SIZE,

145,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.UNRELATED)

.addComponent(btnBuscar)

.addGap(18, 18, 18)

.addComponent(btnBuscar1)

.addGap(371, 371, 371)) );

jPanel2Layout.setVerticalGroup(

jPanel2Layout.createParallelGroup(javax.swing.

GroupLayout.Alignment.LEADING)

.addGroup(jPanel2Layout.createSequentialGrou

p()

.addContainerGap()

.addGroup(jPanel2Layout.createParallelGroup(j

avax.swing.GroupLayout.Alignment.BASELIN

E)

.addComponent(jLabel7)

.addComponent(txtBuscar,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(btnBuscar)

.addComponent(btnBuscar1))

.addGap(18, 18, 18)

.addComponent(jScrollPane1,

javax.swing.GroupLayout.PREFERRED_SIZE,

269,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(25,

Short.MAX_VALUE)) );

jLabel11.setBackground(new

java.awt.Color(0, 102, 255));

jLabel11.setFont(new

java.awt.Font("Tahoma", 0, 48)); // NOI18N

Page 37: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

37

jLabel11.setForeground(new

java.awt.Color(0, 51, 255));

jLabel11.setText(" SERVIDOR B");

jLabel11.setBorder(javax.swing.BorderFactory.

createLineBorder(new java.awt.Color(0, 0, 0)));

jLabel11.setHorizontalTextPosition(javax.swing

.SwingConstants.CENTER);

javax.swing.GroupLayout layout = new

javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupL

ayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jPanel2,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

Short.MAX_VALUE)

.addContainerGap())

.addGroup(javax.swing.GroupLayout.Alignmen

t.TRAILING, layout.createSequentialGroup()

.addContainerGap(javax.swing.GroupLayout.D

EFAULT_SIZE, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swi

ng.GroupLayout.Alignment.TRAILING)

.addComponent(jPanel1,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel11,

javax.swing.GroupLayout.PREFERRED_SIZE,

325,

javax.swing.GroupLayout.PREFERRED_SIZE)

)

.addGap(410, 410, 410)) );

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupL

ayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jLabel11,

javax.swing.GroupLayout.PREFERRED_SIZE,

79,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.Co

mponentPlacement.RELATED, 33,

Short.MAX_VALUE)

.addComponent(jPanel1,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(18, 18, 18)

.addComponent(jPanel2,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap()) );

jPanel2.getAccessibleContext().setAccessibleN

ame("Consulta de Empleado");

setBounds(550, 250, 1202, 759); }//

</editor-fold>

private void

btnSalirActionPerformed(java.awt.event.Action

Event evt) {

this.dispose(); }

private void

btnNuevoActionPerformed(java.awt.event.Actio

nEvent evt) {

habilitar(); }

private void

btnCancelarActionPerformed(java.awt.event.Ac

tionEvent evt) {

inhabilitar(); }

private void

txtCedulaActionPerformed(java.awt.event.Actio

nEvent evt) {

txtCedula.transferFocus(); }

private void

txtCuentaActionPerformed(java.awt.event.Actio

nEvent evt) {

txtCuenta.transferFocus(); }

private void

txtMontoActionPerformed(java.awt.event.Actio

nEvent evt) {

txtMonto.transferFocus(); }

private void

txtBancoActionPerformed(java.awt.event.Actio

nEvent evt) {

txtBanco.transferFocus(); }

String accion = "Insertar";

private void

btnGuardarActionPerformed(java.awt.event.Act

ionEvent evt) {

ConexionServerB mysql = new

ConexionServerB();

Connection cn = mysql.Conectar();

String ap1, ap2, nom1, nom2;

String sSQL = "";

String mensaje = "";

ap1 = txtCedula.getText();

ap2 = txtCuenta.getText();

nom1 = txtMonto.getText();

nom2 = txtBanco.getText();

if(accion.equals("Insertar")) {

sSQL = "INSERT INTO

datos_servidorb(cedula, num_cuenta, monto,

banco)" +

"VALUES(?, ?, ?, ?)";

Page 38: Proyecto Final Modelo

INTEGRANTES: SEBASTIÁN CAMPOVERDE, EDWIN GAMBOA

JORGE DUCHITANGA, MARIELA JIMBO

REDES DE CÓMPUTO I GRUPO: 1

38

mensaje = "Los datos se han Insertado de

Manera Satisfactoria..."; }

else if(accion.equals("Modificar")) {

sSQL = "UPDATE datos_servidorb " +

"SET cedula = ?," +

"num_cuenta = ?," +

"monto = ?," +

"banco = ? " +

"WHERE id_clt = "+id_actualizar;

mensaje = "Los datos se han Modificado

de Manera Satisfactoria...";

accion = "Insertar"; }

try {

PreparedStatement pst =

cn.prepareStatement(sSQL);

pst.setString(1, ap1);

pst.setString(2, ap2);

pst.setString(3, nom1);

pst.setString(4, nom2);

// pst.setString(5, fn);

// pst.setString(6, gen);

int n = pst.executeUpdate();

if(n > 0) {

JOptionPane.showMessageDialog(null,

mensaje);

CargarTablaClientes(""); }

}

catch (SQLException ex) {

JOptionPane.showMessageDialog(null,

ex); } }

private void

btnBuscarActionPerformed(java.awt.event.Acti

onEvent evt) {

String valor = txtBuscar.getText();

CargarTablaClientes(valor); }

private void

mnEditarActionPerformed(java.awt.event.Actio

nEvent evt) {

int filasel;

String id;

try {

filasel =

tblConsultaEmpleado.getSelectedRow();

if(filasel == -1) {

JOptionPane.showMessageDialog(null, "No se

ha seleccionado ninguna fila"); }

else {

accion = "Modificar";

modelo = (DefaultTableModel)

tblConsultaEmpleado.getModel();

id = (String)

modelo.getValueAt(filasel, 0);

habilitar();

BuscarClienteEditar(id); }

}

catch (Exception e) { } }

private void

btnBuscar1ActionPerformed(java.awt.event.Act

ionEvent evt) {

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new

Runnable() {

public void run() {

new Clientes().setVisible(true);

} }); }

// Variables declaration - do not modify

private javax.swing.JButton btnBuscar;

private javax.swing.JButton btnBuscar1;

private javax.swing.JButton btnCancelar;

private javax.swing.JButton btnGuardar;

private javax.swing.JButton btnNuevo;

private javax.swing.JButton btnSalir;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel10;

private javax.swing.JLabel jLabel11;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel7;

private javax.swing.JPanel jPanel1;

private javax.swing.JPanel jPanel2;

private javax.swing.JPopupMenu

jPopupMenu1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JMenuItem mnEditar;

private javax.swing.JTable

tblConsultaEmpleado;

private javax.swing.JTextField txtBanco;

private javax.swing.JTextField txtBuscar;

private javax.swing.JTextField txtCedula;

private javax.swing.JTextField txtCuenta;

private javax.swing.JTextField txtMonto;

// End of variables declaration }