Está en la página 1de 14

Taller de Ingeniería de Software

SEMANA 6
Ingeniería de Software:
Ejemplo de Desarrollo
del Segundo Módulo del
Proyecto

Todos los derechos de autor son de la exclusiva propiedad de IACC o de los otorgantes de sus licencias. No está
permitido copiar, reproducir, reeditar, descargar, publicar, emitir, difundir, poner a disposición del público ni 1
ESTE DOCUMENTO
utilizar los CONTIENE
contenidos para fines EJEMPLOS
comerciales de ninguna clase. DE LA
SEMANA 1
Ejemplo de Desarrollo del Segundo Módulo del Proyecto
Para visualizar el ejemplo de desarrollo del segundo módulo se deben seguir las siguientes
instrucciones:

Descargar archivo modulo2.jar

Ejecutar modulo2.jar

Se debe usar algún usuario creado con el módulo 1 para autentificarse.

Código del Ejemplo


import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.JButton;
import javax.swing.JPasswordField;

public class main extends JFrame {


private static final long serialVersionUID = 1L;
private JPanel contentPane;
private NuevoUsuario nuevoUsuario;
BDConn bd = new BDConn();
private JTextField txtUsuario = new JTextField();
private JPasswordField txtClave;

2
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
/**
* Inicia la Aplicación.
*/
public static void main(String[] args) {
try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
main frame = new main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Formulario de Autenticación
*/
public main() {

bd.crearBD();
setTitle("Sistema de rendiciones de proyectos");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 832, 269);
setLocationRelativeTo(null);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnArchivo = new JMenu("Sistema");
menuBar.add(mnArchivo);
if (nuevoUsuario==null) {
nuevoUsuario = new NuevoUsuario ();
nuevoUsuario.setVisible(false);
}

3
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
JMenuItem mntmNuevo = new JMenuItem("Nuevo Usuario");
mntmNuevo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
nuevoUsuario.setVisible(true);
}
});
mnArchivo.add(mntmNuevo);

JMenuItem mntmSalir = new JMenuItem("Salir");


mntmSalir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mnArchivo.add(mntmSalir);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JPanel panel_1 = new JPanel();
panel_1.setForeground(new Color(192, 192, 192));
panel_1.setBorder(new LineBorder(new Color(192, 192, 192)));
JLabel lblUsuario = new JLabel("Usuario");
JLabel lblClave = new JLabel("Clave");
final JLabel lblUsuarioInvalido = new JLabel("* Usuario invalido");
lblUsuarioInvalido.setVisible(false);
JButton btnIngresar = new JButton("Ingresar");
btnIngresar.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0) {
if (!bd.comprobarUsuario (txtUsuario.getText(),
txtClave.getText())) {
lblUsuarioInvalido.setVisible(true);

}
else {
lblUsuarioInvalido.setVisible(false);
txtUsuario.setText("");
txtClave.setText("");
nuevoUsuario.setVisible(true);
}

4
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
});
txtClave = new JPasswordField();
lblUsuarioInvalido.setForeground(Color.RED);
JLabel lblOlvidasteTu = new JLabel("\u00BF Olvidaste tu clave ?");
lblOlvidasteTu.setForeground(Color.BLUE);
JLabel lblCambiarClave = new JLabel("Cambiar clave");
lblCambiarClave.setForeground(Color.BLUE);
JLabel lblSistemaDeRendiciones = new JLabel("SISTEMA DE RENDICIONES DE
PROYECTOS");
GroupLayout gl_panel_1 = new GroupLayout(panel_1);
gl_panel_1.setHorizontalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_1.createSequentialGroup()
.addGap(28)
.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
.addComponent(lblUsuario)
.addComponent(lblClave))
.addGap(42)
.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
.addComponent(lblSistemaDeRendiciones)
.addGroup(gl_panel_1.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_1.createSequentialGroup()
.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING, false)
.addComponent(txtClave, Alignment.LEADING)
.addComponent(txtUsuario, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 116,
Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblUsuarioInvalido))
.addComponent(btnIngresar,
GroupLayout.PREFERRED_SIZE, 93, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel_1.createSequentialGroup()
.addComponent(lblOlvidasteTu)
.addGap(18)
.addComponent(lblCambiarClave, GroupLayout.PREFERRED_SIZE, 102,
GroupLayout.PREFERRED_SIZE)))))
.addGap(120))
);
gl_panel_1.setVerticalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_1.createSequentialGroup()

