Compare commits

..

5 commits

Author SHA1 Message Date
Amit Kumar Nandi
a8978b4aa6 fixups 2024-03-01 04:00:03 +05:30
Amit Kumar Nandi
853b1d81ac fixups 2024-03-01 03:56:26 +05:30
Amit Kumar Nandi
11e4554ad7 Initial Commit 2024-03-01 03:32:02 +05:30
Amit Kumar Nandi
fed3887aee Initial Commit 2024-02-18 02:40:02 +05:30
Amit Kumar Nandi
f1adc67dc2 Initial Commit 2024-02-18 01:36:05 +05:30
22 changed files with 304 additions and 182 deletions

View file

@ -1,6 +1,6 @@
## 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.
This is a Java application for exporting data from a MySQL database table to various formats (e.g., HTML, XML, etc.). The application uses Swing for the graphical user interface and supports a plug-and-play architecture with configuration-less addition of new export formats without changing existing code.
## Table of Contents
@ -20,6 +20,12 @@ This is a Java application for exporting data from a MySQL database to various f
* Extensible architecture for adding new export formats without modifying existing code.
* Graphical user interface using Swing.
* Virtually configurationless operation.
</br>
### Variants
* `v0` &emsp;&emsp;&emsp; :`(uses an XML config file for adding new export formats)` \
* `v1` &emsp;&emsp;&emsp; :`(Configurationless addition of new export formats)`\
* `Base App` : `v1 + new export format name annotations (@ExportType) `
## Prerequisites
@ -42,7 +48,7 @@ This is a Java application for exporting data from a MySQL database to various f
3. Run using jar:
```bash
java -jar out/DbExporter.jar
java -jar target/DbExporter.jar
<p style="text-align: center;">OR</p>
4. Run using java mainClass:
@ -68,13 +74,29 @@ 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.
The application employs a plugin architecture, allowing you to add new export formats without modifying existing code or addintional config. 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:
```java
package org.nmpl.exporters;
import org.nmpl.Exportable;
public class NewFormatExporter implements Exportable {
// Implement the export method as per your requirements
}
```
You can give the name of the export format using annotaions like this:
```java
package org.nmpl.exporters;
import org.nmpl.ExportType;
import org.nmpl.Exportable;
@ExportType("Export_Type_Name")
public class NewFormatExporter implements Exportable {
// Implement the export method as per your requirements
}
@ -85,7 +107,12 @@ No changes to the existing code are needed. The new class is automatically recog
## 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.
The application is designed for configurationless operation due to its internal usage of Reflection and class loader libraries.
***
#### Note : You may choose to use the version of the program that does not uses an XML configuration file to load the new export types `Go to the V0 directory and run the App.java inside it`
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:

34
pom.xml
View file

@ -31,10 +31,11 @@
<version>3.12.0</version> <!-- Use the latest version -->
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<groupId>org.junit</groupId>
<artifactId>junit5-engine</artifactId>
<version>5.0.0-ALPHA</version>
<scope>test</scope>
</dependency>
@ -44,6 +45,31 @@
<version>0.10.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.easytesting/fest-swing -->
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-swing</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
@ -83,7 +109,7 @@
<transformers>
<!-- add Main-Class to manifest file -->
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.nmpl.App</mainClass>
<mainClass>org.nmpl.v0.App</mainClass>
</transformer>
</transformers>
</configuration>

View file

@ -8,9 +8,7 @@ public class App {
final String dbName = "shortener";
final String username = "root";
final String pasword = "1234qwer";
SwingUtilities.invokeLater(() -> {
DbExporter manager;
try {
manager = new DbExporter(dbName,username,pasword);

View file

@ -75,9 +75,8 @@ public class DbExporter extends JFrame {
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);
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to connect to the database or fetch tables.");
}
}
@ -107,9 +106,8 @@ public class DbExporter extends JFrame {
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);
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to export table.");
}
}
}

View file

