Initial commit

This commit is contained in:
Amit Kumar Nandi 2024-02-17 22:38:33 +05:30
commit 1389fb8bba
29 changed files with 1354 additions and 0 deletions

38
.gitignore vendored Normal file
View file

@ -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

113
Readme.md Normal file
View file

@ -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
<exporters>
<exporter>
<type>html</type>
<class>org.nmpl.exporters.HTMLExporter</class>
</exporter>
<exporter>
<type>xml</type>
<class>org.nmpl.exporters.XMLExporter</class>
</exporter>
<exporter>
<type>newformat</type>
<class>org.nmpl.exporters.NewFormatExporter</class>
</exporter>
<!-- Add more exporter configurations as needed -->
</exporters>
```
## 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.

45
pom.xml Normal file
View file

@ -0,0 +1,45 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.nmpl</groupId>
<artifactId>DbExporter</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>DbExporter</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version> <!-- Use the latest version available -->
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- Use the latest version -->
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
</dependencies>
</project>

View file

@ -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);
});
}
}

View file

@ -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<String> exportFormatComboBox;
private final JList<String> tableList;
private final DefaultListModel<String> 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<String> 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);
}
}
}
}

View file

@ -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());
}
}

View file

@ -0,0 +1,5 @@
package org.nmpl;
public interface Exportable {
void export(String tableName, String fileName) throws Exception;
}

View file

@ -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<String, String> 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<String> getSupportedFormats() {
return new ArrayList<>(exporterClassNames.keySet());
}
}

View file

@ -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("<table border=\"1\">"); // 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("<tr>").append(System.lineSeparator());
for (int i = 1; i <= columnCount; i++) {
htmlContent.append(" <th>").append(metaData.getColumnName(i)).append("</th>").append(System.lineSeparator());
}
htmlContent.append("</tr>").append(System.lineSeparator());
// Generate table data
while (resultSet.next()) {
htmlContent.append("<tr>").append(System.lineSeparator());
for (int i = 1; i <= columnCount; i++) {
htmlContent.append(" <td>").append(resultSet.getString(i)).append("</td>").append(System.lineSeparator());
}
htmlContent.append("</tr>").append(System.lineSeparator());
}
htmlContent.append("</table");
// Save HTML content to the specified file
try (FileWriter fileWriter = new FileWriter(fileName)) {
fileWriter.write(htmlContent.toString());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to HTML.");
}
}
}

View file

@ -0,0 +1,21 @@
package org.nmpl.exporters;
import org.nmpl.DbExporterException;
import org.nmpl.Exportable;
import java.sql.Connection;
public class TestExporter implements Exportable {
private final Connection connection;
public TestExporter(Connection connection) {
this.connection = connection;
}
@Override
public void export(String tableName, String fileName) {
try {
System.out.println("TEST EXPORTER\n DB NAME: "+connection.getCatalog());
} catch (Exception e) {
throw new DbExporterException("Failed to export table to HTML.",e);
}
}
}

View file

@ -0,0 +1,72 @@
package org.nmpl.exporters;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.nmpl.Exportable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
public class XMLExporter implements Exportable {
private final Connection connection;
public XMLExporter(Connection connection) {
this.connection = connection;
}
@Override
public void export(String tableName, String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element rootElement = doc.createElement("tableData");
doc.appendChild(rootElement);
// 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 XML elements for table data
while (resultSet.next()) {
Element row = doc.createElement("row");
rootElement.appendChild(row);
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
String columnValue = resultSet.getString(i);
Element column = doc.createElement(columnName);
column.appendChild(doc.createTextNode(columnValue));
row.appendChild(column);
}
}
// Configure transformer to format the XML with new lines
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// Save the XML content to the specified file
try (FileOutputStream fileOutputStream = new FileOutputStream(fileName)) {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(fileOutputStream);
transformer.transform(source, result);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to XML.");
}
}
}

View file

@ -0,0 +1,19 @@
package org.nmpl.v1;
import javax.swing.*;
import java.sql.SQLException;
public class App {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DbExporter manager;
try {
manager = new DbExporter();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
manager.setVisible(true);
});
}
}

View file

@ -0,0 +1,5 @@
package org.nmpl.v1;
public interface Configurable {
String getExportType();
}

View file

@ -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<String> exportFormatComboBox;
private final JList<String> tableList;
private final DefaultListModel<String> 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<String> 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.");
}
}
}
}

View file

@ -0,0 +1,6 @@
package org.nmpl.v1;
public interface Exportable {
void export(String tableName, String fileName) throws Exception;
}

View file

@ -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<String, String> exporterClassNames;
private final Connection connection;
public ExporterFactory(Connection connection) {
this.connection = connection;
exporterClassNames = loadExporterConfig();
}
private Map<String, String> loadExporterConfig() {
Map<String, String> exporterClassNames = new HashMap<>();
try {
String exporterPackage = "org.nmpl.v1.exporters";
Reflections reflections = new Reflections(exporterPackage);
Set<Class<? extends Exportable>> exporterClasses = reflections.getSubTypesOf(Exportable.class);
for (Class<? extends Exportable> 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<String> getSupportedFormats() {
List<String> arl = new ArrayList<>(exporterClassNames.keySet());
Collections.sort(arl);
return arl;
}
}

View file

@ -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("<table border=\"1\">"); // 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("<tr>").append(System.lineSeparator());
for (int i = 1; i <= columnCount; i++) {
htmlContent.append(" <th>").append(metaData.getColumnName(i)).append("</th>").append(System.lineSeparator());
}
htmlContent.append("</tr>").append(System.lineSeparator());
// Generate table data
while (resultSet.next()) {
htmlContent.append("<tr>").append(System.lineSeparator());
for (int i = 1; i <= columnCount; i++) {
htmlContent.append(" <td>").append(resultSet.getString(i)).append("</td>").append(System.lineSeparator());
}
htmlContent.append("</tr>").append(System.lineSeparator());
}
htmlContent.append("</table");
// Save HTML content to the specified file
try (FileWriter fileWriter = new FileWriter(fileName)) {
fileWriter.write(htmlContent.toString());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to HTML.");
}
}
@Override
public String getExportType() {
return "HTML";
}
}

View file

@ -0,0 +1,32 @@
package org.nmpl.v1.exporters;
import org.nmpl.v1.Configurable;
import org.nmpl.v1.Exportable;
import java.sql.Connection;
public class TestExporter implements Exportable, Configurable {
private final Connection connection;
public TestExporter() {
this.connection = null;
}
public TestExporter(Connection connection) {
this.connection = connection;
}
@Override
public void export(String tableName, String fileName) {
try {
System.out.println("TEST EXPORTER");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to HTML.");
}
}
@Override
public String getExportType() {
return "TEST";
}
}

View file

@ -0,0 +1,78 @@
package org.nmpl.v1.exporters;
import org.nmpl.v1.Configurable;
import org.nmpl.v1.Exportable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class XMLExporter implements Exportable, Configurable {
private final Connection connection;
public XMLExporter() {
this.connection = null;
}
public XMLExporter(Connection connection) {
this.connection = connection;
}
@Override
public void export(String tableName, String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element rootElement = doc.createElement("tableData");
doc.appendChild(rootElement);
// 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 XML elements for table data
while (resultSet.next()) {
Element row = doc.createElement("row");
rootElement.appendChild(row);
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
String columnValue = resultSet.getString(i);
Element column = doc.createElement(columnName);
column.appendChild(doc.createTextNode(columnValue));
row.appendChild(column);
}
}
// Configure transformer to format the XML with new lines
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// Save the XML content to the specified file
try (FileOutputStream fileOutputStream = new FileOutputStream(fileName)) {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(fileOutputStream);
transformer.transform(source, result);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to XML.");
}
}
@Override
public String getExportType() {
return "XML";
}
}

View file

@ -0,0 +1,19 @@
package org.nmpl.v2;
import javax.swing.*;
import java.sql.SQLException;
public class App {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DbExporter manager;
try {
manager = new DbExporter();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
manager.setVisible(true);
});
}
}

View file

@ -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<String> exportFormatComboBox;
private final JList<String> tableList;
private final DefaultListModel<String> 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<String> 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.");
}
}
}
}

View file

@ -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();
}

View file

@ -0,0 +1,5 @@
package org.nmpl.v2;
public interface Exportable {
void export(String tableName, String fileName) throws Exception;
}

View file

@ -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<String, String> 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<Class<? extends Exportable>> exporterClasses = reflections.getSubTypesOf(Exportable.class);
for (Class<? extends Exportable> 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<? extends Exportable> 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<String> getSupportedFormats() {
return new ArrayList<>(exporterClassNames.keySet());
}
}

View file

@ -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("<table border=\"1\">"); // 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("<tr>").append(System.lineSeparator());
for (int i = 1; i <= columnCount; i++) {
htmlContent.append(" <th>").append(metaData.getColumnName(i)).append("</th>").append(System.lineSeparator());
}
htmlContent.append("</tr>").append(System.lineSeparator());
// Generate table data
while (resultSet.next()) {
htmlContent.append("<tr>").append(System.lineSeparator());
for (int i = 1; i <= columnCount; i++) {
htmlContent.append(" <td>").append(resultSet.getString(i)).append("</td>").append(System.lineSeparator());
}
htmlContent.append("</tr>").append(System.lineSeparator());
}
htmlContent.append("</table");
// Save HTML content to the specified file
try (FileWriter fileWriter = new FileWriter(fileName)) {
fileWriter.write(htmlContent.toString());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to HTML.");
}
}
}

View file

@ -0,0 +1,26 @@
package org.nmpl.v2.exporters;
import org.nmpl.v2.ExportType;
import org.nmpl.v2.Exportable;
import java.sql.Connection;
@ExportType("TEST")
public class TestExporter implements Exportable {
private final Connection connection;
public TestExporter(Connection connection) {
this.connection = connection;
}
@Override
public void export(String tableName, String fileName) {
try {
System.out.println("TEST EXPORTER");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to HTML.");
}
}
}

View file

@ -0,0 +1,74 @@
package org.nmpl.v2.exporters;
import org.nmpl.v2.ExportType;
import org.nmpl.v2.Exportable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
@ExportType("XML")
public class XMLExporter implements Exportable {
private final Connection connection;
public XMLExporter(Connection connection) {
this.connection = connection;
}
@Override
public void export(String tableName, String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element rootElement = doc.createElement("tableData");
doc.appendChild(rootElement);
// 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 XML elements for table data
while (resultSet.next()) {
Element row = doc.createElement("row");
rootElement.appendChild(row);
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
String columnValue = resultSet.getString(i);
Element column = doc.createElement(columnName);
column.appendChild(doc.createTextNode(columnValue));
row.appendChild(column);
}
}
// Configure transformer to format the XML with new lines
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// Save the XML content to the specified file
try (FileOutputStream fileOutputStream = new FileOutputStream(fileName)) {
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(fileOutputStream);
transformer.transform(source, result);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to export table to XML.");
}
}
}

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<exporters>
<exporter>
<type>HTML</type>
<class>org.nmpl.exporters.HTMLExporter</class>
</exporter>
<exporter>
<type>XML</type>
<class>org.nmpl.exporters.XMLExporter</class>
</exporter>
<exporter>
<type>TEST</type>
<class>org.nmpl.exporters.TestExporter</class>
</exporter>
<!-- Add additional export formats here -->
</exporters>

View file

@ -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 );
}
}