5
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
.addGap(7)
.addComponent(lblSistemaDeRendiciones)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
.addComponent(txtUsuario,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblUsuarioInvalido)
.addComponent(lblUsuario))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
.addComponent(txtClave,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblClave))
.addGap(18)
.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
.addComponent(lblOlvidasteTu)
.addComponent(lblCambiarClave))
.addGap(18)
.addComponent(btnIngresar)
.addGap(34))
);
panel_1.setLayout(gl_panel_1);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 450,
Short.MAX_VALUE)
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 200,
Short.MAX_VALUE)
);
contentPane.setLayout(gl_contentPane);
pack();
}
}
/* BD */
import java.sql.*;
public class BDConn {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";

6
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
static final String USER = "ejemplo";
static final String PASS = "ejemplo";
Connection conn = null;
Statement stmt = null;
public BDConn () {
}
/* Formulario de Creación de usuarios */
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

public class NuevoUsuario extends JFrame {


private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField ingresoNombre;
private JTextField ingresoUsuario;
private JPasswordField ingresoClave;
BDConn bd = new BDConn();
public NuevoUsuario() {
setResizable(false);
setTitle("Nuevo usuario");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 345, 214);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
JLabel lbl1 = new JLabel("Nombre");
JLabel lbl2 = new JLabel("Usuario");
JLabel lbl3 = new JLabel("Clave");
JLabel lbl4 = new JLabel("Perfil");

7
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
final JLabel lblError = new JLabel("* Error el usuario ya existe");
lblError.setVisible(false);
final JComboBox ingresoPerfil = new JComboBox();
ingresoPerfil.addItem("Tecnico");
ingresoPerfil.addItem("Financiero");
JButton btnVolver = new JButton("Crear");
btnVolver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
boolean respuesta =
bd.ingresarUsuario(ingresoNombre.getText(), ingresoUsuario.getText(),
ingresoClave.getText(), ingresoPerfil.getSelectedItem().toString());

if (respuesta == false) {
lblError.setVisible(true);
}
else {
lblError.setVisible(false);
setVisible(false);
ingresoNombre.setText("");
ingresoUsuario.setText("");
ingresoClave.setText("");
ingresoPerfil.setSelectedIndex(0);
}
}
});

JButton btnCancelar = new JButton("Cancelar");


btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ingresoNombre.setText("");
ingresoUsuario.setText("");
ingresoClave.setText("");
ingresoPerfil.setSelectedIndex(0);
setVisible(false);
}
});
ingresoNombre = new JTextField();
ingresoNombre.setColumns(10);
ingresoUsuario = new JTextField();
ingresoUsuario.setColumns(10);
ingresoClave = new JPasswordField();

8
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
lblError.setForeground(Color.RED);
JLabel lblSistemaDeRendiciones = new JLabel("SISTEMA DE RENDICIONES DE
PROYECTOS");

GroupLayout gl_contentPane = new GroupLayout(contentPane);


gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(31)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(lbl2)
.addComponent(lbl3)
.addComponent(lbl4))
.addGap(18)
.addGroup(gl_contentPane
.createParallelGroup(Alignment.LEADING, false)
.addComponent(ingresoUsuario, GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
.addComponent(ingresoClave)
.addComponent(ingresoPerfil, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(31)
.addComponent(lblError))
.addGroup(gl_contentPane.createS
equentialGroup()
.addComponent(lbl1)
.addGap(18)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(lblSistemaDeRendiciones)
.addComponent(ingresoNombre, GroupLayout.PREFERRED_SIZE, 413,
GroupLayout.PREFERRED_SIZE)))))
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(187)
.addComponent(btnVolver)
.addGap(57)
.addComponent(btnCancelar)))
.addGap(31))
);
gl_contentPane.setVerticalGroup(

9
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblSistemaDeRendiciones)
.addPreferredGap(ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lbl1)
.addComponent(ingresoNombre,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lbl2)
.addComponent(ingresoUsuario,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblError))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lbl3)
.addComponent(ingresoClave,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(lbl4)
.addComponent(ingresoPerfil,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(30)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(btnCancelar)
.addComponent(btnVolver)))
);
contentPane.setLayout(gl_contentPane);
pack();
}
}

