From 1389fb8bba9fb250cc73c809199a8275bcbd61ba Mon Sep 17 00:00:00 2001 From: Amit Kumar Nandi <11887616+aamitn@users.noreply.github.com> Date: Sat, 17 Feb 2024 22:38:33 +0530 Subject: [PATCH] Initial commit --- .gitignore | 38 ++++++ Readme.md | 113 +++++++++++++++++ pom.xml | 45 +++++++ src/main/java/org/nmpl/App.java | 24 ++++ src/main/java/org/nmpl/DbExporter.java | 116 ++++++++++++++++++ .../java/org/nmpl/DbExporterException.java | 13 ++ src/main/java/org/nmpl/Exportable.java | 5 + src/main/java/org/nmpl/ExporterFactory.java | 62 ++++++++++ .../java/org/nmpl/exporters/HTMLExporter.java | 58 +++++++++ .../java/org/nmpl/exporters/TestExporter.java | 21 ++++ .../java/org/nmpl/exporters/XMLExporter.java | 72 +++++++++++ src/main/java/org/nmpl/v1/App.java | 19 +++ src/main/java/org/nmpl/v1/Configurable.java | 5 + src/main/java/org/nmpl/v1/DbExporter.java | 114 +++++++++++++++++ src/main/java/org/nmpl/v1/Exportable.java | 6 + .../java/org/nmpl/v1/ExporterFactory.java | 52 ++++++++ .../org/nmpl/v1/exporters/HTMLExporter.java | 65 ++++++++++ .../org/nmpl/v1/exporters/TestExporter.java | 32 +++++ .../org/nmpl/v1/exporters/XMLExporter.java | 78 ++++++++++++ src/main/java/org/nmpl/v2/App.java | 19 +++ src/main/java/org/nmpl/v2/DbExporter.java | 114 +++++++++++++++++ src/main/java/org/nmpl/v2/ExportType.java | 12 ++ src/main/java/org/nmpl/v2/Exportable.java | 5 + .../java/org/nmpl/v2/ExporterFactory.java | 52 ++++++++ .../org/nmpl/v2/exporters/HTMLExporter.java | 60 +++++++++ .../org/nmpl/v2/exporters/TestExporter.java | 26 ++++ .../org/nmpl/v2/exporters/XMLExporter.java | 74 +++++++++++ src/main/resources/config.xml | 16 +++ src/test/java/org/nmpl/AppTest.java | 38 ++++++ 29 files changed, 1354 insertions(+) create mode 100644 .gitignore create mode 100644 Readme.md create mode 100644 pom.xml create mode 100644 src/main/java/org/nmpl/App.java create mode 100644 src/main/java/org/nmpl/DbExporter.java create mode 100644 src/main/java/org/nmpl/DbExporterException.java create mode 100644 src/main/java/org/nmpl/Exportable.java create mode 100644 src/main/java/org/nmpl/ExporterFactory.java create mode 100644 src/main/java/org/nmpl/exporters/HTMLExporter.java create mode 100644 src/main/java/org/nmpl/exporters/TestExporter.java create mode 100644 src/main/java/org/nmpl/exporters/XMLExporter.java create mode 100644 src/main/java/org/nmpl/v1/App.java create mode 100644 src/main/java/org/nmpl/v1/Configurable.java create mode 100644 src/main/java/org/nmpl/v1/DbExporter.java create mode 100644 src/main/java/org/nmpl/v1/Exportable.java create mode 100644 src/main/java/org/nmpl/v1/ExporterFactory.java create mode 100644 src/main/java/org/nmpl/v1/exporters/HTMLExporter.java create mode 100644 src/main/java/org/nmpl/v1/exporters/TestExporter.java create mode 100644 src/main/java/org/nmpl/v1/exporters/XMLExporter.java create mode 100644 src/main/java/org/nmpl/v2/App.java create mode 100644 src/main/java/org/nmpl/v2/DbExporter.java create mode 100644 src/main/java/org/nmpl/v2/ExportType.java create mode 100644 src/main/java/org/nmpl/v2/Exportable.java create mode 100644 src/main/java/org/nmpl/v2/ExporterFactory.java create mode 100644 src/main/java/org/nmpl/v2/exporters/HTMLExporter.java create mode 100644 src/main/java/org/nmpl/v2/exporters/TestExporter.java create mode 100644 src/main/java/org/nmpl/v2/exporters/XMLExporter.java create mode 100644 src/main/resources/config.xml create mode 100644 src/test/java/org/nmpl/AppTest.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5ff6309 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..fdee171 --- /dev/null +++ b/Readme.md @@ -0,0 +1,113 @@ +## Database Exporter Application + +This is a Java application for exporting data from a MySQL database to various formats (e.g., HTML, XML, etc.). The application uses Swing for the graphical user interface and supports a plug-and-play architecture for adding new export formats without changing existing code. + +## Table of Contents + +* [Features](#features) +* [Prerequisites](#prerequisites) +* [Getting Started](#getting-started) +* [Usage](#usage) +* [Plugin Architecture](#plugin-architecture) +* [Configurationless Operation](#configurationless-operation) +* [Contributing](#contributing) +* [License](#license) + +## Features + +* Export data from MySQL database tables. +* Supports multiple export formats (e.g., HTML, XML, etc.). +* Extensible architecture for adding new export formats without modifying existing code. +* Graphical user interface using Swing. +* Virtually configurationless operation. + +## Prerequisites + +* Java 11 or higher +* MySQL database + +## Getting Started + +1. Clone the repository: + + git clone https://github.com/aamitn/db-exporter.git + +2.  Compile the code: + + cd db-exporter + + javac -cp .:path/to/mysql-connector-java.jar org/nmpl/\*.java org/nmpl/exporters/\*.java org/nmpl/exceptions/\*.java + +3. Run the application: + + java -cp .:path/to/mysql-connector-java.jar org.nmpl.App + + +## Usage + +Launch the application using the steps mentioned in the Getting Started section. +Connect to your MySQL database by entering the database name, username, and password. +Click "Show Tables" to display the available tables. +Select a table from the list. +Choose an export format from the dropdown menu. +Click "Export Table" to export the selected table to the chosen format. + +Example Factory Class Usage: + +```plaintext +ExporterFactory exportFactory = new ExporterFactory(connection); +Exportable exporter = exportFactory.getExporter("xml"); +exporter.export("your_table_name", "output.xml"); +``` + +## Plugin Architecture + +The application employs a plugin architecture, allowing you to add new export formats without modifying existing code. To add a new export format, simply create a new class implementing the Exportable interface and place it in the org.nmpl.exporters package. + +Example for creating a new export format: + +```plaintext +package org.nmpl.exporters; +import org.nmpl.Exportable; +public class NewFormatExporter implements Exportable { +// Implement the export method as per your requirements +} +``` + + +No changes to the existing code are needed. The new class is automatically recognized and integrated into the application at runtime. + +## Configurationless Operation + +The application is designed for configurationless operation. The config.xml file, located in the resources directory, maps export formats to their corresponding Java class names. This enables the application to dynamically recognize and utilize new exporters without explicit configuration. + +Example config.xml: + +```plaintext + + + html + org.nmpl.exporters.HTMLExporter + + + xml + org.nmpl.exporters.XMLExporter + + + newformat + org.nmpl.exporters.NewFormatExporter + + + +``` + +## Fork the repository + +Create a new branch (git checkout -b feature/new-feature) +Make your changes and commit them (git commit -am 'Add new feature') +Push to the branch (git push origin feature/new-feature) +Open a pull request + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..21936e3 --- /dev/null +++ b/pom.xml @@ -0,0 +1,45 @@ + + 4.0.0 + + org.nmpl + DbExporter + 1.0-SNAPSHOT + jar + + DbExporter + http://maven.apache.org + + + UTF-8 + 21 + 21 + + + + + + mysql + mysql-connector-java + 8.0.27 + + + + org.apache.commons + commons-lang3 + 3.12.0 + + + + junit + junit + 3.8.1 + test + + + org.reflections + reflections + 0.10.2 + + + diff --git a/src/main/java/org/nmpl/App.java b/src/main/java/org/nmpl/App.java new file mode 100644 index 0000000..2aad5f4 --- /dev/null +++ b/src/main/java/org/nmpl/App.java @@ -0,0 +1,24 @@ +package org.nmpl; + +import javax.swing.*; +import java.sql.SQLException; + +public class App { + public static void main(String[] args) { + final String dbName = "shortener"; + final String username = "root"; + final String pasword = "1234qwer"; + + SwingUtilities.invokeLater(() -> { + + DbExporter manager; + try { + manager = new DbExporter(dbName,username,pasword); + } + catch (SQLException e) { + throw new RuntimeException(e); + } + manager.setVisible(true); + }); + } +} diff --git a/src/main/java/org/nmpl/DbExporter.java b/src/main/java/org/nmpl/DbExporter.java new file mode 100644 index 0000000..7b934f5 --- /dev/null +++ b/src/main/java/org/nmpl/DbExporter.java @@ -0,0 +1,116 @@ +package org.nmpl; + +import javax.swing.*; +import java.awt.*; +import java.io.File; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class DbExporter extends JFrame { + private final JComboBox exportFormatComboBox; + private final JList tableList; + private final DefaultListModel tableListModel; + private final Connection connection; + + public DbExporter(String dbName,String username,String pasword) throws SQLException { + connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbName, username, pasword); + setTitle("Database Manager"); + setSize(400, 400); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // Create components + tableListModel = new DefaultListModel<>(); + tableList = new JList<>(tableListModel); + JButton showButton = new JButton("Show Tables"); + + ExporterFactory ef; + try { + ef = new ExporterFactory(connection); + } catch (Exception e) { + throw new RuntimeException(e); + } + + List formatList = new ArrayList<>(ef.getSupportedFormats()); + + exportFormatComboBox = new JComboBox<>(formatList.toArray(new String[0])); + JButton exportButton = new JButton("Export Table"); + + // Create panels for layout + JPanel topPanel = new JPanel(); + JPanel mainPanel = new JPanel(new BorderLayout()); + + // Set a vertical BoxLayout for the top panel + topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS)); + + // Add components to the top panel + topPanel.add(showButton); + topPanel.add(exportFormatComboBox); + topPanel.add(exportButton); + + mainPanel.add(new JScrollPane(tableList), BorderLayout.CENTER); + mainPanel.add(topPanel, BorderLayout.NORTH); + + // Add mainPanel to the frame + add(mainPanel); + + // Event handlers + showButton.addActionListener(e -> showTables()); + exportButton.addActionListener(e -> exportTable()); + } + + private void showTables() { + try { + DatabaseMetaData metaData = connection.getMetaData(); + String catalog = connection.getCatalog(); + ResultSet tables = metaData.getTables(catalog, null, null, new String[]{"TABLE"}); + + tableListModel.clear(); + + while (tables.next()) { + String tableName = tables.getString("TABLE_NAME"); + tableListModel.addElement(tableName); + } + + tables.close(); + } catch (SQLException e) { + String error = "Failed to connect to the database or fetch tables."; + JOptionPane.showMessageDialog(this, error); + throw new DbExporterException(error, e); + } + } + + private void exportTable() { + String selectedTable = tableList.getSelectedValue(); + if (selectedTable == null) { + JOptionPane.showMessageDialog(this, "Please select a table to export."); + return; + } + + String exportFormat = Objects.requireNonNull(exportFormatComboBox.getSelectedItem()).toString(); + String fileName = selectedTable + "." + exportFormat.toLowerCase(); + + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Save " + exportFormat + " File"); + fileChooser.setSelectedFile(new File(fileName)); + + int userSelection = fileChooser.showSaveDialog(this); + + if (userSelection == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + fileName = selectedFile.getAbsolutePath(); + + try { + ExporterFactory exportFactory = new ExporterFactory(connection); + Exportable exporter = exportFactory.getExporter(exportFormat); + exporter.export(selectedTable, fileName); + JOptionPane.showMessageDialog(this, "Table data exported to " + fileName); + } catch (Exception e) { + String error = "Failed to export table."; + JOptionPane.showMessageDialog(this, error); + throw new DbExporterException(error, e); + } + } + } +} diff --git a/src/main/java/org/nmpl/DbExporterException.java b/src/main/java/org/nmpl/DbExporterException.java new file mode 100644 index 0000000..211c12b --- /dev/null +++ b/src/main/java/org/nmpl/DbExporterException.java @@ -0,0 +1,13 @@ +package org.nmpl; + +public class DbExporterException extends RuntimeException { + + public DbExporterException(String message, Throwable cause) { + super(message, cause); + } + + @Override + public void printStackTrace() { + System.err.println("Application Error : DbExporterException: " + getMessage()); + } +} \ No newline at end of file diff --git a/src/main/java/org/nmpl/Exportable.java b/src/main/java/org/nmpl/Exportable.java new file mode 100644 index 0000000..9954e07 --- /dev/null +++ b/src/main/java/org/nmpl/Exportable.java @@ -0,0 +1,5 @@ +package org.nmpl; +public interface Exportable { + void export(String tableName, String fileName) throws Exception; +} + diff --git a/src/main/java/org/nmpl/ExporterFactory.java b/src/main/java/org/nmpl/ExporterFactory.java new file mode 100644 index 0000000..bc76f65 --- /dev/null +++ b/src/main/java/org/nmpl/ExporterFactory.java @@ -0,0 +1,62 @@ +package org.nmpl; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ExporterFactory { + private final Map exporterClassNames; + private final Connection connection; + + public ExporterFactory(Connection connection) { + this.connection = connection; + exporterClassNames = new HashMap<>(); + loadExporterConfig(); + } + + private void loadExporterConfig() { + try { + // Parse the XML configuration file + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(getClass().getClassLoader().getResourceAsStream("config.xml")); + + doc.getDocumentElement().normalize(); + + // Read exporter elements from the XML + NodeList nodeList = doc.getElementsByTagName("exporter"); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node; + String type = element.getElementsByTagName("type").item(0).getTextContent(); + String className = element.getElementsByTagName("class").item(0).getTextContent(); + exporterClassNames.put(type, className); + } + } + } catch (Exception e) { + throw new RuntimeException("Failed to load exporter configuration: " + e.getMessage(), e); + } + } + + public Exportable getExporter(String format) throws Exception { + String className = exporterClassNames.get(format); + if (className == null) { + throw new IllegalArgumentException("Unsupported export format: " + format); + } + return (Exportable) Class.forName(className).getDeclaredConstructor(Connection.class).newInstance(connection); + } + + public List getSupportedFormats() { + return new ArrayList<>(exporterClassNames.keySet()); + } +} \ No newline at end of file diff --git a/src/main/java/org/nmpl/exporters/HTMLExporter.java b/src/main/java/org/nmpl/exporters/HTMLExporter.java new file mode 100644 index 0000000..5faada5 --- /dev/null +++ b/src/main/java/org/nmpl/exporters/HTMLExporter.java @@ -0,0 +1,58 @@ +package org.nmpl.exporters; + +import org.nmpl.Exportable; + +import java.io.FileWriter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.Statement; + +public class HTMLExporter implements Exportable { + private final Connection connection; + + public HTMLExporter(Connection connection) { + this.connection = connection; + } + + @Override + public void export(String tableName, String fileName) { + try { + StringBuilder htmlContent = new StringBuilder(); + htmlContent.append(""); // Add border attribute to create table borders + htmlContent.append(System.lineSeparator()); + + // Fetch the data from the database table + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + tableName); + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnCount = metaData.getColumnCount(); + + // Generate table header + htmlContent.append("").append(System.lineSeparator()); + for (int i = 1; i <= columnCount; i++) { + htmlContent.append(" ").append(System.lineSeparator()); + } + htmlContent.append("").append(System.lineSeparator()); + + // Generate table data + while (resultSet.next()) { + htmlContent.append("").append(System.lineSeparator()); + for (int i = 1; i <= columnCount; i++) { + htmlContent.append(" ").append(System.lineSeparator()); + } + htmlContent.append("").append(System.lineSeparator()); + } + + htmlContent.append(" { + DbExporter manager; + try { + manager = new DbExporter(); + } + catch (SQLException e) { + throw new RuntimeException(e); + } + manager.setVisible(true); + }); + } +} diff --git a/src/main/java/org/nmpl/v1/Configurable.java b/src/main/java/org/nmpl/v1/Configurable.java new file mode 100644 index 0000000..c213c61 --- /dev/null +++ b/src/main/java/org/nmpl/v1/Configurable.java @@ -0,0 +1,5 @@ +package org.nmpl.v1; + +public interface Configurable { + String getExportType(); +} diff --git a/src/main/java/org/nmpl/v1/DbExporter.java b/src/main/java/org/nmpl/v1/DbExporter.java new file mode 100644 index 0000000..076f5fe --- /dev/null +++ b/src/main/java/org/nmpl/v1/DbExporter.java @@ -0,0 +1,114 @@ +package org.nmpl.v1; + +import javax.swing.*; +import java.awt.*; +import java.io.File; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class DbExporter extends JFrame { + private final JComboBox exportFormatComboBox; + private final JList tableList; + private final DefaultListModel tableListModel; + private final Connection connection; + + public DbExporter() throws SQLException { + connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankdb", "root", ""); + setTitle("Database Manager"); + setSize(400, 400); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // Create components + tableListModel = new DefaultListModel<>(); + tableList = new JList<>(tableListModel); + JButton showButton = new JButton("Show Tables"); + + ExporterFactory ef; + try { + ef = new ExporterFactory(connection); + } catch (Exception e) { + throw new RuntimeException(e); + } + + List formatList = new ArrayList<>(ef.getSupportedFormats()); + + exportFormatComboBox = new JComboBox<>(formatList.toArray(new String[0])); + JButton exportButton = new JButton("Export Table"); + + // Create panels for layout + JPanel topPanel = new JPanel(); + JPanel mainPanel = new JPanel(new BorderLayout()); + + // Set a vertical BoxLayout for the top panel + topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS)); + + // Add components to the top panel + topPanel.add(showButton); + topPanel.add(exportFormatComboBox); + topPanel.add(exportButton); + + mainPanel.add(new JScrollPane(tableList), BorderLayout.CENTER); + mainPanel.add(topPanel, BorderLayout.NORTH); + + // Add mainPanel to the frame + add(mainPanel); + + // Event handlers + showButton.addActionListener(e -> showTables()); + exportButton.addActionListener(e -> exportTable()); + } + + private void showTables() { + try { + DatabaseMetaData metaData = connection.getMetaData(); + String catalog = connection.getCatalog(); + ResultSet tables = metaData.getTables(catalog, null, null, new String[]{"TABLE"}); + + tableListModel.clear(); + + while (tables.next()) { + String tableName = tables.getString("TABLE_NAME"); + tableListModel.addElement(tableName); + } + + tables.close(); + } catch (SQLException e) { + e.printStackTrace(); + JOptionPane.showMessageDialog(this, "Failed to connect to the database or fetch tables."); + } + } + + private void exportTable() { + String selectedTable = tableList.getSelectedValue(); + if (selectedTable == null) { + JOptionPane.showMessageDialog(this, "Please select a table to export."); + return; + } + + String exportFormat = Objects.requireNonNull(exportFormatComboBox.getSelectedItem()).toString(); + String fileName = selectedTable + "." + exportFormat.toLowerCase(); + + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Save " + exportFormat + " File"); + fileChooser.setSelectedFile(new File(fileName)); + + int userSelection = fileChooser.showSaveDialog(this); + + if (userSelection == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + fileName = selectedFile.getAbsolutePath(); + + try { + ExporterFactory exportFactory = new ExporterFactory(connection); + Exportable exporter = exportFactory.getExporter(exportFormat); + exporter.export(selectedTable, fileName); + JOptionPane.showMessageDialog(this, "Table data exported to " + fileName); + } catch (Exception e) { + e.printStackTrace(); + JOptionPane.showMessageDialog(this, "Failed to export table."); + } + } + } +} diff --git a/src/main/java/org/nmpl/v1/Exportable.java b/src/main/java/org/nmpl/v1/Exportable.java new file mode 100644 index 0000000..d95320e --- /dev/null +++ b/src/main/java/org/nmpl/v1/Exportable.java @@ -0,0 +1,6 @@ +package org.nmpl.v1; +public interface Exportable { + void export(String tableName, String fileName) throws Exception; + +} + diff --git a/src/main/java/org/nmpl/v1/ExporterFactory.java b/src/main/java/org/nmpl/v1/ExporterFactory.java new file mode 100644 index 0000000..940da40 --- /dev/null +++ b/src/main/java/org/nmpl/v1/ExporterFactory.java @@ -0,0 +1,52 @@ +package org.nmpl.v1; + +import org.reflections.Reflections; + +import java.sql.Connection; +import java.util.*; + +public class ExporterFactory { + private final Map exporterClassNames; + private final Connection connection; + + public ExporterFactory(Connection connection) { + this.connection = connection; + exporterClassNames = loadExporterConfig(); + } + + private Map loadExporterConfig() { + Map exporterClassNames = new HashMap<>(); + try { + String exporterPackage = "org.nmpl.v1.exporters"; + Reflections reflections = new Reflections(exporterPackage); + Set> exporterClasses = reflections.getSubTypesOf(Exportable.class); + + for (Class exporterClass : exporterClasses) { + if (Configurable.class.isAssignableFrom(exporterClass)) { + String format = ((Configurable) exporterClass.getDeclaredConstructor().newInstance()).getExportType(); + if (format != null) { + exporterClassNames.put(format, exporterClass.getName()); + } + } + } + } catch (Exception e) { + throw new RuntimeException("Failed to load exporter configuration: " + e.getMessage(), e); + } + return exporterClassNames; + } + + + public Exportable getExporter(String format) throws Exception { + String className = exporterClassNames.get(format); + if (className == null) { + throw new IllegalArgumentException("Unsupported export format: " + format); + } + return (Exportable) Class.forName(className).getDeclaredConstructor(Connection.class).newInstance(connection); + } + + public List getSupportedFormats() { + List arl = new ArrayList<>(exporterClassNames.keySet()); + Collections.sort(arl); + return arl; + } +} \ No newline at end of file diff --git a/src/main/java/org/nmpl/v1/exporters/HTMLExporter.java b/src/main/java/org/nmpl/v1/exporters/HTMLExporter.java new file mode 100644 index 0000000..024d129 --- /dev/null +++ b/src/main/java/org/nmpl/v1/exporters/HTMLExporter.java @@ -0,0 +1,65 @@ +package org.nmpl.v1.exporters; + +import org.nmpl.v1.Configurable; +import org.nmpl.v1.Exportable; + +import java.io.FileWriter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; + +public class HTMLExporter implements Exportable, Configurable { + private final Connection connection; + + public HTMLExporter() { + this.connection = null; + } + public HTMLExporter(Connection connection) { + this.connection = connection; + } + + @Override + public void export(String tableName, String fileName) { + try { + StringBuilder htmlContent = new StringBuilder(); + htmlContent.append("
").append(metaData.getColumnName(i)).append("
").append(resultSet.getString(i)).append("
"); // Add border attribute to create table borders + htmlContent.append(System.lineSeparator()); + + // Fetch the data from the database table + assert connection != null; + ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM " + tableName); + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnCount = metaData.getColumnCount(); + + // Generate table header + htmlContent.append("").append(System.lineSeparator()); + for (int i = 1; i <= columnCount; i++) { + htmlContent.append(" ").append(System.lineSeparator()); + } + htmlContent.append("").append(System.lineSeparator()); + + // Generate table data + while (resultSet.next()) { + htmlContent.append("").append(System.lineSeparator()); + for (int i = 1; i <= columnCount; i++) { + htmlContent.append(" ").append(System.lineSeparator()); + } + htmlContent.append("").append(System.lineSeparator()); + } + + htmlContent.append(" { + DbExporter manager; + try { + manager = new DbExporter(); + } + catch (SQLException e) { + throw new RuntimeException(e); + } + manager.setVisible(true); + }); + } +} diff --git a/src/main/java/org/nmpl/v2/DbExporter.java b/src/main/java/org/nmpl/v2/DbExporter.java new file mode 100644 index 0000000..2af713d --- /dev/null +++ b/src/main/java/org/nmpl/v2/DbExporter.java @@ -0,0 +1,114 @@ +package org.nmpl.v2; + +import javax.swing.*; +import java.awt.*; +import java.io.File; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class DbExporter extends JFrame { + private final JComboBox exportFormatComboBox; + private final JList tableList; + private final DefaultListModel tableListModel; + private final Connection connection; + + public DbExporter() throws SQLException { + connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankdb", "root", ""); + setTitle("Database Manager"); + setSize(400, 400); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // Create components + tableListModel = new DefaultListModel<>(); + tableList = new JList<>(tableListModel); + JButton showButton = new JButton("Show Tables"); + + ExporterFactory ef; + try { + ef = new ExporterFactory(connection); + } catch (Exception e) { + throw new RuntimeException(e); + } + + List formatList = new ArrayList<>(ef.getSupportedFormats()); + + exportFormatComboBox = new JComboBox<>(formatList.toArray(new String[0])); + JButton exportButton = new JButton("Export Table"); + + // Create panels for layout + JPanel topPanel = new JPanel(); + JPanel mainPanel = new JPanel(new BorderLayout()); + + // Set a vertical BoxLayout for the top panel + topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS)); + + // Add components to the top panel + topPanel.add(showButton); + topPanel.add(exportFormatComboBox); + topPanel.add(exportButton); + + mainPanel.add(new JScrollPane(tableList), BorderLayout.CENTER); + mainPanel.add(topPanel, BorderLayout.NORTH); + + // Add mainPanel to the frame + add(mainPanel); + + // Event handlers + showButton.addActionListener(e -> showTables()); + exportButton.addActionListener(e -> exportTable()); + } + + private void showTables() { + try { + DatabaseMetaData metaData = connection.getMetaData(); + String catalog = connection.getCatalog(); + ResultSet tables = metaData.getTables(catalog, null, null, new String[]{"TABLE"}); + + tableListModel.clear(); + + while (tables.next()) { + String tableName = tables.getString("TABLE_NAME"); + tableListModel.addElement(tableName); + } + + tables.close(); + } catch (SQLException e) { + e.printStackTrace(); + JOptionPane.showMessageDialog(this, "Failed to connect to the database or fetch tables."); + } + } + + private void exportTable() { + String selectedTable = tableList.getSelectedValue(); + if (selectedTable == null) { + JOptionPane.showMessageDialog(this, "Please select a table to export."); + return; + } + + String exportFormat = Objects.requireNonNull(exportFormatComboBox.getSelectedItem()).toString(); + String fileName = selectedTable + "." + exportFormat.toLowerCase(); + + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Save " + exportFormat + " File"); + fileChooser.setSelectedFile(new File(fileName)); + + int userSelection = fileChooser.showSaveDialog(this); + + if (userSelection == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + fileName = selectedFile.getAbsolutePath(); + + try { + ExporterFactory exportFactory = new ExporterFactory(connection); + Exportable exporter = exportFactory.getExporter(exportFormat); + exporter.export(selectedTable, fileName); + JOptionPane.showMessageDialog(this, "Table data exported to " + fileName); + } catch (Exception e) { + e.printStackTrace(); + JOptionPane.showMessageDialog(this, "Failed to export table."); + } + } + } +} diff --git a/src/main/java/org/nmpl/v2/ExportType.java b/src/main/java/org/nmpl/v2/ExportType.java new file mode 100644 index 0000000..18fd25a --- /dev/null +++ b/src/main/java/org/nmpl/v2/ExportType.java @@ -0,0 +1,12 @@ +package org.nmpl.v2; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface ExportType { + String value(); +} \ No newline at end of file diff --git a/src/main/java/org/nmpl/v2/Exportable.java b/src/main/java/org/nmpl/v2/Exportable.java new file mode 100644 index 0000000..c41f460 --- /dev/null +++ b/src/main/java/org/nmpl/v2/Exportable.java @@ -0,0 +1,5 @@ +package org.nmpl.v2; +public interface Exportable { + void export(String tableName, String fileName) throws Exception; +} + diff --git a/src/main/java/org/nmpl/v2/ExporterFactory.java b/src/main/java/org/nmpl/v2/ExporterFactory.java new file mode 100644 index 0000000..66b827f --- /dev/null +++ b/src/main/java/org/nmpl/v2/ExporterFactory.java @@ -0,0 +1,52 @@ +package org.nmpl.v2; + +import org.reflections.Reflections; +import java.sql.Connection; +import java.util.*; + +public class ExporterFactory { + private final Map exporterClassNames; + private final Connection connection; + + public ExporterFactory(Connection connection) { + this.connection = connection; + exporterClassNames = new HashMap<>(); + loadExporterConfig(); + } + private void loadExporterConfig() { + try { + String exporterPackage = "org.nmpl.v2.exporters"; + Reflections reflections = new Reflections(exporterPackage); + Set> exporterClasses = reflections.getSubTypesOf(Exportable.class); + + for (Class exporterClass : exporterClasses) { + String format = getExportFormat(exporterClass); + if (format != null) { + exporterClassNames.put(format, exporterClass.getName()); + } + } + } catch (Exception e) { + throw new RuntimeException("Failed to load exporter configuration: " + e.getMessage(), e); + } + } + + private String getExportFormat(Class exporterClass) { + ExportType annotation = exporterClass.getAnnotation(ExportType.class); + if (annotation != null) { + return annotation.value(); + } + return null; + } + + public Exportable getExporter(String format) throws Exception { + String className = exporterClassNames.get(format); + if (className == null) { + throw new IllegalArgumentException("Unsupported export format: " + format); + } + return (Exportable) Class.forName(className).getDeclaredConstructor(Connection.class).newInstance(connection); + } + + public List getSupportedFormats() { + return new ArrayList<>(exporterClassNames.keySet()); + } +} \ No newline at end of file diff --git a/src/main/java/org/nmpl/v2/exporters/HTMLExporter.java b/src/main/java/org/nmpl/v2/exporters/HTMLExporter.java new file mode 100644 index 0000000..d6221db --- /dev/null +++ b/src/main/java/org/nmpl/v2/exporters/HTMLExporter.java @@ -0,0 +1,60 @@ +package org.nmpl.v2.exporters; + +import org.nmpl.v2.ExportType; +import org.nmpl.v2.Exportable; + +import java.io.FileWriter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.Statement; + +@ExportType("HTML") +public class HTMLExporter implements Exportable { + private final Connection connection; + + public HTMLExporter(Connection connection) { + this.connection = connection; + } + + @Override + public void export(String tableName, String fileName) { + try { + StringBuilder htmlContent = new StringBuilder(); + htmlContent.append("
").append(metaData.getColumnName(i)).append("
").append(resultSet.getString(i)).append("
"); // Add border attribute to create table borders + htmlContent.append(System.lineSeparator()); + + // Fetch the data from the database table + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + tableName); + ResultSetMetaData metaData = resultSet.getMetaData(); + int columnCount = metaData.getColumnCount(); + + // Generate table header + htmlContent.append("").append(System.lineSeparator()); + for (int i = 1; i <= columnCount; i++) { + htmlContent.append(" ").append(System.lineSeparator()); + } + htmlContent.append("").append(System.lineSeparator()); + + // Generate table data + while (resultSet.next()) { + htmlContent.append("").append(System.lineSeparator()); + for (int i = 1; i <= columnCount; i++) { + htmlContent.append(" ").append(System.lineSeparator()); + } + htmlContent.append("").append(System.lineSeparator()); + } + + htmlContent.append(" + + + HTML + org.nmpl.exporters.HTMLExporter + + + XML + org.nmpl.exporters.XMLExporter + + + TEST + org.nmpl.exporters.TestExporter + + + \ No newline at end of file diff --git a/src/test/java/org/nmpl/AppTest.java b/src/test/java/org/nmpl/AppTest.java new file mode 100644 index 0000000..1e03cff --- /dev/null +++ b/src/test/java/org/nmpl/AppTest.java @@ -0,0 +1,38 @@ +package org.nmpl; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +}
").append(metaData.getColumnName(i)).append("
").append(resultSet.getString(i)).append("