commit 1eea24561ed859c1a7430270aa59ba0c51e89e96 Author: Trebellar Date: Tue Apr 7 19:02:38 2026 +0200 Inicio diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..b5237e2 --- /dev/null +++ b/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + modelo + tarea04.1 + 1.0-SNAPSHOT + jar + + UTF-8 + 21 + 21 + + + + + net.sf.xmldb-org + xmldb-api + 1.7.0 + + + + + + org.exist-db + exist-core + 6.2.0 + + + \ No newline at end of file diff --git a/src/main/java/modelo/Departamento.java b/src/main/java/modelo/Departamento.java new file mode 100644 index 0000000..44f7361 --- /dev/null +++ b/src/main/java/modelo/Departamento.java @@ -0,0 +1,60 @@ +package modelo; +// Generated 21:11:36, 10 de xan. de 2023 by Hibernate Tools 5.6.14.Final + +/** + * Dept generated by hbm2java + */ +public class Departamento implements java.io.Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private Integer deptno; + private String dname; + private String loc; + + + public Departamento() { + } + + public Departamento(String dname, String loc) { + this.dname = dname; + this.loc = loc; + + } + + public Integer getDeptno() { + return this.deptno; + } + + public void setDeptno(Integer deptno) { + this.deptno = deptno; + } + + public String getDname() { + return this.dname; + } + + public void setDname(String dname) { + this.dname = dname; + } + + public String getLoc() { + return this.loc; + } + + public void setLoc(String loc) { + this.loc = loc; + } + + + + @Override + public String toString() { + return "Departamento [deptno=" + ( (deptno!=null)? deptno : " ") + ", dname=" + dname + ", loc=" + loc + "]"; + } + + + +} diff --git a/src/main/java/modelo/dao/AbstractGenericDao.java b/src/main/java/modelo/dao/AbstractGenericDao.java new file mode 100644 index 0000000..70345ae --- /dev/null +++ b/src/main/java/modelo/dao/AbstractGenericDao.java @@ -0,0 +1,26 @@ + +package modelo.dao; + +import java.lang.reflect.ParameterizedType; + +/** + * + * @author maria + */ +public abstract class AbstractGenericDao implements IGenericDao{ + + // getClass(): accedemos a la clase de la instancia que extienda esta clase (será DepartamentoSQLServerDao u XSQLServerDao) + //.getGenericSuperclass(): obtenemos el tipo de la clase madre directa: AbstractGenericDao En el caso de que sea una clase parametrizada (con Generics),devuelve el tipo del parámetro de tipo E: ParameterizedType: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getGenericSuperclass-- + //.getActualTypeArguments(): devuelve un array de los tipos de los argumentos que se le pasan al tipo parametrizado (podrían ser más de uno, aunque en este caso el tipo es uno solo ) + //finalmente obtenemos el nombre del tipo parametrizado: que será Departamento (o empleado cuando se implemente) + @SuppressWarnings("unchecked") + final String entityClass = + ((Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]).getName(); + + public String getEntityClass() { + return entityClass; + } + + + +} diff --git a/src/main/java/modelo/dao/IGenericDao.java b/src/main/java/modelo/dao/IGenericDao.java new file mode 100644 index 0000000..e3dc985 --- /dev/null +++ b/src/main/java/modelo/dao/IGenericDao.java @@ -0,0 +1,58 @@ + +package modelo.dao; + +import java.util.List; + +import modelo.exceptions.InstanceNotFoundException; + +/** + * + * @author maria + * @param + */ +public interface IGenericDao { +//Usamos un tipo genérico para indicar que la interfaz IGenericDao tendrá un parámetro de cualquier tipo (clases del modelo), salvo tipos primitivos + //https://docs.oracle.com/javase/tutorial/java/generics/types.html + + +/*** + * Guarda una entidad en el sistema de persistencia + * @param entity + * @return el oid o -1 si hubo algún error + */ + public boolean create(E entity); + + /*** + * Busca en el sistema de persistencia una entidad por su clave primaria + * @param id + * @return la entidad si la encuentra + * @throws InstanceNotFoundException si no encuentra la entidad + */ + public E read(long id) throws InstanceNotFoundException; + + + /*** + * Actualiza los datos de una entidad + * @param entity entidad con los nuevos datos + * @return true si se ha actualizado correctamente, false en caso contrario. + */ + public boolean update(E entity); + + + /*** + * Elimina una entidad del sistema de persistencia + * @param id clave primaria para encontrar la entidad + * @return true si se ha eliminado correctamente, false en caso contrario. + */ + public boolean delete(E entity); + + /** + * Obtienen todos los objetos de una clase almacenados en el sistema de persistencia + * @return la lista de los objetos + */ + public List findAll(); + + + + +} diff --git a/src/main/java/modelo/dao/departamento/DepartamentoEXistDao.java b/src/main/java/modelo/dao/departamento/DepartamentoEXistDao.java new file mode 100644 index 0000000..5f7583d --- /dev/null +++ b/src/main/java/modelo/dao/departamento/DepartamentoEXistDao.java @@ -0,0 +1,256 @@ + +package modelo.dao.departamento; + +import java.io.ByteArrayInputStream; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.exist.xmldb.EXistResource; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xmldb.api.DatabaseManager; +import org.xmldb.api.base.Collection; +import org.xmldb.api.base.CompiledExpression; +import org.xmldb.api.base.Database; +import org.xmldb.api.base.Resource; +import org.xmldb.api.base.ResourceIterator; +import org.xmldb.api.base.ResourceSet; +import org.xmldb.api.base.XMLDBException; +import org.xmldb.api.modules.XQueryService; + +import modelo.Departamento; +import modelo.dao.AbstractGenericDao; +import modelo.exceptions.InstanceNotFoundException; +import util.ConnectionManager; +import util.MyDataSource; + +/** + * 3 + * + * @author mfernandez + */ +public class DepartamentoEXistDao extends AbstractGenericDao implements IDepartamentoDao { + + private static final String DEPT_ROW_TAG = "DEP_ROW"; + private static final String DEPT_NO_TAG = "DEPT_NO"; + private static final String DNOMBRE_TAG = "DNOMBRE"; + private static final String LOC_TAG = "LOC"; + private MyDataSource dataSource; + + public DepartamentoEXistDao() { + this.dataSource = ConnectionManager.getDataSource("src/main/resources/db.properties"); + Class cl; + try { + cl = Class.forName(dataSource.getDriver()); + + Database database = (Database) cl.getDeclaredConstructor().newInstance(); + database.setProperty("create-database", "true"); + + DatabaseManager.registerDatabase(database); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public boolean create(Departamento entity) { + boolean exito = false; + + String deptNodeString = toXMLString(entity); + + if (deptNodeString != "") { + + try (Collection col = DatabaseManager.getCollection(dataSource.getUrl() + dataSource.getColeccion(), + dataSource.getUser(), dataSource.getPwd())) { + + XQueryService xqs = (XQueryService) col.getService("XQueryService", "1.0"); + xqs.setProperty("indent", "yes"); + + CompiledExpression compiled = xqs + .compile("update insert " + deptNodeString + "into doc(\"departamentos.xml\")//departamentos"); + xqs.execute(compiled); + + exito = true; + + } catch (XMLDBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + return exito; + + } + + @Override + public Departamento read(long id) throws InstanceNotFoundException { + Departamento departamento = null; + + try (Collection col = DatabaseManager.getCollection(dataSource.getUrl() + dataSource.getColeccion(), + dataSource.getUser(), dataSource.getPwd())) { + + XQueryService xqs = (XQueryService) col.getService("XQueryService", "1.0"); + xqs.setProperty("indent", "yes"); + + CompiledExpression compiled = xqs.compile("//DEP_ROW[DEPT_NO=" + id + "]"); + ResourceSet result = xqs.execute(compiled); + + if (result.getSize() == 0) + throw new InstanceNotFoundException(id, Departamento.class.getName()); + + ResourceIterator i = result.getIterator(); + Resource res = null; + while (i.hasMoreResources()) { + try { + res = i.nextResource(); + + // System.out.println(res.getContent().toString()); + + departamento = stringNodeToDepartamento(res.getContent().toString()); + + } finally { + // dont forget to cleanup resources + try { + ((EXistResource) res).freeResources(); + } catch (XMLDBException xe) { + departamento = null; + xe.printStackTrace(); + } + } + } + + } catch (XMLDBException e) { + departamento = null; + // TODO Auto-generated catch block + e.printStackTrace(); + } + return departamento; + } + + /** + * Toma un objeto Departamento y devuelve un nodo XML como el del documento + * departamentos.xml de src/main/resources + * 10 + * CONTABILIDAD + * SEVILLA + * en formato String + * + * @param dept + * @return + */ + private String toXMLString(Departamento dept) { + String output = ""; + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + + DOMImplementation implementation = builder.getDOMImplementation(); + + // Crea un document con un elmento raiz + Document document = implementation.createDocument(null, DEPT_ROW_TAG, null); + // Obtenemos el elemento raíz + Element root = document.getDocumentElement(); + Element deptNo = createElement(document, DEPT_NO_TAG, String.valueOf(dept.getDeptno())); + + Element name = createElement(document, DNOMBRE_TAG, dept.getDname().trim()); + Element loc = createElement(document, LOC_TAG, dept.getLoc().trim()); + + root.appendChild(deptNo); + root.appendChild(name); + root.appendChild(loc); + + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + + // https://docs.oracle.com/javase/8/docs/api/java/io/StringWriter.html + StringWriter writer = new StringWriter(); + transformer.transform(new DOMSource(document), new StreamResult(writer)); + output = writer.getBuffer().toString().replaceAll("\n|\r", ""); + + // System.out.println(output); + + } catch (ParserConfigurationException e) { + output = ""; + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (TransformerException e) { + output = ""; + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return output; + } + + private Element createElement(Document document, String tag, String content) { + Element elemento = document.createElement(tag); + elemento.setTextContent(content); + return elemento; + } + + private Departamento stringNodeToDepartamento(String nodeString) { + Element node = null; + Departamento departamento = null; + try { + node = DocumentBuilderFactory.newInstance().newDocumentBuilder() + .parse(new ByteArrayInputStream(nodeString.getBytes())).getDocumentElement(); + + String nombre = getElementText(node, DNOMBRE_TAG); + String location = getElementText(node, LOC_TAG); + Integer id = Integer.parseInt(getElementText(node, DEPT_NO_TAG)); + + departamento = new Departamento(nombre, location); + departamento.setDeptno(id); + + } catch (Exception ex) { + ex.printStackTrace(); + } + return departamento; + } + + private String getElementText(Element parent, String tag) { + String texto = ""; + NodeList lista = parent.getElementsByTagName(tag); + + if (lista.getLength() > 0) { + texto = lista.item(0).getTextContent(); + } + + return texto; + } + + @Override + public boolean update(Departamento entity) { + throw new UnsupportedOperationException("Este método update debe ser implementado"); + + } + + @Override + public boolean delete(Departamento entity) { + throw new UnsupportedOperationException("Este método delete debe ser implementado"); + + } + + @Override + public List findAll() { + throw new UnsupportedOperationException("Este método findAll debe ser implementado"); + + } + +} diff --git a/src/main/java/modelo/dao/departamento/IDepartamentoDao.java b/src/main/java/modelo/dao/departamento/IDepartamentoDao.java new file mode 100644 index 0000000..c5a3125 --- /dev/null +++ b/src/main/java/modelo/dao/departamento/IDepartamentoDao.java @@ -0,0 +1,23 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template + */ +package modelo.dao.departamento; + + +import modelo.Departamento; +import modelo.dao.IGenericDao; + +/** + * + * @author mfernandez + */ +public interface IDepartamentoDao extends IGenericDao{ + + + + + + + +} diff --git a/src/main/java/modelo/exceptions/DuplicateInstanceException.java b/src/main/java/modelo/exceptions/DuplicateInstanceException.java new file mode 100644 index 0000000..48ee101 --- /dev/null +++ b/src/main/java/modelo/exceptions/DuplicateInstanceException.java @@ -0,0 +1,29 @@ +package modelo.exceptions; + + + +@SuppressWarnings("serial") +public class DuplicateInstanceException extends Exception { + private Object key; + private String className; + + public DuplicateInstanceException(String specificMessage, Object key, + String className) { + + super(specificMessage + " (key = '" + key + "' - className = '" + + className + "')"); + this.key = key; + this.className = className; + + } + + public Object getKey() { + return key; + } + + public String getClassName() { + return className; + } + + +} \ No newline at end of file diff --git a/src/main/java/modelo/exceptions/InstanceNotFoundException.java b/src/main/java/modelo/exceptions/InstanceNotFoundException.java new file mode 100644 index 0000000..bca14b5 --- /dev/null +++ b/src/main/java/modelo/exceptions/InstanceNotFoundException.java @@ -0,0 +1,40 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package modelo.exceptions; + +/** + * + * @author maria + */ +public class InstanceNotFoundException extends Exception { + + + /** + * + */ + private static final long serialVersionUID = 1L; + private Object key; + private String className; + + private static final String DEFAULT_MSG = "Instance not found"; + + public InstanceNotFoundException( Object key, + String className) { + + super(DEFAULT_MSG + " (key = '" + key + "' - className = '" + + className + "')"); + this.key = key; + this.className = className; + + } + + public Object getKey() { + return key; + } + + public String getClassName() { + return className; + } +} diff --git a/src/main/java/modelo/main/CreateNewDeptDialog.java b/src/main/java/modelo/main/CreateNewDeptDialog.java new file mode 100644 index 0000000..5f51efd --- /dev/null +++ b/src/main/java/modelo/main/CreateNewDeptDialog.java @@ -0,0 +1,180 @@ +package modelo.main; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.EmptyBorder; + +import modelo.Departamento; +import java.awt.Color; + +public class CreateNewDeptDialog extends JDialog { + + /** + * + */ + private static final long serialVersionUID = 1L; + private final JPanel contentPanel = new JPanel(); + private JTextField textFieldUbicacion; + private JTextField textFieldNombreDept; + private JButton okButton; + private JLabel lblError; + private Departamento departamentoACrearOActualizar = null; + + private JLabel lblId; + + public Departamento getResult() { + return this.departamentoACrearOActualizar; + } + + public enum TIPO_EDICION { + EDITAR, CREAR + }; + + private TIPO_EDICION tipo = TIPO_EDICION.CREAR; + private JTextField textFieldDeptno; + + /** + * Create the dialog. + */ + public void initComponents() { + + setBounds(100, 100, 598, 300); + getContentPane().setLayout(new BorderLayout()); + contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + getContentPane().add(contentPanel, BorderLayout.CENTER); + contentPanel.setLayout(null); + + JLabel lblDeptName = new JLabel("Nombre departamento"); + lblDeptName.setFont(new Font("Tahoma", Font.PLAIN, 14)); + lblDeptName.setBounds(39, 34, 208, 24); + contentPanel.add(lblDeptName); + + textFieldUbicacion = new JTextField(); + textFieldUbicacion.setFont(new Font("Tahoma", Font.PLAIN, 14)); + textFieldUbicacion.setBounds(330, 83, 197, 23); + contentPanel.add(textFieldUbicacion); + textFieldUbicacion.setColumns(10); + + JLabel lblDeptLocation = new JLabel("Ubicación"); + lblDeptLocation.setFont(new Font("Tahoma", Font.PLAIN, 14)); + lblDeptLocation.setBounds(39, 82, 140, 24); + contentPanel.add(lblDeptLocation); + + textFieldNombreDept = new JTextField(); + textFieldNombreDept.setFont(new Font("Tahoma", Font.PLAIN, 14)); + textFieldNombreDept.setColumns(10); + textFieldNombreDept.setBounds(330, 35, 197, 23); + contentPanel.add(textFieldNombreDept); + + lblId= new JLabel("Dept. no"); + lblId.setFont(new Font("Tahoma", Font.PLAIN, 14)); + lblId.setBounds(39, 135, 140, 24); + contentPanel.add(lblId); + + textFieldDeptno = new JTextField(); + textFieldDeptno.setFont(new Font("Tahoma", Font.PLAIN, 14)); + textFieldDeptno.setColumns(10); + textFieldDeptno.setBounds(330, 136, 197, 23); + contentPanel.add(textFieldDeptno); + + lblError = new JLabel("Error label"); + lblError.setForeground(new Color(255, 0, 0)); + lblError.setFont(new Font("Tahoma", Font.PLAIN, 14)); + lblError.setBounds(52, 187, 294, 24); + lblError.setVisible(false); + contentPanel.add(lblError); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); + getContentPane().add(buttonPane, BorderLayout.SOUTH); + + okButton = new JButton("Guardar"); + + okButton.setActionCommand("OK"); + buttonPane.add(okButton); + getRootPane().setDefaultButton(okButton); + + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + departamentoACrearOActualizar = null; + CreateNewDeptDialog.this.dispose(); + + } + }); + cancelButton.setActionCommand("Cancel"); + buttonPane.add(cancelButton); + + ActionListener crearBtnActionListener = new ActionListener() { + + public void actionPerformed(ActionEvent e) { + if (!(textFieldUbicacion.getText().trim().equals("")) + && !(textFieldNombreDept.getText().trim().equals(""))) { + if (departamentoACrearOActualizar == null) { + // Solo para creación + departamentoACrearOActualizar = new Departamento(); + } + departamentoACrearOActualizar.setDname(textFieldNombreDept.getText().trim()); + departamentoACrearOActualizar.setLoc(textFieldUbicacion.getText().trim()); + int deptno = getDeptnoFromTextField(); + if (deptno != -1) { + departamentoACrearOActualizar.setDeptno(deptno); + CreateNewDeptDialog.this.dispose(); + } else { + lblError.setText("Introduzca un entero en número de departamento"); + lblError.setVisible(true); + } + + } + } + }; + + this.okButton.addActionListener(crearBtnActionListener); + + } + + public CreateNewDeptDialog(Window owner, String title, ModalityType modalityType, Departamento dept, + TIPO_EDICION tipo) { + super(owner, title, modalityType); + initComponents(); + departamentoACrearOActualizar = dept; + this.tipo = tipo; + if (departamentoACrearOActualizar != null) { + textFieldNombreDept.setText(departamentoACrearOActualizar.getDname()); + textFieldUbicacion.setText(departamentoACrearOActualizar.getLoc()); + textFieldDeptno.setText(String.valueOf(departamentoACrearOActualizar.getDeptno())); + + // No permitir cambio de deptno en edición + textFieldDeptno.setVisible(tipo != TIPO_EDICION.EDITAR); + lblId.setVisible(tipo !=TIPO_EDICION.EDITAR); + + } + lblError.setVisible(false); + this.setLocationRelativeTo(owner); + } + + public TIPO_EDICION getTipo() { + return tipo; + } + + private int getDeptnoFromTextField() { + int deptno = -1; + String textIntroducido = textFieldDeptno.getText().trim(); + try { + deptno = Integer.parseInt(textIntroducido); + } catch (Exception nfe) { + deptno = -1; + } + return deptno; + } +} diff --git a/src/main/java/modelo/main/DeptWindow.java b/src/main/java/modelo/main/DeptWindow.java new file mode 100644 index 0000000..f508ed0 --- /dev/null +++ b/src/main/java/modelo/main/DeptWindow.java @@ -0,0 +1,278 @@ +package modelo.main; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dialog; +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; + +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.border.EmptyBorder; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import modelo.Departamento; +import modelo.exceptions.DuplicateInstanceException; +import modelo.main.CreateNewDeptDialog.TIPO_EDICION; +import modelo.servicio.departamento.IServicioDepartamento; +import modelo.servicio.departamento.ServicioDepartamento; + +public class DeptWindow extends JFrame { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private JPanel contentPane; + + private JTextArea mensajes_text_Area; + private JList JListAllDepts; + + private IServicioDepartamento departamentoServicio; + private CreateNewDeptDialog createDialog; + private JButton btnModificarDepartamento; + private JButton btnEliminarDepartamento; + + /** + * Launch the application. + */ + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + DeptWindow frame = new DeptWindow(); + frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + /** + * Create the frame. + */ + public DeptWindow() { + + departamentoServicio = new ServicioDepartamento(); + + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setBounds(100, 100, 847, 772); + contentPane = new JPanel(); + contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + + setContentPane(contentPane); + contentPane.setLayout(null); + + JPanel panel = new JPanel(); + panel.setBounds(8, 8, 821, 500); + contentPane.add(panel); + panel.setLayout(null); + + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setBounds(19, 264, 669, 228); + panel.add(scrollPane); + + mensajes_text_Area = new JTextArea(); + scrollPane.setViewportView(mensajes_text_Area); + mensajes_text_Area.setEditable(false); + mensajes_text_Area.setText("Panel de mensajes"); + mensajes_text_Area.setForeground(new Color(255, 0, 0)); + mensajes_text_Area.setFont(new Font("Monospaced", Font.PLAIN, 13)); + + JButton btnShowAllDepts = new JButton("Mostrar departamentos"); + + btnShowAllDepts.setFont(new Font("Tahoma", Font.PLAIN, 14)); + btnShowAllDepts.setBounds(50, 37, 208, 36); + panel.add(btnShowAllDepts); + + btnModificarDepartamento = new JButton("Modificar departamento"); + + JListAllDepts = new JList(); + + JListAllDepts.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + JListAllDepts.setBounds(403, 37, 377, 200); + + JScrollPane scrollPanel_in_JlistAllDepts = new JScrollPane(JListAllDepts); + scrollPanel_in_JlistAllDepts.setLocation(300, 0); + scrollPanel_in_JlistAllDepts.setSize(500, 250); + + panel.add(scrollPanel_in_JlistAllDepts); + + JButton btnCrearNuevoDepartamento = new JButton("Crear nuevo departamento"); + + btnCrearNuevoDepartamento.setFont(new Font("Tahoma", Font.PLAIN, 14)); + btnCrearNuevoDepartamento.setBounds(50, 85, 208, 36); + panel.add(btnCrearNuevoDepartamento); + + btnModificarDepartamento.setEnabled(false); + btnModificarDepartamento.setFont(new Font("Tahoma", Font.PLAIN, 14)); + btnModificarDepartamento.setBounds(50, 139, 208, 36); + panel.add(btnModificarDepartamento); + + btnEliminarDepartamento = new JButton("Eliminar departamento"); + + btnEliminarDepartamento.setFont(new Font("Tahoma", Font.PLAIN, 14)); + btnEliminarDepartamento.setEnabled(false); + btnEliminarDepartamento.setBounds(50, 201, 208, 36); + panel.add(btnEliminarDepartamento); + + // Eventos + ActionListener showAllDepartamentosActionListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + getAllDepartamentos(); + } + }; + btnShowAllDepts.addActionListener(showAllDepartamentosActionListener); + + ActionListener crearListener = new ActionListener() { + + public void actionPerformed(ActionEvent e) { + + JFrame owner = (JFrame) SwingUtilities.getRoot((Component) e.getSource()); + createDialog = new CreateNewDeptDialog(owner, "Crear nuevo departamento", + Dialog.ModalityType.DOCUMENT_MODAL, null, TIPO_EDICION.CREAR); + showDialog(); + } + }; + btnCrearNuevoDepartamento.addActionListener(crearListener); + + ActionListener modificarListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + int selectedIx = JListAllDepts.getSelectedIndex(); + if (selectedIx > -1) { + Departamento departamento = (Departamento) JListAllDepts.getModel().getElementAt(selectedIx); + if (departamento != null) { + + JFrame owner = (JFrame) SwingUtilities.getRoot((Component) e.getSource()); + + createDialog = new CreateNewDeptDialog(owner, "Modificar departamento", + Dialog.ModalityType.DOCUMENT_MODAL, departamento, TIPO_EDICION.EDITAR); + showDialog(); + } + } + } + }; + + btnModificarDepartamento.addActionListener(modificarListener); + + ListSelectionListener selectionListListener = new ListSelectionListener() { + public void valueChanged(ListSelectionEvent e) { + if (e.getValueIsAdjusting() == false) { + int selectedIx = JListAllDepts.getSelectedIndex(); + btnModificarDepartamento.setEnabled((selectedIx > -1)); + btnEliminarDepartamento.setEnabled((selectedIx > -1)); + if (selectedIx > -1) { + Departamento d = (Departamento) DeptWindow.this.JListAllDepts.getModel() + .getElementAt(selectedIx); + if (d != null) { + addMensaje(true, "Se ha seleccionado el d: " + d); + } + } + } + } + }; + JListAllDepts.addListSelectionListener(selectionListListener); + + ActionListener deleteListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + int selectedIx = JListAllDepts.getSelectedIndex(); + if (selectedIx > -1) { + Departamento d = (Departamento) JListAllDepts.getModel().getElementAt(selectedIx); + if (d != null) { + try { + boolean exito = departamentoServicio.delete(d); + if (exito) { + addMensaje(true, "Se ha eliminado el dept con id: " + d.getDeptno()); + getAllDepartamentos(); + } + + } catch (Exception ex) { + addMensaje(true, "No se ha podido borrar el departamento. "); + System.out.println("Exception: " + ex.getMessage()); + ex.printStackTrace(); + } + } + } + } + }; + btnEliminarDepartamento.addActionListener(deleteListener); + } + + private void addMensaje(boolean keepText, String msg) { + String oldText = ""; + if (keepText) { + oldText = mensajes_text_Area.getText(); + + } + oldText = oldText + "\n" + msg; + mensajes_text_Area.setText(oldText); + + } + + private void showDialog() { + createDialog.setVisible(true); + Departamento departamentoACrear = createDialog.getResult(); + if (departamentoACrear != null) { + + if (createDialog.getTipo() == TIPO_EDICION.CREAR) { + try { + boolean exito = departamentoServicio.create(departamentoACrear); + if (!exito) { + addMensaje(true, "No se ha creado correctamete el departamento"); + } else { + addMensaje(true, " El departamento se ha creado correctamente"); + } + } catch (DuplicateInstanceException die) { + addMensaje(true, "Ya existe un departamento con ese id. No se ha podido crear."); + + } catch (Exception ex) { + addMensaje(true, "Ha ocurrido un error y no se ha podido crear el departamento"); + } + } else if (createDialog.getTipo() == TIPO_EDICION.EDITAR) { + try { + boolean exito = departamentoServicio.update(departamentoACrear); + if (!exito) { + addMensaje(true, "No se ha editado correctamete el departamento"); + } else { + addMensaje(true, " El departamento se ha actualizado correctamente"); + } + + } catch (Exception ex) { + addMensaje(true, "Ha ocurrido un error y no se ha podido crear/actualizar el departamento"); + } + } + + getAllDepartamentos(); + + } + } + + private void getAllDepartamentos() { + List departamentos = departamentoServicio.findAll(); + addMensaje(true, "Se han recuperado: " + departamentos.size() + " departamentos"); + DefaultListModel defModel = new DefaultListModel<>(); + for (Departamento departamento : departamentos) { + defModel.addElement(departamento); + } + + // defModel.addAll(departamentos); + + JListAllDepts.setModel(defModel); + + } + +} diff --git a/src/main/java/modelo/servicio/departamento/IServicioDepartamento.java b/src/main/java/modelo/servicio/departamento/IServicioDepartamento.java new file mode 100644 index 0000000..1c072ac --- /dev/null +++ b/src/main/java/modelo/servicio/departamento/IServicioDepartamento.java @@ -0,0 +1,23 @@ +package modelo.servicio.departamento; + + +import java.util.List; + +import modelo.Departamento; +import modelo.exceptions.DuplicateInstanceException; +import modelo.exceptions.InstanceNotFoundException; + +public interface IServicioDepartamento { + + public boolean create(Departamento dept)throws DuplicateInstanceException; + + public boolean delete(Departamento dept); + public boolean update(Departamento dept); + + public List findAll(); + + public Departamento read(long deptno) throws InstanceNotFoundException; + +} + + diff --git a/src/main/java/modelo/servicio/departamento/ServicioDepartamento.java b/src/main/java/modelo/servicio/departamento/ServicioDepartamento.java new file mode 100644 index 0000000..780b77e --- /dev/null +++ b/src/main/java/modelo/servicio/departamento/ServicioDepartamento.java @@ -0,0 +1,47 @@ +package modelo.servicio.departamento; + +import java.util.List; + +import modelo.Departamento; +import modelo.dao.departamento.DepartamentoEXistDao; +import modelo.dao.departamento.IDepartamentoDao; +import modelo.exceptions.DuplicateInstanceException; +import modelo.exceptions.InstanceNotFoundException; + +public class ServicioDepartamento implements IServicioDepartamento { + + private IDepartamentoDao departamentoDao; + + public ServicioDepartamento() { + departamentoDao = new DepartamentoEXistDao(); + } + + @Override + public boolean create(Departamento dept) throws DuplicateInstanceException { + + return departamentoDao.create(dept); + + + } + + @Override + public boolean delete(Departamento dept) { + return departamentoDao.delete(dept); + } + + @Override + public boolean update(Departamento dept) { + return departamentoDao.update(dept); + } + + @Override + public List findAll() { + return departamentoDao.findAll(); + } + + @Override + public Departamento read(long deptno) throws InstanceNotFoundException { + return departamentoDao.read(deptno); + } + +} diff --git a/src/main/java/util/ConnectionManager.java b/src/main/java/util/ConnectionManager.java new file mode 100644 index 0000000..a6ebfbe --- /dev/null +++ b/src/main/java/util/ConnectionManager.java @@ -0,0 +1,62 @@ +package util; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Properties; + +import org.xmldb.api.base.Database; + +public class ConnectionManager { + + private static final String URL_KEY = "url"; + private static final String USER_KEY = "user"; + private static final String PWD_KEY = "pwd"; + private static final String DRIVER_KEY = "driver"; + private static final String COL_DEPTS_KEY = "coleccionDepartamentos"; + + private static MyDataSource datasource = null; + + + private ConnectionManager() { + + } + + public static MyDataSource getDataSource(String ruta) { + if (datasource == null) { + Properties properties = new Properties(); + try (FileInputStream fis = new FileInputStream(ruta)) { + properties.load(fis); + String url = properties.getProperty(URL_KEY); + String user = properties.getProperty(USER_KEY); + String pwd = properties.getProperty(PWD_KEY); + String driver = properties.getProperty(DRIVER_KEY); + String col_depts = properties.getProperty(COL_DEPTS_KEY); + + datasource = new MyDataSource(user, pwd, url, driver); + + datasource.setColeccion(col_depts); + + + + + } catch (FileNotFoundException e) { + System.err.println("Ha ocurrido una excepción FileNotFound: " + e.getMessage()); + } catch (IOException e) { + System.err.println("Ha ocurrido una excepción IOE: " + e.getMessage()); + } catch (Exception e) { + System.err.println("Ha ocurrido una excepción: " + e.getMessage()); + + } + + } + + return datasource; + + } + + + + + +} diff --git a/src/main/java/util/MyDataSource.java b/src/main/java/util/MyDataSource.java new file mode 100644 index 0000000..752dfa8 --- /dev/null +++ b/src/main/java/util/MyDataSource.java @@ -0,0 +1,71 @@ +package util; + +public class MyDataSource { + private String user = null; + private String pwd = null; + private String url = null; + private String driver = null; + private String coleccion = null; + + + + public MyDataSource(String user, String pwd, String url, String driver) { + super(); + this.user = user; + this.pwd = pwd; + this.url = url; + this.driver = driver; + } + + + public String getUser() { + return user; + } + + + public void setUser(String user) { + this.user = user; + } + + + public String getPwd() { + return pwd; + } + + + public void setPwd(String pwd) { + this.pwd = pwd; + } + + + public String getUrl() { + return url; + } + + + public void setUrl(String url) { + this.url = url; + } + + + public String getDriver() { + return driver; + } + + + public void setDriver(String driver) { + this.driver = driver; + } + + + public String getColeccion() { + return coleccion; + } + + + public void setColeccion(String col_depts) { + this.coleccion = col_depts; + } + + +} diff --git a/src/main/resources/db.properties b/src/main/resources/db.properties new file mode 100644 index 0000000..493d5cb --- /dev/null +++ b/src/main/resources/db.properties @@ -0,0 +1,6 @@ +url=xmldb:exist://localhost:8080/exist/xmlrpc/db/apps/ +#importante la barra final de url +user= +pwd= +driver=org.exist.xmldb.DatabaseImpl +coleccionDepartamentos= \ No newline at end of file diff --git a/src/main/resources/departamentos.xml b/src/main/resources/departamentos.xml new file mode 100644 index 0000000..ad8c275 --- /dev/null +++ b/src/main/resources/departamentos.xml @@ -0,0 +1,24 @@ + + +DATOS DE LA TABLA DEPART + + 10 + CONTABILIDAD + SEVILLA + + + 20 + INVESTIGACION + MADRID + + + 30 + VENTAS + BARCELONA + + + 40 + PRODUCCION + BILBAO + + \ No newline at end of file