/* Creación de BD y Tablas*/
public void crearBD () {
try{
abrirConexion();
if (conn!=null && stmt!=null) {
System.out.println("Creando Base de datos...");

10
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
// String sql = "DROP DATABASE IF EXISTS Srenproy";
stmt.executeUpdate(sql);
sql = "CREATE DATABASE Srenproy";
stmt.executeUpdate(sql);
sql = "DROP TABLE IF EXISTS Srenproy.Usuarios";
stmt.executeUpdate(sql);
sql = "CREATE TABLE Srenproy.Usuarios " +
"(unombre varchar(60), " +
" uusuario varchar(15), " +
" uclave varchar(15), " +
" uperfil varchar(15), " +
" PRIMARY KEY ( uusuario ))";
stmt.executeUpdate(sql);
sql = "DROP TABLE IF EXISTS Srenproy.Proyectos";
stmt.executeUpdate(sql);
sql = "CREATE TABLE Srenproy.Proyectos " +
"(pID_proy varchar(10), " +
" pnom_proy varchar(30), " +
" pinf_tec_proy varchar(40), " +
" pinf_fin_proy varchar(40), " +
" pjefe_proy varchar(40), " +
" PRIMARY KEY ( pID_proy ))";
stmt.executeUpdate(sql);
System.out.println("Base de datos creada...");
}
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Terminado");
cerrarConexion();
}
/* valida existencia de Usuario */
public boolean comprobarUsuario (String usuario, String clave) {
abrirConexion();
try{
if (conn!=null && stmt!=null) {
System.out.println("Comprobando usuario...");

11
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
String sql = "SELECT * FROM Srenproy.Usuarios where uusuario='"
+ usuario + "' and uclave='" + clave +"';";
ResultSet rs = stmt.executeQuery(sql) ;
int rowCount = 0;
while ( rs.next()) {
rowCount++;
}
System.out.println(rowCount + " registros encontrados");
System.out.println("Terminado");
if (rowCount!=0) return true;
else return false;
}
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
cerrarConexion();
return (false);
}

/* Creción de Usuario en BD */
public boolean ingresarUsuario (String nombre, String usuario, String clave, String perfil) {
abrirConexion();
int rowCount = 0;
try{
if (conn!=null && stmt!=null) {
System.out.println("Creando usuario...");
String sql = "SELECT * FROM Srenproy.Usuarios where uusuario='"
+ usuario + "';";
ResultSet rs = stmt.executeQuery(sql) ;
while ( rs.next()) {
rowCount++;
}
if (rowCount==0) { //crea el usuario
sql = "INSERT INTO Srenproy.Usuarios VALUES ('" + nombre
+ "','" + usuario + "','" + clave + "','" + perfil + "');";
stmt.executeUpdate(sql);
System.out.println("Usuario creado...");

12
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
return true;
}
else { //no crea usuario
System.out.println("Usuario ya existe...");
return false;
}
}
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
cerrarConexion();
return (false);
}
/* Conexión a la BD */
private void abrirConexion () {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Conectando a servidor...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
System.out.println("Problemas con la conexión a base de datos");
e.printStackTrace();
}
}
/* Desconexión a la BD */
private void cerrarConexion () {
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){
}// nothing we can do

13
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end try
}
}

14
ESTE DOCUMENTO CONTIENE EJEMPLOS DE LA
SEMANA 1

También podría gustarte