@ -1,4 +1,4 @@
package org.nmpl.v2;
package org.nmpl;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;

View file

@ -1,17 +1,9 @@
package org.nmpl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.reflections.Reflections;
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;
import java.util.*;
public class ExporterFactory {
private final Map<String, String> exporterClassNames;
@ -22,25 +14,16 @@ public class ExporterFactory {
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"));
String exporterPackage = "org.nmpl.exporters";
Reflections reflections = new Reflections(exporterPackage);
Set<Class<? extends Exportable>> exporterClasses = reflections.getSubTypesOf(Exportable.class);
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);
for (Class<? extends Exportable> exporterClass : exporterClasses) {
String format = getExportFormat(exporterClass);
if (format != null) {
exporterClassNames.put(format, exporterClass.getName());
}
}
} catch (Exception e) {
@ -48,6 +31,14 @@ public class ExporterFactory {
}
}
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) {

View file

@ -1,5 +1,6 @@
package org.nmpl.exporters;
import org.nmpl.ExportType;
import org.nmpl.Exportable;
import java.io.FileWriter;
@ -8,6 +9,7 @@ import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
@ExportType("HTML")
public class HTMLExporter implements Exportable {
private final Connection connection;

View file

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

View file

@ -1,22 +1,24 @@
package org.nmpl.exporters;
import org.nmpl.ExportType;
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;
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;
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;
@ExportType("XML")
public class XMLExporter implements Exportable {
private final Connection connection;

View file

@ -1,16 +1,20 @@
package org.nmpl.v2;
package org.nmpl.v0;
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();
manager = new DbExporter(dbName,username,pasword);
}
catch (SQLException e) {
catch (Exception e) {
throw new RuntimeException(e);
}
manager.setVisible(true);

View file

@ -1,4 +1,4 @@
package org.nmpl.v2;
package org.nmpl.v0;
import javax.swing.*;
import java.awt.*;
@ -9,13 +9,13 @@ import java.util.List;
import java.util.Objects;
public class DbExporter extends JFrame {
private final JComboBox<String> exportFormatComboBox;
private final JList<String> tableList;
protected final JComboBox<String> exportFormatComboBox;
protected 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", "");
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);
@ -60,7 +60,7 @@ public class DbExporter extends JFrame {
exportButton.addActionListener(e -> exportTable());
}
private void showTables() {
protected void showTables() {
try {
DatabaseMetaData metaData = connection.getMetaData();
String catalog = connection.getCatalog();
@ -75,12 +75,13 @@ public class DbExporter extends JFrame {
tables.close();
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to connect to the database or fetch tables.");
String error = "Failed to connect to the database or fetch tables.";
JOptionPane.showMessageDialog(this, error);
throw new DbExporterException(error, e);
}
}
private void exportTable() {
protected void exportTable() {
String selectedTable = tableList.getSelectedValue();
if (selectedTable == null) {
JOptionPane.showMessageDialog(this, "Please select a table to export.");
@ -106,8 +107,9 @@ public class DbExporter extends JFrame {
exporter.export(selectedTable, fileName);
JOptionPane.showMessageDialog(this, "Table data exported to " + fileName);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to export table.");
String error = "Failed to export table.";
JOptionPane.showMessageDialog(this, error);
throw new DbExporterException(error, e);
}
}
}

View file

@ -1,4 +1,4 @@
package org.nmpl;
package org.nmpl.v0;
public class DbExporterException extends RuntimeException {

View file

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

View file

@ -0,0 +1,66 @@
package org.nmpl.v0;
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) {
String className = exporterClassNames.get(format);
if (className == null) {
throw new IllegalArgumentException("Unsupported export format: " + format);
}
try {
return (Exportable) Class.forName(className).getDeclaredConstructor(Connection.class).newInstance(connection);
} catch (Exception e) {
throw new RuntimeException("Failed to create exporter instance", e);
}
}
public List<String> getSupportedFormats() {
return new ArrayList<>(exporterClassNames.keySet());
}
}

View file

@ -1,7 +1,6 @@
package org.nmpl.v2.exporters;
package org.nmpl.v0.exporters;
import org.nmpl.v2.ExportType;
import org.nmpl.v2.Exportable;
import org.nmpl.v0.Exportable;
import java.io.FileWriter;
import java.sql.Connection;
@ -9,7 +8,6 @@ import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
@ExportType("HTML")
public class HTMLExporter implements Exportable {
private final Connection connection;

View file

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

View file

@ -1,7 +1,6 @@
package org.nmpl.v2.exporters;
package org.nmpl.v0.exporters;
import org.nmpl.v2.ExportType;
import org.nmpl.v2.Exportable;
import org.nmpl.v0.Exportable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@ -18,7 +17,6 @@ import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
@ExportType("XML")
public class XMLExporter implements Exportable {
private final Connection connection;

View file

@ -1,52 +0,0 @@
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

@ -1,3 +1,3 @@
Manifest-Version: 1.0
Main-Class: org.nmpl.App
Main-Class: org.nmpl.v0.App

View file

@ -2,15 +2,15 @@
<exporters>
<exporter>
<type>HTML</type>
<class>org.nmpl.exporters.HTMLExporter</class>
<class>org.nmpl.v0.exporters.HTMLExporter</class>
</exporter>
<exporter>
<type>XML</type>
<class>org.nmpl.exporters.XMLExporter</class>
<class>org.nmpl.v0.exporters.XMLExporter</class>
</exporter>
<exporter>
<type>TEST</type>
<class>org.nmpl.exporters.TestExporter</class>
<class>org.nmpl.v0.exporters.TestExporter</class>
</exporter>
<!-- Add additional export formats here -->
</exporters>

View file

@ -1,38 +1,40 @@
package org.nmpl;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.fest.swing.fixture.FrameFixture;
import org.junit.jupiter.api.Test;
import org.nmpl.DbExporter;
/**
* 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 );
import javax.swing.*;
import java.sql.SQLException;
import static org.fest.swing.core.matcher.JButtonMatcher.withText;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AppTest {
private FrameFixture frame;
@Test
void setUp() {
final String dbName = "testDb";
final String username = "root";
final String password = "password";
SwingUtilities.invokeLater(() -> {
DbExporter app = null;
try {
app = new DbExporter(dbName, username, password);
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
frame = new FrameFixture(app);
frame.show();
frame.button(withText("Show Tables")).click();
assertTrue(frame.table().rowCount() >= 2); // Assuming tables are populated
}
});
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

View file

@ -0,0 +1,59 @@
package org.nmpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.nmpl.exporters.XMLExporter;
import java.sql.Connection;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class ExporterFactoryTest {
private Connection connection;
@Mock
private Connection mockConnection;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
// Assuming you have a method in ExporterFactory to set the Connection
// You may need to modify ExporterFactory to accept Connection as a parameter
ExporterFactory exporterFactory = new ExporterFactory(mockConnection);
}
@Test
void testGetExporter() {
ExporterFactory exporterFactory = new ExporterFactory(connection);
try {
// Assuming 'XML' is a supported export format in your config.xml
Exportable exporter = exporterFactory.getExporter("XML");
assertNotNull(exporter);
System.out.println("Actual class of exporter: " + exporter.getClass().getName());
assertTrue(exporter instanceof XMLExporter); // Adjust based on your actual exporter class
} catch (Exception e) {
e.printStackTrace();
fail("Exception occurred while getting exporter");
}
}
@Test
void testGetSupportedFormats() {
ExporterFactory exporterFactory = new ExporterFactory(connection);
List<String> supportedFormats = exporterFactory.getSupportedFormats();
assertNotNull(supportedFormats);
assertFalse(supportedFormats.isEmpty());
assertTrue(supportedFormats.contains("XML")); // Adjust based on your actual supported formats
}
}