This commit is contained in:
Amit Kumar Nandi 2023-08-13 01:06:41 +05:30
commit d3528d161b
33 changed files with 3982 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

8
.idea/.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View file

@ -0,0 +1,16 @@
<component name="ArtifactManager">
<artifact type="jar" build-on-make="true" name="Tagger:jar">
<output-path>$PROJECT_DIR$/out/artifacts/Tagger_jar</output-path>
<root id="archive" name="Tagger.jar">
<element id="directory" name="META-INF">
<element id="file-copy" path="$PROJECT_DIR$/META-INF/MANIFEST.MF" />
</element>
<element id="module-output" name="Tagger" />
<element id="module-test-output" name="Tagger" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/mysql/mysql-connector-java/8.0.28/mysql-connector-java-8.0.28.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/junit/junit/3.8.1/junit-3.8.1.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/org/json/json/20230618/json-20230618.jar" path-in-jar="/" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/com/google/protobuf/protobuf-java/3.11.4/protobuf-java-3.11.4.jar" path-in-jar="/" />
</root>
</artifact>
</component>

12
.idea/dataSources.xml Normal file
View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="@localhost" uuid="988b7668-c8d3-4656-ba6c-7293371a3b78">
<driver-ref>mariadb</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.mariadb.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mariadb://localhost:3306</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

7
.idea/encodings.xml Normal file
View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

13
.idea/misc.xml Normal file
View file

@ -0,0 +1,13 @@
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_20" default="true" project-jdk-name="openjdk-20" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View file

@ -0,0 +1,15 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="TagReplacementToolApp" type="Application" factoryName="Application" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="com.tagger.TagReplacementToolApp" />
<module name="Tagger" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="com.tagger.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

8
.idea/sqldialects.xml Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/java/com/tagger/console/tagger.sql" dialect="MySQL" />
<file url="file://$PROJECT_DIR$/src/main/java/com/tagger/tagger.sql" dialect="MySQL" />
<file url="file://$PROJECT_DIR$/tagger.sql" dialect="MySQL" />
</component>
</project>

6
.idea/vcs.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

127
.idea/workspace.xml Normal file
View file

@ -0,0 +1,127 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="0b68a305-54e6-4883-bda9-826bb4c92443" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/artifacts/Tagger_jar.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/dataSources.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/encodings.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/runConfigurations/TagReplacementToolApp.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/sqldialects.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/META-INF/MANIFEST.MF" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pom.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/Changelog" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/DeveloperDoc" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/Readme" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/TagReplacementToolApp.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/TagReplacementToolConfig.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/TagReplacementToolController.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/TagReplacementToolModel.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/TagReplacementToolView.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/Driver.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/Driverv2.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/TagReplacementTool.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/TagReplacementToolv2.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/TagReplacementToolv3.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/hasher.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/tagger.sql" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/console/trtconfig.json" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/old/Tagrt.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/old/TagrtGUI.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/com/tagger/tagger.sql" afterDir="false" />
<change afterPath="$PROJECT_DIR$/tagger.sql" afterDir="false" />
<change afterPath="$PROJECT_DIR$/trtconfig.json" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="ProjectId" id="2TbT5d2jyOZ8ISSt78ZdwNyjlDh" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;Downloaded.Files.Path.Enabled&quot;: &quot;false&quot;,
&quot;Repository.Attach.Annotations&quot;: &quot;false&quot;,
&quot;Repository.Attach.JavaDocs&quot;: &quot;false&quot;,
&quot;Repository.Attach.Sources&quot;: &quot;false&quot;,
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;WebServerToolWindowFactoryState&quot;: &quot;false&quot;,
&quot;git-widget-placeholder&quot;: &quot;master&quot;,
&quot;ignore.virus.scanning.warn.message&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;C:/Users/bigwi/IdeaProjects/Tagger/out/Tagger&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;project.structure.last.edited&quot;: &quot;Artifacts&quot;,
&quot;project.structure.proportion&quot;: &quot;0.15&quot;,
&quot;project.structure.side.proportion&quot;: &quot;0.43103448&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.pathVariables&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
},
&quot;keyToStringList&quot;: {
&quot;DatabaseDriversLRU&quot;: [
&quot;mysql&quot;,
&quot;mariadb&quot;
]
}
}</component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="C:\Users\bigwi\IdeaProjects\Tagger" />
<recent name="C:\Users\amit\IdeaProjects\Tagger\src\main\java\com\tagger\console" />
<recent name="C:\Users\amit\IdeaProjects\Tagger\src\main\java\com\tagger\old" />
<recent name="C:\Users\amit\IdeaProjects\Tagger\src\main\java\com\tagger" />
</key>
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\bigwi\IdeaProjects\Tagger" />
</key>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="0b68a305-54e6-4883-bda9-826bb4c92443" name="Changes" comment="" />
<created>1691310599944</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1691310599944</updated>
<workItem from="1691310602060" duration="2951000" />
<workItem from="1691506042022" duration="1150000" />
<workItem from="1691510071025" duration="13000" />
<workItem from="1691510639810" duration="13000" />
<workItem from="1691852023698" duration="492000" />
<workItem from="1691852532910" duration="397000" />
<workItem from="1691852940870" duration="2648000" />
<workItem from="1691855942286" duration="944000" />
<workItem from="1691861615461" duration="6000" />
<workItem from="1691862143759" duration="3324000" />
<workItem from="1691868127578" duration="67000" />
<workItem from="1691868470494" duration="108000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="XSLT-Support.FileAssociations.UIState">
<expand />
<select />
</component>
</project>

3
META-INF/MANIFEST.MF Normal file
View file

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: com.tagger.TagReplacementToolApp

50
pom.xml Normal file
View file

@ -0,0 +1,50 @@
<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>com.tagger</groupId>
<artifactId>Tagger</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Tagger</name>
<url>https://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>20</source>
<target>20</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,49 @@
CHANGELOG FILE :
Version History:
Version 0.1 (Initial Development):
Created the basic structure of the Tag Replacement Tool program.
Implemented database connectivity to fetch MO names.
Provided a simple GUI with a combo box to select MO names.
Supported loading MO content from the database based on the selected MO name.
Implemented basic tag replacement functionality for tags with content only.
Version 0.2:
Added support for tags with only names and no content during the replacement process.
Updated the GUI to show a welcome heading on the MO name selection dialog.
Improved validation and error handling for database connections.
Enhanced the JSON configuration loading to handle errors more gracefully.
Version 0.3:
Refactored the code to use the MVC design pattern.
Separated frontend (View) and business logic (Model) into different classes.
Used lambda expressions and functional interfaces for event handling.
Introduced a Controller class to manage interactions between Model and View.
Implemented toolbar with "Open," "Save," "Load," "Help," and "About" buttons.
Added "Help" and "About" dialogs to display relevant information to the user.
Version 0.4:
Enabled opening a specific website when the "Open" button is clicked.
Supported saving and loading MO data to and from custom .trt files.
Implemented custom dialog for tag replacement, including tag name, comments, and replacement text input.
Introduced a separate final content window to display the processed MO content after replacement.
Handled errors related to database connections and configuration file loading.
Improved the GUI design for a better user experience.
Version 0.5 (Upcoming Changes):
Updated the TagReplacementToolConfig class to use properties file or environment variables for configuration.
Added support for internationalization (i18n) and localization (l10n) for the user interface.
Implemented data persistence to store processed MO content back into the database.
Enhanced the GUI with keyboard shortcuts for important actions in the application.
Included unit tests to ensure the correctness of the core functionality.
Optimized database queries and handling of large datasets.
Version 1.0 (Future Release):
Finalized and polished the Tag Replacement Tool for production use.
Documented the code and provided user documentation.
Performed extensive testing and bug fixing for a stable release.
Prepared for official deployment and distribution.
Note: The version history provided here is just an example and can be modified based on the actual progress and updates of the project. The version numbers and features are subject to change as development continues.

View file

@ -0,0 +1,88 @@
Developer Docs
Tag Replacement Tool Developer Documentation
Introduction
The Tag Replacement Tool is a Java desktop application designed to simplify the process of tag replacement in Managed Object (MO) content. This document provides a comprehensive guide for developers working on the application. It covers the architecture, classes, methods, and attributes used in the application.
Architecture
The Tag Replacement Tool follows the Model-View-Controller (MVC) design pattern to separate the concerns of data management, user interface, and application logic. The architecture consists of three main components:
Model: Represents the data and business logic of the application. Includes classes related to database management and tag processing.
View: Represents the user interface of the application. Includes classes related to GUI components and user interactions.
Controller: Acts as an intermediary between the Model and View. Handles user input, invokes business logic, and updates the View accordingly.
Architecture Diagram
Package Structure
The application is organized into the following packages:
releasemvc: Contains the main class to launch the application.
model: Contains classes related to the data model and database management.
view: Contains classes related to the user interface and GUI components.
controller: Contains classes related to the application's logic and user interactions.
Class Details
Model Package
TagReplacementToolModel: Represents the data model of the application. Contains attributes to store database connection details and methods to handle database operations and tag processing.
Attributes:
DB_URL: String, the JDBC URL for the database connection.
USER: String, the username for the database connection.
PASS: String, the password for the database connection.
DB_NAME: String, the name of the database to use.
TABLE1_NAME: String, the name of the table containing MO names, content, and tags.
TABLE2_NAME: String, the name of the table containing tag comments.
Methods:
connectToDatabase(): Establishes a connection to the database.
getMoNames(): Retrieves an array of available MO names from the database.
processMoContent(String moName): Processes the MO content for tag replacement.
extractTags(String moContent): Extracts tags from the MO content.
getTagName(String tag): Gets the tag name from the tag (handles tags with and without content).
getTagComment(String tagName): Retrieves the tag comment from the database for a given tag name.
replaceTag(String moName, String tagName, String replacement): Replaces a tag in the MO content with the provided replacement value.
saveMoContent(String moName, String moContent): Saves the processed MO content back to the database.
View Package
TagReplacementToolView: Represents the user interface of the application. Contains GUI components and methods for UI interactions.
Methods:
createAndShowGUI(): Creates and displays the main application window.
createToolBar(): Creates the toolbar with buttons and their action listeners.
createInputPanel(): Creates the input panel with MO name selection and process button.
createOutputPanel(): Creates the output panel to display the processed content.
showHelpDialog(): Displays the "Help" dialog with additional information.
showAboutDialog(): Displays the "About" dialog with version and author information.
showInputDialogWithInfo(String message, String moName, String tagName, String tagComment): Displays the replacement dialog with tag information.
showFinalContentWindow(String moContent): Displays the final processed MO content in a separate window.
Controller Package
TagReplacementToolController: Represents the controller of the application. Handles user interactions and updates the Model and View accordingly.
Methods:
attachEventListeners(): Attaches event listeners to GUI components.
processMoContent(): Invokes the tag replacement process for the selected MO name.
openWebsite(String url): Opens a website URL in the default web browser.
saveData(): Saves the processed MO content to a custom ".trt" file.
loadData(): Loads MO content from a ".trt" file.
loadConfig(): Loads configuration settings from "trtconfig.json".
Version History
Refer to the version history section for a detailed list of updates made to the application.
Conclusion
The Tag Replacement Tool provides a structured and modular approach to tag replacement in Managed Object content. Developers can easily extend and modify the application to suit specific requirements. The MVC architecture ensures a clear separation of concerns and enhances code maintainability and scalability.

View file

@ -0,0 +1,86 @@
Sure! Let's provide a detailed description of the Tag Replacement Tool application and its architecture:
Tag Replacement Tool Application Description:
The Tag Replacement Tool is a desktop application designed to help users perform tag replacement in MO (Managed Object) content. Managed Objects are entities managed by a network management system in telecommunications or network domains. These MOs often contain tags that need to be replaced with specific values, and the application simplifies this process.
Application Features:
GUI Interface: The application provides a user-friendly Graphical User Interface (GUI) for easy interaction with the users. It uses Swing, a Java GUI toolkit, to build the UI components.
Database Integration: The application integrates with an external relational database to store and retrieve MO-related data. This database holds MO names, their content, and tag information.
Tag Replacement: The main functionality of the application is to replace tags within MO content with user-defined values. Users can select an MO from a dropdown list, view its content, and replace tags interactively.
Configurable Settings: The application loads configuration settings from a JSON file named "trtconfig.json." These settings include database credentials, table names, and other options, making the application flexible for different environments.
File Operations: The application supports saving the processed MO content to custom ".trt" files and loading data from these files for future use.
Help and About Dialogs: The application provides "Help" and "About" dialogs that display relevant information about the tool.
Application Architecture:
The Tag Replacement Tool follows the Model-View-Controller (MVC) architectural pattern, which separates the application into three main components:
Model:
The Model represents the data and business logic of the application. It encapsulates the interaction with the database and tag replacement operations.
Key components:
TagReplacementToolModel: Manages data related to MOs, tags, and processed content. It interacts with the database to fetch and update data.
TagReplacementToolConfig: Handles loading configuration from "trtconfig.json."
View:
The View handles the user interface and presentation layer. It is responsible for displaying information to the user and capturing user inputs.
Key components:
TagReplacementToolView: Builds and manages the GUI components like combo boxes, buttons, text areas, and dialogs.
Controller:
The Controller acts as an intermediary between the Model and View. It facilitates communication and coordination between the two.
Key components:
TagReplacementToolController: Listens to user actions, processes user inputs, and triggers appropriate operations in the Model.
Interaction Flow:
When the application starts (TagReplacementToolApp), it initializes the Model (TagReplacementToolModel) and loads the configuration from "trtconfig.json" using TagReplacementToolConfig.
The Model establishes a connection to the external database using the database credentials from the configuration.
The Model retrieves a list of MO names from the database and populates the dropdown list in the View.
When the user selects an MO from the dropdown list and clicks the "Process" button, the Controller (TagReplacementToolController) captures the event.
The Controller communicates with the Model to fetch the MO content and extract tags from it.
The Controller then interacts with the View to display the MO content and initiate the tag replacement process.
For each tag, the Controller shows a replacement dialog (showInputDialogWithInfo) and takes the user's input for the replacement value.
The Controller updates the Model with the user's input and performs tag replacement in the MO content.
The Controller communicates with the View to display the final processed MO content in a separate window (showFinalContentWindow).
The user can copy the final processed MO content to the clipboard or save it to a custom ".trt" file.
Version History:
Version 1.0:
Basic application framework with MVC architecture.
GUI interface with "Process," "Open," "Save," "Load," "Help," and "About" buttons.
Tag replacement for MOs with tags containing both name and content.
Version 1.1:
Improved error handling and GUI feedback for database connection failures.
Added "Welcome" heading on the MO name selection dialog.
Refactored code for better organization and readability.
Version 1.2:
Enhanced getTagName method to handle tags with only name and no content.
Version 1.3:
Improved user experience by removing {# and } characters from tag names in the replacement dialog.
Bug fix for tag replacement not working for tags with only name.
Version 1.4:
Shortened code and optimized loading of configuration settings from "trtconfig.json."
Added extensive logging for debugging and error tracking.
Please note that this version history is fictional and provided for illustrative purposes. In a real development scenario, each version would include detailed release notes, bug fixes, enhancements, and other relevant changes.

View file

@ -0,0 +1,23 @@
package com.tagger;
import java.util.Vector;
import javax.swing.SwingUtilities;
public class TagReplacementToolApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TagReplacementToolConfig tc = new TagReplacementToolConfig();
Vector<String> vec = new Vector<>();
tc.getClass().getDeclaredFields();
for (var field : tc.getClass().getDeclaredFields()) {
field.setAccessible(true);
try { vec.add((String) field.get(tc));}
catch (IllegalAccessException e) { e.printStackTrace();}
}
TagReplacementToolModel model = new TagReplacementToolModel(
vec.get(1), vec.get(2), vec.get(3), vec.get(4), vec.get(5));
TagReplacementToolView view = new TagReplacementToolView();
new TagReplacementToolController(model, view);
});
}
}

View file

@ -0,0 +1,128 @@
package com.tagger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.json.JSONObject;
import org.json.JSONTokener;
public class TagReplacementToolConfig {
public TagReplacementToolConfig()
{
loadConfig();
}
static final String CONFIG_FILE_PATH = "C:\\trtconfig.json";
// Configuration variables (from trtconfig.json) - Replace with your own values
private String DB_URL = "";
private String USER = "";
private String PASS = "";
private String TABLE1_NAME = "";
private String TABLE2_NAME = "";
private void loadConfig() {
try {
String configData = readFile(CONFIG_FILE_PATH);
JSONObject configJson = new JSONObject(new JSONTokener(configData));
setDB_URL(configJson.getString("DB_URL"));
setUSER(configJson.getString("USER"));
setPASS(configJson.getString("PASS"));
//DB_NAME = configJson.getString("DB_NAME");
setTABLE1_NAME(configJson.getString("TABLE1_NAME"));
setTABLE2_NAME(configJson.getString("TABLE2_NAME"));
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error loading configuration from " + CONFIG_FILE_PATH,
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private static String readFile(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
}
return content.toString();
}
/**
* @return the dB_URL
*/
public String getDB_URL() {
return DB_URL;
}
/**
* @param dB_URL the dB_URL to set
*/
public void setDB_URL(String dB_URL) {
DB_URL = dB_URL;
}
/**
* @return the uSER
*/
public String getUSER() {
return USER;
}
/**
* @param uSER the uSER to set
*/
public void setUSER(String uSER) {
USER = uSER;
}
/**
* @return the pASS
*/
public String getPASS() {
return PASS;
}
/**
* @param pASS the pASS to set
*/
public void setPASS(String pASS) {
PASS = pASS;
}
/**
* @return the tABLE1_NAME
*/
public String getTABLE1_NAME() {
return TABLE1_NAME;
}
/**
* @param tABLE1_NAME the tABLE1_NAME to set
*/
public void setTABLE1_NAME(String tABLE1_NAME) {
TABLE1_NAME = tABLE1_NAME;
}
/**
* @return the tABLE2_NAME
*/
public String getTABLE2_NAME() {
return TABLE2_NAME;
}
/**
* @param tABLE2_NAME the tABLE2_NAME to set
*/
public void setTABLE2_NAME(String tABLE2_NAME) {
TABLE2_NAME = tABLE2_NAME;
}
}

View file

@ -0,0 +1,22 @@
package com.tagger;
public class TagReplacementToolController {
@SuppressWarnings("unused")
private TagReplacementToolModel model;
private TagReplacementToolView view;
public TagReplacementToolController(TagReplacementToolModel model, TagReplacementToolView view) {
this.model = model;
this.view = view;
initController();
}
private void initController() {
// Attach event listeners and handle user interactions
loadMoNames();
}
private void loadMoNames() {
String[] moNames = TagReplacementToolModel.getMoNames();
view.setMoNames(moNames);
}
// Other methods for handling events and updating the model and view
}

View file

@ -0,0 +1,123 @@
package com.tagger;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagReplacementToolModel {
static String DB_URL;
static String USER;
static String PASS;
static String TABLE1_NAME;
static String TABLE2_NAME;
public TagReplacementToolModel(String dbUrl, String user, String pass, String table1, String table2) {
TagReplacementToolModel.DB_URL = dbUrl;
TagReplacementToolModel.USER = user;
TagReplacementToolModel.PASS = pass;
TagReplacementToolModel.TABLE1_NAME = table1;
TagReplacementToolModel.TABLE2_NAME = table2;
}
// Create the tables if they don't exist
static void createTables(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String createTable1Query = "CREATE TABLE IF NOT EXISTS " + TABLE1_NAME + " (" +
"mo_name TEXT PRIMARY KEY, " +
"mo_content TEXT, " +
"mo_tags TEXT)";
stmt.execute(createTable1Query);
String createTable2Query = "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + " (" +
"mo_tags TEXT PRIMARY KEY, " +
"tag_comment TEXT)";
stmt.execute(createTable2Query);
}
}
public static String[] getMoNames() {
List<String> moNameList = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mo_name FROM " + TABLE1_NAME)) {
while (rs.next()) {
moNameList.add(rs.getString("mo_name"));
}
} catch (SQLException e) {
TagReplacementToolView.showSQLErrorMessage(e);
e.printStackTrace();
}
return moNameList.toArray(new String[0]);
}
public static boolean isMoNameExists(String moName) {
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement("SELECT mo_name FROM " + TABLE1_NAME + " WHERE mo_name = ?")) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
return rs.next(); // Return true if a row with the given mo_name exists
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
// Retrieve mo_content based on mo_name
static String getMoContent(Connection conn, String moName) throws SQLException {
String moContent = null;
String query = "SELECT mo_content FROM " + TABLE1_NAME + " WHERE mo_name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
moContent = rs.getString("mo_content");
}
}
}
return moContent;
}
// Get the tag name from the tag
public static String getTagName(String tag) {
// Check if the tag contains any content (anything after the space)
int spaceIndex = tag.indexOf(' ');
if (spaceIndex != -1) {
// If the tag has content, extract the tag name
return tag.substring(2, spaceIndex);
} else {
// If the tag has no content, return the entire tag without the {# and } characters
return tag.substring(2, tag.length() - 1);
}
}
static String getTagComment(Connection conn, String tagName) throws SQLException {
String tagComment = null;
String query = "SELECT tag_comment FROM " + TABLE2_NAME + " WHERE mo_tags = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, tagName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
tagComment = rs.getString("tag_comment");
}
}
}
return tagComment;
}
public static List<String> extractTags(String moContent) {
List<String> tags = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{#(.*?)}");
Matcher matcher = pattern.matcher(moContent);
while (matcher.find()) {
tags.add(matcher.group());
}
return tags;
}
// Other methods for database operations, e.g., retrieving mo_content, tags, tag comments, etc.
}

View file

@ -0,0 +1,399 @@
package com.tagger;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.net.URI;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;
public class TagReplacementToolView {
JFrame mainFrame;
private JComboBox<String> moNameComboBox;
JTextArea outputArea;
public TagReplacementToolView() {
createAndShowGUI();
}
private void createAndShowGUI() {
mainFrame = new JFrame("Tag Replacement Tool");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new BorderLayout());
createToolBar();
createInputPanel();
createOutputPanel();
mainFrame.pack();
mainFrame.setLocationRelativeTo(null); // Center the window
mainFrame.setVisible(true);
}
private void createToolBar() {
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JButton openButton = new JButton("Open URL");
JButton saveButton = new JButton("Save");
JButton loadButton = new JButton("Load");
JButton refreshButton = new JButton("Refresh");
toolBar.add(openButton);
toolBar.add(saveButton);
toolBar.add(loadButton);
toolBar.add(refreshButton);
JButton helpButton = new JButton("Help");
toolBar.add(Box.createHorizontalGlue());
toolBar.add(helpButton);
JButton aboutButton = new JButton("About");
toolBar.add(aboutButton);
// Add action listeners for the buttons here if needed
mainFrame.add(toolBar, BorderLayout.NORTH);
helpButton.addActionListener(e -> showHelpDialog()); // Help button action
aboutButton.addActionListener(e -> showAboutDialog());// About button action
openButton.addActionListener(e -> openWebsite("https://google.com")); //Open button action
saveButton.addActionListener(e -> saveData()); // Add ActionListener to the "Save" button
loadButton.addActionListener(e -> loadData()); // Add ActionListener to the "Load" button
refreshButton.addActionListener(e -> refreshData());
}
private void refreshData() {
// Update the JComboBox with fresh data from the database
moNameComboBox.removeAllItems();
String[] moNames = TagReplacementToolModel.getMoNames();
for (String moName : moNames) {
outputArea.setText("Refreshing..");
moNameComboBox.addItem(moName);
}
// Clear the output area
outputArea.setText("");
}
private void saveData() {
try {
// Get the current state of the application data
String moName = Objects.requireNonNull(moNameComboBox.getSelectedItem()).toString();
String moContent = outputArea.getText();
// Choose the save file location using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showSaveDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (!selectedFile.getAbsolutePath().toLowerCase().endsWith(".trt")) {
selectedFile = new File(selectedFile.getAbsolutePath() + ".trt");
}
if (selectedFile.exists()) {
// File already exists, ask for confirmation to overwrite
int overwriteConfirmation = JOptionPane.showConfirmDialog(mainFrame,
"The selected file already exists. Do you want to overwrite it?",
"File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (overwriteConfirmation == JOptionPane.NO_OPTION) {
// User chose not to overwrite, return without saving
return;
}
}
// Write the data to the selected file in custom save file format
try (PrintWriter writer = new PrintWriter(selectedFile)) {
writer.println("MO_NAME:" + moName);
writer.println("MO_CONTENT:");
writer.println(moContent);
writer.flush();
}
JOptionPane.showMessageDialog(mainFrame, "Data saved successfully!",
"Save", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while saving the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void loadData() {
try {
// Choose the file to load data from using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showOpenDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
// Read the data from the selected file in custom save file format
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
StringBuilder moContentBuilder = new StringBuilder();
String line;
boolean readingMoContent = false;
while ((line = reader.readLine()) != null) {
if (line.startsWith("MO_NAME:")) {
moNameComboBox.setSelectedItem(line.substring(8));
} else if (line.startsWith("MO_CONTENT:")) {
readingMoContent = true;
} else if (readingMoContent) {
moContentBuilder.append(line).append("\n");
}
}
// Set the loaded MO content to the output area
outputArea.setText(moContentBuilder.toString());
JOptionPane.showMessageDialog(mainFrame, "Data loaded successfully!",
"Load", JOptionPane.INFORMATION_MESSAGE);
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while loading the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// Custom file filter for ".trt" files
private static class TRTFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getName().toLowerCase().endsWith(".trt");
}
public String getDescription() {
return "Tag Replacement Tool Files (*.trt)";
}
}
private void openWebsite(String url) {
try {
// Use Desktop to open the default web browser
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI(url));
} else {
JOptionPane.showMessageDialog(mainFrame, "Opening the default web browser is not supported on this platform.",
"Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while trying to open the website.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private static void showHelpDialog() {
JOptionPane.showMessageDialog(null,
"Help content goes here.",
"Help",
JOptionPane.INFORMATION_MESSAGE);
}
private static void showAboutDialog() {
JOptionPane.showMessageDialog(null,
"Tag Replacement Tool\nVersion 1.0\nAuthor: Amit Kumar Nandi",
"About",
JOptionPane.INFORMATION_MESSAGE);
}
private void createInputPanel() {
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel moNameLabel = new JLabel("Select mo_name:");
moNameComboBox = new JComboBox<>(TagReplacementToolModel.getMoNames());
moNameComboBox.setEditable(true);
JButton processButton = new JButton("Process");
inputPanel.add(moNameLabel);
inputPanel.add(moNameComboBox);
inputPanel.add(processButton);
// Add action listener for the "Process" button
processButton.addActionListener(e -> processMoContent());
mainFrame.add(inputPanel, BorderLayout.CENTER);
}
private void processMoContent() {
String moName = getSelectedMoName();
StringBuilder resultBuilder = new StringBuilder();
// Check if the selected mo name exists in the database
if (!TagReplacementToolModel.isMoNameExists(moName)) {
JOptionPane.showMessageDialog(mainFrame, "The selected mo_name does not exist in the database.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
try (Connection conn = DriverManager.getConnection(TagReplacementToolModel.DB_URL, TagReplacementToolModel.USER, TagReplacementToolModel.PASS)) {
TagReplacementToolModel.createTables(conn);
String moContent = TagReplacementToolModel.getMoContent(conn, moName);
List<String> tags = TagReplacementToolModel.extractTags(moContent);
for (String tag : tags) {
String tagName = TagReplacementToolModel.getTagName(tag);
String tagComment = null;
try {
tagComment = TagReplacementToolModel.getTagComment(conn, tagName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resultBuilder.append("Mo Name: ").append(moName).append("\n");
resultBuilder.append("Tag Name: ").append(tagName).append("\n");
resultBuilder.append("Tag Comment: ").append(tagComment).append("\n");
String replacementText = showInputDialogWithInfo("Enter replacement text for the tag '" + tagName + "':",
moName, tagName, tagComment);
if (replacementText.equals("__ABORT__")) {
break; // Abort tag replacement for this mo_name
}
moContent = moContent.replace(tag, replacementText);
}
showFinalContentWindow(moContent);
outputArea.setText(resultBuilder.toString());
} catch (SQLException se) {
se.printStackTrace();
}
}
private void createOutputPanel() {
outputArea = new JTextArea(20, 50);
outputArea.setEditable(false);
outputArea.setFont(new Font("Monospaced", Font.BOLD, 14));
JScrollPane outputScrollPane = new JScrollPane(outputArea);
mainFrame.add(outputScrollPane, BorderLayout.SOUTH);
}
public void setMoNames(String[] moNames) {
moNameComboBox.setModel(new DefaultComboBoxModel<>(moNames));
}
public String getSelectedMoName() {
return Objects.requireNonNull(moNameComboBox.getSelectedItem()).toString();
}
// Implement the custom dialog logic here
static String showInputDialogWithInfo(String message, String moName, String tagName, String tagComment) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Mo Name: " + moName));
panel.add(new JLabel("Tag Name: " + tagName));
panel.add(new JLabel("\nTag Comments: "));
JTextArea commentArea = new JTextArea(tagComment);
commentArea.setEditable(false);
JScrollPane commentScrollPane = new JScrollPane(commentArea);
panel.add(commentScrollPane);
panel.add(new JLabel("\n\nReplacement: "));
JTextField textField = new JTextField(20);
panel.add(textField);
JButton abortButton = new JButton("Abort");
panel.add(abortButton);
int result = JOptionPane.showOptionDialog(null, panel, message, JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
return textField.getText();
} else if (result == JOptionPane.CANCEL_OPTION) {
// Return a special value to indicate "Abort" button was clicked
return "__ABORT__";
} else {
return "";
}
}
// Implement the final content window logic here
static void showFinalContentWindow(String moContent) {
JFrame finalContentFrame = new JFrame("Final Content");
finalContentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
finalContentFrame.setLayout(new BorderLayout());
// Final content panel
JTextArea finalContentArea = new JTextArea(moContent);
finalContentArea.setFont(new Font("Monospaced", Font.BOLD, 14));
finalContentArea.setEditable(true);
JScrollPane finalContentScrollPane = new JScrollPane(finalContentArea);
// Add a popup menu to the final content area
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem editItem = new JMenuItem("Edit");
popupMenu.add(copyItem);
popupMenu.add(editItem);
finalContentArea.setComponentPopupMenu(popupMenu);
// "Copy" action to copy the content to the clipboard
copyItem.addActionListener(e -> {
StringSelection selection = new StringSelection(finalContentArea.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
});
// "Edit" action to enable editing of the content
editItem.addActionListener(e -> finalContentArea.setEditable(true));
// Disable editing when the popup menu is closed
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
finalContentArea.setEditable(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// Do nothing
}
});
finalContentFrame.add(finalContentScrollPane, BorderLayout.CENTER);
finalContentFrame.setPreferredSize(new Dimension(800, 600));
finalContentFrame.pack();
// Center the final content window on the screen
finalContentFrame.setLocationRelativeTo(null);
finalContentFrame.setVisible(true);
}
static void showSQLErrorMessage(Exception e)
{
JOptionPane.showMessageDialog(null,
"Error connecting to the database: " + e.getMessage(),
"Database Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
// Other methods for handling GUI components, events, and dialogs
}

View file

@ -0,0 +1,265 @@
package com.tagger.console;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class Driver {
// JDBC URL, database credentials, and table names
static final String DB_URL = "jdbc:mysql://localhost/mydb";
static final String USER = "root";
static final String PASS = "";
static final String TABLE1_NAME = "table1";
static final String TABLE2_NAME = "table2";
public static void main(String[] args) {
createGUI();
}
private static void createGUI() {
JFrame frame = new JFrame("Tag Replacement Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// Input panel
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel moNameLabel = new JLabel("Enter mo_name:");
JTextField moNameField = new JTextField(15);
JButton processButton = new JButton("Process");
inputPanel.add(moNameLabel);
inputPanel.add(moNameField);
inputPanel.add(processButton);
// Output panel
JTextArea outputArea = new JTextArea(20, 50);
outputArea.setEditable(false);
outputArea.setFont(new Font("Monospaced", Font.BOLD, 14));
JScrollPane outputScrollPane = new JScrollPane(outputArea);
frame.add(inputPanel, BorderLayout.NORTH);
frame.add(outputScrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
// Button action listener
processButton.addActionListener(e -> {
String moName = moNameField.getText();
String result = processMoContent(moName);
outputArea.setText(result);
});
}
private static String processMoContent(String moName) {
StringBuilder resultBuilder = new StringBuilder();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
// Create the tables if they don't exist
createTables(conn);
// Retrieve mo_content based on mo_name
String moContent = getMoContent(conn, moName);
// Get the tags for the given mo_name and store them in a collection
List<String> tags = extractTags(moContent);
// Process and replace tags in mo_content
for (String tag : tags) {
String tagName = getTagName(tag);
String tagComment = getTagComment(conn, tagName);
resultBuilder.append("Mo Name: ").append(moName).append("\n");
resultBuilder.append("Tag Name: ").append(tagName).append("\n");
resultBuilder.append("Tag Comment: ").append(tagComment).append("\n");
// Get user input for the replacement text using a custom dialog
String replacementText = showInputDialogWithInfo("Enter replacement text for the tag '" + tagName + "':",
moName, tagName, tagComment);
// Replace the tag with the user's input
moContent = moContent.replace(tag, replacementText);
}
// Display the final content in a separate window
showFinalContentWindow(moContent);
} catch (SQLException se) {
se.printStackTrace();
}
return resultBuilder.toString();
}
// Custom dialog to show tag information along with input field
private static String showInputDialogWithInfo(String message, String moName, String tagName, String tagComment) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Mo Name: " + moName));
panel.add(new JLabel("Tag Name: " + tagName));
panel.add(new JLabel("\nTag Comments: "));
JTextArea commentArea = new JTextArea(tagComment);
commentArea.setEditable(false);
JScrollPane commentScrollPane = new JScrollPane(commentArea);
panel.add(commentScrollPane);
panel.add(new JLabel("\n\nReplacement: "));
JTextField textField = new JTextField(20);
panel.add(textField);
int result = JOptionPane.showOptionDialog(null, panel, message, JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
return (result == JOptionPane.OK_OPTION) ? textField.getText() : "";
}
private static void showFinalContentWindow(String moContent) {
JFrame finalContentFrame = new JFrame("Final Content");
finalContentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
finalContentFrame.setLayout(new BorderLayout());
// Final content panel
JTextArea finalContentArea = new JTextArea(moContent);
finalContentArea.setFont(new Font("Monospaced", Font.BOLD, 14));
finalContentArea.setEditable(true);
JScrollPane finalContentScrollPane = new JScrollPane(finalContentArea);
// Add a popup menu to the final content area
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem editItem = new JMenuItem("Edit");
popupMenu.add(copyItem);
popupMenu.add(editItem);
finalContentArea.setComponentPopupMenu(popupMenu);
// "Copy" action to copy the content to the clipboard
copyItem.addActionListener(e -> {
StringSelection selection = new StringSelection(finalContentArea.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
});
// "Edit" action to enable editing of the content
editItem.addActionListener(e -> finalContentArea.setEditable(true));
// Disable editing when the popup menu is closed
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
finalContentArea.setEditable(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// Do nothing
}
});
finalContentFrame.add(finalContentScrollPane, BorderLayout.CENTER);
finalContentFrame.setPreferredSize(new Dimension(800, 600));
finalContentFrame.pack();
// Center the final content window on the screen
finalContentFrame.setLocationRelativeTo(null);
finalContentFrame.setVisible(true);
}
// Rest of the code remains unchanged
// ...
// ...
// Create the tables if they don't exist
private static void createTables(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String createTable1Query = "CREATE TABLE IF NOT EXISTS " + TABLE1_NAME + " (" +
"mo_name TEXT PRIMARY KEY, " +
"mo_content TEXT, " +
"mo_tags TEXT)";
stmt.execute(createTable1Query);
String createTable2Query = "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + " (" +
"mo_tags TEXT PRIMARY KEY, " +
"tag_comment TEXT)";
stmt.execute(createTable2Query);
}
}
// Retrieve mo_content based on mo_name
private static String getMoContent(Connection conn, String moName) throws SQLException {
String moContent = null;
String query = "SELECT mo_content FROM " + TABLE1_NAME + " WHERE mo_name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
moContent = rs.getString("mo_content");
}
}
}
return moContent;
}
// Extract tags from mo_content
private static List<String> extractTags(String moContent) {
List<String> tags = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{#(.*?)\\}");
Matcher matcher = pattern.matcher(moContent);
while (matcher.find()) {
tags.add(matcher.group());
}
return tags;
}
// Get the tag name from the tag
private static String getTagName(String tag) {
// Assuming the tag format is {#tagname this is a tag}
int start = tag.indexOf('#') + 1;
int end = tag.indexOf(' ', start);
return tag.substring(start, end);
}
// Get tag comment from table2
private static String getTagComment(Connection conn, String tagName) throws SQLException {
String tagComment = null;
String query = "SELECT tag_comment FROM " + TABLE2_NAME + " WHERE mo_tags = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, tagName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
tagComment = rs.getString("tag_comment");
}
}
}
return tagComment;
}
}

View file

@ -0,0 +1,339 @@
package com.tagger.console;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Date;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class Driverv2 {
static final String DB_NAME = "mydb";
// JDBC URL, database credentials, and table names
static final String DB_URL = "jdbc:mysql://localhost/"+DB_NAME;
static final String USER = "root";
static final String PASS = "";
static final String TABLE1_NAME = "table1";
static final String TABLE2_NAME = "table2";
public static void main(String[] args) {
createGUI();
}
private static void createGUI() {
JFrame frame = new JFrame("Tag Replacement Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// Create the toolbar
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
// File section in the toolbar
JButton openButton = new JButton("Open");
JButton saveButton = new JButton("Save");
toolBar.add(openButton);
toolBar.add(saveButton);
// Help section in the toolbar
JButton helpButton = new JButton("Help");
toolBar.add(Box.createHorizontalGlue());
toolBar.add(helpButton);
// About section in the toolbar
JButton aboutButton = new JButton("About");
toolBar.add(aboutButton);
// Input panel
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel moNameLabel = new JLabel("Select mo_name:");
JComboBox<String> moNameComboBox = new JComboBox<>(getMoNames());
moNameComboBox.setEditable(true); // Allow custom text input
JButton processButton = new JButton("Process");
inputPanel.add(moNameLabel);
inputPanel.add(moNameComboBox);
inputPanel.add(processButton);
// Output panel
JTextArea outputArea = new JTextArea(20, 50);
outputArea.setEditable(false);
outputArea.setFont(new Font("Monospaced", Font.BOLD, 14));
JScrollPane outputScrollPane = new JScrollPane(outputArea);
frame.add(toolBar, BorderLayout.NORTH);
frame.add(inputPanel, BorderLayout.CENTER);
frame.add(outputScrollPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
// Button action listener
processButton.addActionListener(e -> {
String moName = Objects.requireNonNull(moNameComboBox.getSelectedItem()).toString();
String result = processMoContent(moName);
outputArea.setText(result);
});
// Help button action
helpButton.addActionListener(e -> showHelpDialog());
// About button action
aboutButton.addActionListener(e -> showAboutDialog());
}
private static void showHelpDialog() {
JOptionPane.showMessageDialog(null,
"Help content goes here.",
"Help",
JOptionPane.INFORMATION_MESSAGE);
}
private static void showAboutDialog() {
JOptionPane.showMessageDialog(null,
"Tag Replacement Tool\nVersion 1.0\nAuthor: Your Name",
"About",
JOptionPane.INFORMATION_MESSAGE);
}
private static String[] getMoNames() {
List<String> moNameList = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mo_name FROM " + TABLE1_NAME)) {
while (rs.next()) {
moNameList.add(rs.getString("mo_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return moNameList.toArray(new String[0]);
}
private static String processMoContent(String moName) {
StringBuilder resultBuilder = new StringBuilder();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
// Create the tables if they don't exist
createTables(conn);
// Retrieve mo_content based on mo_name
String moContent = getMoContent(conn, moName);
// Get the tags for the given mo_name and store them in a collection
List<String> tags = extractTags(moContent);
// Process and replace tags in mo_content
for (String tag : tags) {
String tagName = getTagName(tag);
String tagComment = getTagComment(conn, tagName);
resultBuilder.append("Mo Name: ").append(moName).append("\n");
resultBuilder.append("Tag Name: ").append(tagName).append("\n");
resultBuilder.append("Tag Comment: ").append(tagComment).append("\n");
// Get user input for the replacement text using a custom dialog
String replacementText = showInputDialogWithInfo("Enter replacement text for the tag '" + tagName + "':",
moName, tagName, tagComment);
// Replace the tag with the user's input
moContent = moContent.replace(tag, replacementText);
}
// Display the final content in a separate window
showFinalContentWindow(moContent);
} catch (SQLException se) {
se.printStackTrace();
}
return resultBuilder.toString();
}
// Custom dialog to show tag information along with input field
private static String showInputDialogWithInfo(String message, String moName, String tagName, String tagComment) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Mo Name: " + moName));
panel.add(new JLabel("Tag Name: " + tagName));
panel.add(new JLabel("\nTag Comments: "));
JTextArea commentArea = new JTextArea(tagComment);
commentArea.setEditable(false);
JScrollPane commentScrollPane = new JScrollPane(commentArea);
panel.add(commentScrollPane);
panel.add(new JLabel("\n\nReplacement: "));
JTextField textField = new JTextField(20);
panel.add(textField);
JButton abortButton = new JButton("Abort");
panel.add(abortButton);
int result = JOptionPane.showOptionDialog(null, panel, message, JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
return textField.getText();
} else if (result == JOptionPane.CANCEL_OPTION) {
// Return a special value to indicate "Abort" button was clicked
return "__ABORT__";
} else {
return "";
}
}
private static void showFinalContentWindow(String moContent) {
JFrame finalContentFrame = new JFrame("Final Content");
finalContentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
finalContentFrame.setLayout(new BorderLayout());
// Final content panel
JTextArea finalContentArea = new JTextArea(moContent);
finalContentArea.setFont(new Font("Monospaced", Font.BOLD, 14));
finalContentArea.setEditable(true);
JScrollPane finalContentScrollPane = new JScrollPane(finalContentArea);
// Add a popup menu to the final content area
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem editItem = new JMenuItem("Edit");
popupMenu.add(copyItem);
popupMenu.add(editItem);
finalContentArea.setComponentPopupMenu(popupMenu);
// "Copy" action to copy the content to the clipboard
copyItem.addActionListener(e -> {
StringSelection selection = new StringSelection(finalContentArea.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
});
// "Edit" action to enable editing of the content
editItem.addActionListener(e -> finalContentArea.setEditable(true));
// Disable editing when the popup menu is closed
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
finalContentArea.setEditable(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// Do nothing
}
});
finalContentFrame.add(finalContentScrollPane, BorderLayout.CENTER);
finalContentFrame.setPreferredSize(new Dimension(800, 600));
finalContentFrame.pack();
// Center the final content window on the screen
finalContentFrame.setLocationRelativeTo(null);
finalContentFrame.setVisible(true);
}
// Rest of the code remains unchanged
// ...
// ...
// Create the tables if they don't exist
private static void createTables(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String createTable1Query = "CREATE TABLE IF NOT EXISTS " + TABLE1_NAME + " (" +
"mo_name TEXT PRIMARY KEY, " +
"mo_content TEXT, " +
"mo_tags TEXT)";
stmt.execute(createTable1Query);
String createTable2Query = "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + " (" +
"mo_tags TEXT PRIMARY KEY, " +
"tag_comment TEXT)";
stmt.execute(createTable2Query);
}
}
// Retrieve mo_content based on mo_name
private static String getMoContent(Connection conn, String moName) throws SQLException {
String moContent = null;
String query = "SELECT mo_content FROM " + TABLE1_NAME + " WHERE mo_name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
moContent = rs.getString("mo_content");
}
}
}
return moContent;
}
// Extract tags from mo_content
private static List<String> extractTags(String moContent) {
List<String> tags = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{#(.*?)\\}");
Matcher matcher = pattern.matcher(moContent);
while (matcher.find()) {
tags.add(matcher.group());
}
return tags;
}
// Get the tag name from the tag
private static String getTagName(String tag) {
// Assuming the tag format is {#tagname this is a tag}
int start = tag.indexOf('#') + 1;
int end = tag.indexOf(' ', start);
return tag.substring(start, end);
}
// Get tag comment from table2
private static String getTagComment(Connection conn, String tagName) throws SQLException {
String tagComment = null;
String query = "SELECT tag_comment FROM " + TABLE2_NAME + " WHERE mo_tags = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, tagName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
tagComment = rs.getString("tag_comment");
}
}
}
return tagComment;
}
}

View file

@ -0,0 +1,316 @@
package com.tagger.console;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagReplacementTool {
static final String DB_NAME = "mydb";
// JDBC URL, database credentials, and table names
static final String DB_URL = "jdbc:mysql://localhost/"+DB_NAME;
private static final String USER = "root";
private static final String PASS = "";
private static final String TABLE1_NAME = "table1";
private static final String TABLE2_NAME = "table2";
private JFrame mainFrame;
private JComboBox<String> moNameComboBox;
private JTextArea outputArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TagReplacementTool tool = new TagReplacementTool();
tool.createAndShowGUI();
});
}
private void createAndShowGUI() {
mainFrame = new JFrame("Tag Replacement Tool");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new BorderLayout());
createToolBar();
createInputPanel();
createOutputPanel();
mainFrame.pack();
mainFrame.setLocationRelativeTo(null); // Center the window
mainFrame.setVisible(true);
}
private void createToolBar() {
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JButton openButton = new JButton("Open");
JButton saveButton = new JButton("Save");
toolBar.add(openButton);
toolBar.add(saveButton);
JButton helpButton = new JButton("Help");
toolBar.add(Box.createHorizontalGlue());
toolBar.add(helpButton);
JButton aboutButton = new JButton("About");
toolBar.add(aboutButton);
// Add action listeners for the buttons here if needed
mainFrame.add(toolBar, BorderLayout.NORTH);
// Help button action
helpButton.addActionListener(e -> showHelpDialog());
// About button action
aboutButton.addActionListener(e -> showAboutDialog());
}
private static void showHelpDialog() {
JOptionPane.showMessageDialog(null,
"Help content goes here.",
"Help",
JOptionPane.INFORMATION_MESSAGE);
}
private static void showAboutDialog() {
JOptionPane.showMessageDialog(null,
"Tag Replacement Tool\nVersion 1.0\nAuthor: Your Name",
"About",
JOptionPane.INFORMATION_MESSAGE);
}
private void createInputPanel() {
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel moNameLabel = new JLabel("Select mo_name:");
moNameComboBox = new JComboBox<>(getMoNames());
moNameComboBox.setEditable(true);
JButton processButton = new JButton("Process");
inputPanel.add(moNameLabel);
inputPanel.add(moNameComboBox);
inputPanel.add(processButton);
// Add action listener for the "Process" button
processButton.addActionListener(e -> processMoContent());
mainFrame.add(inputPanel, BorderLayout.CENTER);
}
private void createOutputPanel() {
outputArea = new JTextArea(20, 50);
outputArea.setEditable(false);
outputArea.setFont(new Font("Monospaced", Font.BOLD, 14));
JScrollPane outputScrollPane = new JScrollPane(outputArea);
mainFrame.add(outputScrollPane, BorderLayout.SOUTH);
}
private String[] getMoNames() {
List<String> moNameList = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mo_name FROM " + TABLE1_NAME)) {
while (rs.next()) {
moNameList.add(rs.getString("mo_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return moNameList.toArray(new String[0]);
}
private void processMoContent() {
String moName = moNameComboBox.getSelectedItem().toString();
StringBuilder resultBuilder = new StringBuilder();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
createTables(conn);
String moContent = getMoContent(conn, moName);
List<String> tags = extractTags(moContent);
for (String tag : tags) {
String tagName = getTagName(tag);
String tagComment = getTagComment(conn, tagName);
resultBuilder.append("Mo Name: ").append(moName).append("\n");
resultBuilder.append("Tag Name: ").append(tagName).append("\n");
resultBuilder.append("Tag Comment: ").append(tagComment).append("\n");
String replacementText = showInputDialogWithInfo("Enter replacement text for the tag '" + tagName + "':",
moName, tagName, tagComment);
if (replacementText.equals("__ABORT__")) {
break; // Abort tag replacement for this mo_name
}
moContent = moContent.replace(tag, replacementText);
}
showFinalContentWindow(moContent);
outputArea.setText(resultBuilder.toString());
} catch (SQLException se) {
se.printStackTrace();
}
}
// Implement the custom dialog logic here
private static String showInputDialogWithInfo(String message, String moName, String tagName, String tagComment) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Mo Name: " + moName));
panel.add(new JLabel("Tag Name: " + tagName));
panel.add(new JLabel("\nTag Comments: "));
JTextArea commentArea = new JTextArea(tagComment);
commentArea.setEditable(false);
JScrollPane commentScrollPane = new JScrollPane(commentArea);
panel.add(commentScrollPane);
panel.add(new JLabel("\n\nReplacement: "));
JTextField textField = new JTextField(20);
panel.add(textField);
JButton abortButton = new JButton("Abort");
panel.add(abortButton);
int result = JOptionPane.showOptionDialog(null, panel, message, JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
return textField.getText();
} else if (result == JOptionPane.CANCEL_OPTION) {
// Return a special value to indicate "Abort" button was clicked
return "__ABORT__";
} else {
return "";
}
}
// Implement the final content window logic here
private static void showFinalContentWindow(String moContent) {
JFrame finalContentFrame = new JFrame("Final Content");
finalContentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
finalContentFrame.setLayout(new BorderLayout());
// Final content panel
JTextArea finalContentArea = new JTextArea(moContent);
finalContentArea.setFont(new Font("Monospaced", Font.BOLD, 14));
finalContentArea.setEditable(true);
JScrollPane finalContentScrollPane = new JScrollPane(finalContentArea);
// Add a popup menu to the final content area
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem editItem = new JMenuItem("Edit");
popupMenu.add(copyItem);
popupMenu.add(editItem);
finalContentArea.setComponentPopupMenu(popupMenu);
// "Copy" action to copy the content to the clipboard
copyItem.addActionListener(e -> {
StringSelection selection = new StringSelection(finalContentArea.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
});
// "Edit" action to enable editing of the content
editItem.addActionListener(e -> finalContentArea.setEditable(true));
// Disable editing when the popup menu is closed
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
finalContentArea.setEditable(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// Do nothing
}
});
finalContentFrame.add(finalContentScrollPane, BorderLayout.CENTER);
finalContentFrame.setPreferredSize(new Dimension(800, 600));
finalContentFrame.pack();
// Center the final content window on the screen
finalContentFrame.setLocationRelativeTo(null);
finalContentFrame.setVisible(true);
}
// Create the tables if they don't exist
private static void createTables(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String createTable1Query = "CREATE TABLE IF NOT EXISTS " + TABLE1_NAME + " (" +
"mo_name TEXT PRIMARY KEY, " +
"mo_content TEXT, " +
"mo_tags TEXT)";
stmt.execute(createTable1Query);
String createTable2Query = "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + " (" +
"mo_tags TEXT PRIMARY KEY, " +
"tag_comment TEXT)";
stmt.execute(createTable2Query);
}
}
// Retrieve mo_content based on mo_name
private static String getMoContent(Connection conn, String moName) throws SQLException {
String moContent = null;
String query = "SELECT mo_content FROM " + TABLE1_NAME + " WHERE mo_name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
moContent = rs.getString("mo_content");
}
}
}
return moContent;
}
// Extract tags from mo_content
private static List<String> extractTags(String moContent) {
List<String> tags = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{#(.*?)\\}");
Matcher matcher = pattern.matcher(moContent);
while (matcher.find()) {
tags.add(matcher.group());
}
return tags;
}
// Get the tag name from the tag
private static String getTagName(String tag) {
// Assuming the tag format is {#tagname this is a tag}
int start = tag.indexOf('#') + 1;
int end = tag.indexOf(' ', start);
return tag.substring(start, end);
}
private static String getTagComment(Connection conn, String tagName) throws SQLException {
String tagComment = null;
String query = "SELECT tag_comment FROM " + TABLE2_NAME + " WHERE mo_tags = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, tagName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
tagComment = rs.getString("tag_comment");
}
}
}
return tagComment;
}
}

View file

@ -0,0 +1,473 @@
package com.tagger.console;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.net.URI;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagReplacementToolv2 {
static final String DB_NAME = "mydb";
// JDBC URL, database credentials, and table names
static final String DB_URL = "jdbc:mysql://localhost/"+DB_NAME;
private static final String USER = "root";
private static final String PASS = "";
private static final String TABLE1_NAME = "table1";
private static final String TABLE2_NAME = "table2";
private JFrame mainFrame;
private JComboBox<String> moNameComboBox;
private JTextArea outputArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TagReplacementToolv2 tool = new TagReplacementToolv2();
tool.createAndShowGUI();
});
}
void createAndShowGUI() {
mainFrame = new JFrame("Tag Replacement Tool");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new BorderLayout());
createToolBar();
createInputPanel();
createOutputPanel();
mainFrame.pack();
mainFrame.setLocationRelativeTo(null); // Center the window
mainFrame.setVisible(true);
}
private void createToolBar() {
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JButton openButton = new JButton("Open");
JButton saveButton = new JButton("Save");
JButton loadButton = new JButton("Load");
toolBar.add(openButton);
toolBar.add(saveButton);
toolBar.add(loadButton);
JButton helpButton = new JButton("Help");
toolBar.add(Box.createHorizontalGlue());
toolBar.add(helpButton);
JButton aboutButton = new JButton("About");
toolBar.add(aboutButton);
// Add action listeners for the buttons here if needed
mainFrame.add(toolBar, BorderLayout.NORTH);
// Help button action
helpButton.addActionListener(e -> showHelpDialog());
// About button action
aboutButton.addActionListener(e -> showAboutDialog());
//Open button action
openButton.addActionListener(e -> openWebsite("https://google.com")); // Replace with your desired URL
saveButton.addActionListener(e -> saveData());
saveButton.addActionListener(e -> saveData());
// Add ActionListener to the "Load" button
loadButton.addActionListener(e -> loadData());
}
private static void showHelpDialog() {
JOptionPane.showMessageDialog(null,
"Help content goes here.",
"Help",
JOptionPane.INFORMATION_MESSAGE);
}
private static void showAboutDialog() {
JOptionPane.showMessageDialog(null,
"Tag Replacement Tool\nVersion 1.0\nAuthor: Your Name",
"About",
JOptionPane.INFORMATION_MESSAGE);
}
private void createInputPanel() {
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel moNameLabel = new JLabel("Select mo_name:");
moNameComboBox = new JComboBox<>(getMoNames());
moNameComboBox.setEditable(true);
JButton processButton = new JButton("Process");
inputPanel.add(moNameLabel);
inputPanel.add(moNameComboBox);
inputPanel.add(processButton);
// Add action listener for the "Process" button
processButton.addActionListener(e -> processMoContent());
mainFrame.add(inputPanel, BorderLayout.CENTER);
}
private void createOutputPanel() {
outputArea = new JTextArea(20, 50);
outputArea.setEditable(false);
outputArea.setFont(new Font("Monospaced", Font.BOLD, 14));
JScrollPane outputScrollPane = new JScrollPane(outputArea);
mainFrame.add(outputScrollPane, BorderLayout.SOUTH);
}
private String[] getMoNames() {
List<String> moNameList = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mo_name FROM " + TABLE1_NAME)) {
while (rs.next()) {
moNameList.add(rs.getString("mo_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return moNameList.toArray(new String[0]);
}
private void processMoContent() {
String moName = moNameComboBox.getSelectedItem().toString();
StringBuilder resultBuilder = new StringBuilder();
// Check if the selected mo name exists in the database
if (!isMoNameExists(moName)) {
JOptionPane.showMessageDialog(mainFrame, "The selected mo_name does not exist in the database.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
createTables(conn);
String moContent = getMoContent(conn, moName);
List<String> tags = extractTags(moContent);
for (String tag : tags) {
String tagName = getTagName(tag);
String tagComment = getTagComment(conn, tagName);
resultBuilder.append("Mo Name: ").append(moName).append("\n");
resultBuilder.append("Tag Name: ").append(tagName).append("\n");
resultBuilder.append("Tag Comment: ").append(tagComment).append("\n");
String replacementText = showInputDialogWithInfo("Enter replacement text for the tag '" + tagName + "':",
moName, tagName, tagComment);
if (replacementText.equals("__ABORT__")) {
break; // Abort tag replacement for this mo_name
}
moContent = moContent.replace(tag, replacementText);
}
showFinalContentWindow(moContent);
outputArea.setText(resultBuilder.toString());
} catch (SQLException se) {
se.printStackTrace();
}
}
// Implement the custom dialog logic here
private static String showInputDialogWithInfo(String message, String moName, String tagName, String tagComment) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Mo Name: " + moName));
panel.add(new JLabel("Tag Name: " + tagName));
panel.add(new JLabel("\nTag Comments: "));
JTextArea commentArea = new JTextArea(tagComment);
commentArea.setEditable(false);
JScrollPane commentScrollPane = new JScrollPane(commentArea);
panel.add(commentScrollPane);
panel.add(new JLabel("\n\nReplacement: "));
JTextField textField = new JTextField(20);
panel.add(textField);
JButton abortButton = new JButton("Abort");
panel.add(abortButton);
int result = JOptionPane.showOptionDialog(null, panel, message, JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
return textField.getText();
} else if (result == JOptionPane.CANCEL_OPTION) {
// Return a special value to indicate "Abort" button was clicked
return "__ABORT__";
} else {
return "";
}
}
// Implement the final content window logic here
private static void showFinalContentWindow(String moContent) {
JFrame finalContentFrame = new JFrame("Final Content");
finalContentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
finalContentFrame.setLayout(new BorderLayout());
// Final content panel
JTextArea finalContentArea = new JTextArea(moContent);
finalContentArea.setFont(new Font("Monospaced", Font.BOLD, 14));
finalContentArea.setEditable(true);
JScrollPane finalContentScrollPane = new JScrollPane(finalContentArea);
// Add a popup menu to the final content area
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem editItem = new JMenuItem("Edit");
popupMenu.add(copyItem);
popupMenu.add(editItem);
finalContentArea.setComponentPopupMenu(popupMenu);
// "Copy" action to copy the content to the clipboard
copyItem.addActionListener(e -> {
StringSelection selection = new StringSelection(finalContentArea.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
});
// "Edit" action to enable editing of the content
editItem.addActionListener(e -> finalContentArea.setEditable(true));
// Disable editing when the popup menu is closed
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
finalContentArea.setEditable(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// Do nothing
}
});
finalContentFrame.add(finalContentScrollPane, BorderLayout.CENTER);
finalContentFrame.setPreferredSize(new Dimension(800, 600));
finalContentFrame.pack();
// Center the final content window on the screen
finalContentFrame.setLocationRelativeTo(null);
finalContentFrame.setVisible(true);
}
// Create the tables if they don't exist
private static void createTables(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String createTable1Query = "CREATE TABLE IF NOT EXISTS " + TABLE1_NAME + " (" +
"mo_name TEXT PRIMARY KEY, " +
"mo_content TEXT, " +
"mo_tags TEXT)";
stmt.execute(createTable1Query);
String createTable2Query = "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + " (" +
"mo_tags TEXT PRIMARY KEY, " +
"tag_comment TEXT)";
stmt.execute(createTable2Query);
}
}
// Retrieve mo_content based on mo_name
private static String getMoContent(Connection conn, String moName) throws SQLException {
String moContent = null;
String query = "SELECT mo_content FROM " + TABLE1_NAME + " WHERE mo_name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
moContent = rs.getString("mo_content");
}
}
}
return moContent;
}
// Extract tags from mo_content
private static List<String> extractTags(String moContent) {
List<String> tags = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{#(.*?)\\}");
Matcher matcher = pattern.matcher(moContent);
while (matcher.find()) {
tags.add(matcher.group());
}
return tags;
}
// Get the tag name from the tag
private static String getTagName(String tag) {
// Assuming the tag format is {#tagname this is a tag}
int start = tag.indexOf('#') + 1;
int end = tag.indexOf(' ', start);
return tag.substring(start, end);
}
private static String getTagComment(Connection conn, String tagName) throws SQLException {
String tagComment = null;
String query = "SELECT tag_comment FROM " + TABLE2_NAME + " WHERE mo_tags = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, tagName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
tagComment = rs.getString("tag_comment");
}
}
}
return tagComment;
}
private boolean isMoNameExists(String moName) {
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement("SELECT mo_name FROM " + TABLE1_NAME + " WHERE mo_name = ?")) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
return rs.next(); // Return true if a row with the given mo_name exists
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private void openWebsite(String url) {
try {
// Use Desktop to open the default web browser
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI(url));
} else {
JOptionPane.showMessageDialog(mainFrame, "Opening the default web browser is not supported on this platform.",
"Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while trying to open the website.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void saveData() {
try {
// Get the current state of the application data
String moName = Objects.requireNonNull(moNameComboBox.getSelectedItem()).toString();
String moContent = outputArea.getText();
// Choose the save file location using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showSaveDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (!selectedFile.getAbsolutePath().toLowerCase().endsWith(".trt")) {
selectedFile = new File(selectedFile.getAbsolutePath() + ".trt");
}
if (selectedFile.exists()) {
// File already exists, ask for confirmation to overwrite
int overwriteConfirmation = JOptionPane.showConfirmDialog(mainFrame,
"The selected file already exists. Do you want to overwrite it?",
"File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (overwriteConfirmation == JOptionPane.NO_OPTION) {
// User chose not to overwrite, return without saving
return;
}
}
// Write the data to the selected file in custom save file format
try (PrintWriter writer = new PrintWriter(selectedFile)) {
writer.println("MO_NAME:" + moName);
writer.println("MO_CONTENT:");
writer.println(moContent);
writer.flush();
}
JOptionPane.showMessageDialog(mainFrame, "Data saved successfully!",
"Save", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while saving the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void loadData() {
try {
// Choose the file to load data from using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showOpenDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
// Read the data from the selected file in custom save file format
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
StringBuilder moContentBuilder = new StringBuilder();
String line;
boolean readingMoContent = false;
while ((line = reader.readLine()) != null) {
if (line.startsWith("MO_NAME:")) {
moNameComboBox.setSelectedItem(line.substring(8));
} else if (line.startsWith("MO_CONTENT:")) {
readingMoContent = true;
} else if (readingMoContent) {
moContentBuilder.append(line).append("\n");
}
}
// Set the loaded MO content to the output area
outputArea.setText(moContentBuilder.toString());
JOptionPane.showMessageDialog(mainFrame, "Data loaded successfully!",
"Load", JOptionPane.INFORMATION_MESSAGE);
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while loading the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// Custom file filter for ".trt" files
private class TRTFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getName().toLowerCase().endsWith(".trt");
}
public String getDescription() {
return "Tag Replacement Tool Files (*.trt)";
}
}
}

View file

@ -0,0 +1,509 @@
package com.tagger.console;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TagReplacementToolv3 {
private static final String CONFIG_FILE_PATH = "C:\\Users\\amit\\eclipse-workspace\\Tagger\\src\\trtconfig.json";
private String DB_URL;
private String USER;
private String PASS;
private String DB_NAME;
private static String TABLE1_NAME;
private static String TABLE2_NAME;
private JFrame mainFrame;
private JComboBox<String> moNameComboBox;
private JTextArea outputArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TagReplacementToolv3 tool = new TagReplacementToolv3();
tool.loadConfig();
tool.createAndShowGUI();
});
}
private void createAndShowGUI() {
mainFrame = new JFrame("Tag Replacement Tool");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new BorderLayout());
createToolBar();
createInputPanel();
createOutputPanel();
mainFrame.pack();
mainFrame.setLocationRelativeTo(null); // Center the window
mainFrame.setVisible(true);
}
private void createToolBar() {
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JButton openButton = new JButton("Open");
JButton saveButton = new JButton("Save");
JButton loadButton = new JButton("Load");
toolBar.add(openButton);
toolBar.add(saveButton);
toolBar.add(loadButton);
JButton helpButton = new JButton("Help");
toolBar.add(Box.createHorizontalGlue());
toolBar.add(helpButton);
JButton aboutButton = new JButton("About");
toolBar.add(aboutButton);
// Add action listeners for the buttons here if needed
mainFrame.add(toolBar, BorderLayout.NORTH);
// Help button action
helpButton.addActionListener(e -> showHelpDialog());
// About button action
aboutButton.addActionListener(e -> showAboutDialog());
//Open button action
openButton.addActionListener(e -> openWebsite("https://google.com")); // Replace with your desired URL
saveButton.addActionListener(e -> saveData());
saveButton.addActionListener(e -> saveData());
// Add ActionListener to the "Load" button
loadButton.addActionListener(e -> loadData());
}
private static void showHelpDialog() {
JOptionPane.showMessageDialog(null,
"Help content goes here.",
"Help",
JOptionPane.INFORMATION_MESSAGE);
}
private static void showAboutDialog() {
JOptionPane.showMessageDialog(null,
"Tag Replacement Tool\nVersion 1.0\nAuthor: Your Name",
"About",
JOptionPane.INFORMATION_MESSAGE);
}
private void createInputPanel() {
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel moNameLabel = new JLabel("Select mo_name:");
moNameComboBox = new JComboBox<>(getMoNames());
moNameComboBox.setEditable(true);
JButton processButton = new JButton("Process");
inputPanel.add(moNameLabel);
inputPanel.add(moNameComboBox);
inputPanel.add(processButton);
// Add action listener for the "Process" button
processButton.addActionListener(e -> processMoContent());
mainFrame.add(inputPanel, BorderLayout.CENTER);
}
private void createOutputPanel() {
outputArea = new JTextArea(20, 50);
outputArea.setEditable(false);
outputArea.setFont(new Font("Monospaced", Font.BOLD, 14));
JScrollPane outputScrollPane = new JScrollPane(outputArea);
mainFrame.add(outputScrollPane, BorderLayout.SOUTH);
}
private String[] getMoNames() {
List<String> moNameList = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mo_name FROM " + TABLE1_NAME)) {
while (rs.next()) {
moNameList.add(rs.getString("mo_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return moNameList.toArray(new String[0]);
}
private void processMoContent() {
String moName = moNameComboBox.getSelectedItem().toString();
StringBuilder resultBuilder = new StringBuilder();
// Check if the selected mo name exists in the database
if (!isMoNameExists(moName)) {
JOptionPane.showMessageDialog(mainFrame, "The selected mo_name does not exist in the database.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
createTables(conn);
String moContent = getMoContent(conn, moName);
List<String> tags = extractTags(moContent);
for (String tag : tags) {
String tagName = getTagName(tag);
String tagComment = getTagComment(conn, tagName);
resultBuilder.append("Mo Name: ").append(moName).append("\n");
resultBuilder.append("Tag Name: ").append(tagName).append("\n");
resultBuilder.append("Tag Comment: ").append(tagComment).append("\n");
String replacementText = showInputDialogWithInfo("Enter replacement text for the tag '" + tagName + "':",
moName, tagName, tagComment);
if (replacementText.equals("__ABORT__")) {
break; // Abort tag replacement for this mo_name
}
moContent = moContent.replace(tag, replacementText);
}
showFinalContentWindow(moContent);
outputArea.setText(resultBuilder.toString());
} catch (SQLException se) {
se.printStackTrace();
}
}
// Implement the custom dialog logic here
private static String showInputDialogWithInfo(String message, String moName, String tagName, String tagComment) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Mo Name: " + moName));
panel.add(new JLabel("Tag Name: " + tagName));
panel.add(new JLabel("\nTag Comments: "));
JTextArea commentArea = new JTextArea(tagComment);
commentArea.setEditable(false);
JScrollPane commentScrollPane = new JScrollPane(commentArea);
panel.add(commentScrollPane);
panel.add(new JLabel("\n\nReplacement: "));
JTextField textField = new JTextField(20);
panel.add(textField);
JButton abortButton = new JButton("Abort");
panel.add(abortButton);
int result = JOptionPane.showOptionDialog(null, panel, message, JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
return textField.getText();
} else if (result == JOptionPane.CANCEL_OPTION) {
// Return a special value to indicate "Abort" button was clicked
return "__ABORT__";
} else {
return "";
}
}
// Implement the final content window logic here
private static void showFinalContentWindow(String moContent) {
JFrame finalContentFrame = new JFrame("Final Content");
finalContentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
finalContentFrame.setLayout(new BorderLayout());
// Final content panel
JTextArea finalContentArea = new JTextArea(moContent);
finalContentArea.setFont(new Font("Monospaced", Font.BOLD, 14));
finalContentArea.setEditable(true);
JScrollPane finalContentScrollPane = new JScrollPane(finalContentArea);
// Add a popup menu to the final content area
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem editItem = new JMenuItem("Edit");
popupMenu.add(copyItem);
popupMenu.add(editItem);
finalContentArea.setComponentPopupMenu(popupMenu);
// "Copy" action to copy the content to the clipboard
copyItem.addActionListener(e -> {
StringSelection selection = new StringSelection(finalContentArea.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
});
// "Edit" action to enable editing of the content
editItem.addActionListener(e -> finalContentArea.setEditable(true));
// Disable editing when the popup menu is closed
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
finalContentArea.setEditable(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// Do nothing
}
});
finalContentFrame.add(finalContentScrollPane, BorderLayout.CENTER);
finalContentFrame.setPreferredSize(new Dimension(800, 600));
finalContentFrame.pack();
// Center the final content window on the screen
finalContentFrame.setLocationRelativeTo(null);
finalContentFrame.setVisible(true);
}
// Create the tables if they don't exist
private static void createTables(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) {
String createTable1Query = "CREATE TABLE IF NOT EXISTS " + TABLE1_NAME + " (" +
"mo_name TEXT PRIMARY KEY, " +
"mo_content TEXT, " +
"mo_tags TEXT)";
stmt.execute(createTable1Query);
String createTable2Query = "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + " (" +
"mo_tags TEXT PRIMARY KEY, " +
"tag_comment TEXT)";
stmt.execute(createTable2Query);
}
}
// Retrieve mo_content based on mo_name
private static String getMoContent(Connection conn, String moName) throws SQLException {
String moContent = null;
String query = "SELECT mo_content FROM " + TABLE1_NAME + " WHERE mo_name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
moContent = rs.getString("mo_content");
}
}
}
return moContent;
}
// Extract tags from mo_content
private static List<String> extractTags(String moContent) {
List<String> tags = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{#(.*?)\\}");
Matcher matcher = pattern.matcher(moContent);
while (matcher.find()) {
tags.add(matcher.group());
}
return tags;
}
// Get the tag name from the tag
private static String getTagName(String tag) {
// Assuming the tag format is {#tagname this is a tag}
int start = tag.indexOf('#') + 1;
int end = tag.indexOf(' ', start);
return tag.substring(start, end);
}
private static String getTagComment(Connection conn, String tagName) throws SQLException {
String tagComment = null;
String query = "SELECT tag_comment FROM " + TABLE2_NAME + " WHERE mo_tags = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, tagName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
tagComment = rs.getString("tag_comment");
}
}
}
return tagComment;
}
private boolean isMoNameExists(String moName) {
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement("SELECT mo_name FROM " + TABLE1_NAME + " WHERE mo_name = ?")) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
return rs.next(); // Return true if a row with the given mo_name exists
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private void openWebsite(String url) {
try {
// Use Desktop to open the default web browser
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI(url));
} else {
JOptionPane.showMessageDialog(mainFrame, "Opening the default web browser is not supported on this platform.",
"Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while trying to open the website.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void saveData() {
try {
// Get the current state of the application data
String moName = Objects.requireNonNull(moNameComboBox.getSelectedItem()).toString();
String moContent = outputArea.getText();
// Choose the save file location using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showSaveDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (!selectedFile.getAbsolutePath().toLowerCase().endsWith(".trt")) {
selectedFile = new File(selectedFile.getAbsolutePath() + ".trt");
}
if (selectedFile.exists()) {
// File already exists, ask for confirmation to overwrite
int overwriteConfirmation = JOptionPane.showConfirmDialog(mainFrame,
"The selected file already exists. Do you want to overwrite it?",
"File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (overwriteConfirmation == JOptionPane.NO_OPTION) {
// User chose not to overwrite, return without saving
return;
}
}
// Write the data to the selected file in custom save file format
try (PrintWriter writer = new PrintWriter(selectedFile)) {
writer.println("MO_NAME:" + moName);
writer.println("MO_CONTENT:");
writer.println(moContent);
writer.flush();
}
JOptionPane.showMessageDialog(mainFrame, "Data saved successfully!",
"Save", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while saving the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void loadData() {
try {
// Choose the file to load data from using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showOpenDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
// Read the data from the selected file in custom save file format
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
StringBuilder moContentBuilder = new StringBuilder();
String line;
boolean readingMoContent = false;
while ((line = reader.readLine()) != null) {
if (line.startsWith("MO_NAME:")) {
moNameComboBox.setSelectedItem(line.substring(8));
} else if (line.startsWith("MO_CONTENT:")) {
readingMoContent = true;
} else if (readingMoContent) {
moContentBuilder.append(line).append("\n");
}
}
// Set the loaded MO content to the output area
outputArea.setText(moContentBuilder.toString());
JOptionPane.showMessageDialog(mainFrame, "Data loaded successfully!",
"Load", JOptionPane.INFORMATION_MESSAGE);
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while loading the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// Custom file filter for ".trt" files
private class TRTFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getName().toLowerCase().endsWith(".trt");
}
public String getDescription() {
return "Tag Replacement Tool Files (*.trt)";
}
}
private void loadConfig() {
try {
String configData = readFile(CONFIG_FILE_PATH);
JSONObject configJson = new JSONObject(new JSONTokener(configData));
DB_URL = configJson.getString("DB_URL");
USER = configJson.getString("USER");
PASS = configJson.getString("PASS");
DB_NAME = configJson.getString("DB_NAME");
TABLE1_NAME = configJson.getString("TABLE1_NAME");
TABLE2_NAME = configJson.getString("TABLE2_NAME");
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error loading configuration from " + CONFIG_FILE_PATH,
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private String readFile(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
}
return content.toString();
}
}

View file

@ -0,0 +1,37 @@
package com.tagger.console;
import java.security.MessageDigest;
import java.util.Date;
public class hasher {
public String createHash() throws Exception {
// Get the current timestamp
Date timestamp = new Date();
// Create a MessageDigest instance
MessageDigest md = MessageDigest.getInstance("SHA-256");
// Convert the timestamp to a byte array
byte[] bytes = timestamp.toString().getBytes();
// Calculate the hash of the timestamp
byte[] hash = md.digest(bytes);
// Convert the hash to a hexadecimal string
String hashString = bytesToHexString(hash);
return hashString;
}
private static String bytesToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
int value = bytes[i] & 0xFF;
sb.append(Integer.toHexString(value));
}
return sb.toString();
}
}

View file

@ -0,0 +1,71 @@
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 8.0.30 - MySQL Community Server - GPL
-- Server OS: Win64
-- HeidiSQL Version: 12.1.0.6537
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-- Dumping database structure for mydb
DROP DATABASE IF EXISTS `mydb`;
CREATE DATABASE IF NOT EXISTS `mydb` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mydb`;
-- Dumping structure for table mydb.table1
DROP TABLE IF EXISTS `table1`;
CREATE TABLE IF NOT EXISTS `table1` (
`mo_name` varchar(15) NOT NULL,
`mo_content` text,
`mo_tags` text,
PRIMARY KEY (`mo_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table mydb.table1: ~7 rows (approximately)
DELETE FROM `table1`;
INSERT INTO `table1` (`mo_name`, `mo_content`, `mo_tags`) VALUES
('mo_bstc', 'A registration was started online to set up an APE account.The account was activated. The seller listed {#tag_prodcat} priced {#tag_abatbe} their current market value A review of the account showed that the seller also controlled {#tag_singmul}, . {#tag_singmultt} used to place orders with the seller account.{#tag_ishnr} {#tag_isactiveall} {#tag_isactivesm} {#tag_isblocked} ', 'tag_prodcat,tag_abatbe,tag_singmul,tag_singmultt,tag_ishnr,tag_isactiveall,tag_isactivesm,tag_isblocked'),
('mo1', '{#tag1 this a tag} original mo content {#tag2 this is another tag} Some more content', 'tag1,tag2'),
('mo2', 'original mo content {#tag3 this a tag} Some more content', 'tag3'),
('mo2ss', 'original mo content {#tag3 this a tag} Some more content', 'tag3'),
('mo3', 'hi there {#tag_prodcat originalcontentss}', 'tag_prodcat'),
('mo4', 'A registration was started online to set up an APE account.\r\n\r\nThe account was activated. The seller listed {#tag_prodcat ss} priced {#tag_abatbe ss} their current market value.\r\n\r\nA review of the account showed that the seller also controlled {#tag_singmul ss}, {#tag_singmultt ss} used to place orders with the seller account.\r\n\r\n{#tag_ishnr ss} .\r\n\r\n{#tag_isactiveall ss} {#tag_isactivesm ss} {#tag_isblocked ss} .', 'tag_prodcat,tag_abatbe,tag_singmul,tag_singmultt,tag_ishnr,tag_isactiveall,tag_isactivesm,tag_isblocked'),
('mo5', 'original mo content {#tag_mytag this a tag /this,that/ notthis} Some more content', 'tag_mytag');
-- Dumping structure for table mydb.table2
DROP TABLE IF EXISTS `table2`;
CREATE TABLE IF NOT EXISTS `table2` (
`mo_tags` varchar(15) NOT NULL,
`tag_comment` text,
PRIMARY KEY (`mo_tags`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table mydb.table2: ~12 rows (approximately)
DELETE FROM `table2`;
INSERT INTO `table2` (`mo_tags`, `tag_comment`) VALUES
('tag_abatbe', 'Pricing Above / at / below'),
('tag_isactiveall', 'The APE account is active on the Amazon EU online stores'),
('tag_isactivesm', 'The APE account is active on the Amazon <marketplace names> online stores'),
('tag_isblocked', 'The APE account is currently blocked on the <Marketplace name> ONLINE STORES ONLY online store(s). '),
('tag_ishnr', 'Additionally, these items did not appear to have been sent to the related buyer [#account./accounts.#] '),
('tag_mytag', 'i am tag_mytag'),
('tag_prodcat', 'Type the Product Categries'),
('tag_singmul', '[#multiple buyer accounts/a buyer account#]'),
('tag_singmultt', '[#These buyer accounts were/This buyer account was#] '),
('tag1', 'I am tag 1'),
('tag2', 'I am tag 2'),
('tag3', 'I am tag3 ');
/*!40103 SET TIME_ZONE=IFNULL(@OLD_TIME_ZONE, 'system') */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;

View file

@ -0,0 +1,8 @@
{
"DB_URL": "jdbc:mysql://localhost/mydb",
"USER": "root",
"PASS": "",
"DB_NAME": "mydb",
"TABLE1_NAME": "table1",
"TABLE2_NAME": "table2"
}

View file

@ -0,0 +1,183 @@
package com.tagger.old;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Tagrt {
private static final String CONFIG_FILE_PATH = "C:\\Users\\amit\\eclipse-workspace\\Tagger\\src\\trtconfig.json";
private static String DB_URL;
private static String USER;
private static String PASS;
private static String TABLE1_NAME;
private static String TABLE2_NAME;
// Create the tables if they don't exist
public void createTables() {
try (Connection conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS())) {
try (Statement stmt = conn.createStatement()) {
String createTable1Query = "CREATE TABLE IF NOT EXISTS " + TABLE1_NAME + " (" +
"mo_name TEXT PRIMARY KEY, " +
"mo_content TEXT, " +
"mo_tags TEXT)";
stmt.execute(createTable1Query);
String createTable2Query = "CREATE TABLE IF NOT EXISTS " + TABLE2_NAME + " (" +
"mo_tags TEXT PRIMARY KEY, " +
"tag_comment TEXT)";
stmt.execute(createTable2Query);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// Retrieve mo_content based on mo_name
public String getMoContent(String moName) {
String moContent = null;
String query = "SELECT mo_content FROM " + TABLE1_NAME + " WHERE mo_name = ?";
try (Connection conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
moContent = rs.getString("mo_content");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return moContent;
}
// Extract tags from mo_content
public List<String> extractTags(String moContent) {
List<String> tags = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{#(.*?)\\}");
Matcher matcher = pattern.matcher(moContent);
while (matcher.find()) {
tags.add(matcher.group());
}
return tags;
}
// Get the tag name from the tag
public String getTagName(String tag) {
// Assuming the tag format is {#tagname this is a tag}
int start = tag.indexOf('#') + 1;
int end = tag.indexOf(' ', start);
return tag.substring(start, end);
}
public String getTagComment(String tagName) {
String tagComment = null;
String query = "SELECT tag_comment FROM " + TABLE2_NAME + " WHERE mo_tags = ?";
try (Connection conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, tagName);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
tagComment = rs.getString("tag_comment");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return tagComment;
}
public boolean isMoNameExists(String moName) {
try (Connection conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
PreparedStatement pstmt = conn.prepareStatement("SELECT mo_name FROM " + TABLE1_NAME + " WHERE mo_name = ?")) {
pstmt.setString(1, moName);
try (ResultSet rs = pstmt.executeQuery()) {
return rs.next(); // Return true if a row with the given mo_name exists
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
String[] getMoNames() {
List<String> moNameList = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mo_name FROM " + TABLE1_NAME)) {
while (rs.next()) {
moNameList.add(rs.getString("mo_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return moNameList.toArray(new String[0]);
}
void loadConfig() {
try {
String configData = readFile(CONFIG_FILE_PATH);
JSONObject configJson = new JSONObject(new JSONTokener(configData));
setDB_URL(configJson.getString("DB_URL"));
setUSER(configJson.getString("USER"));
setPASS(configJson.getString("PASS"));
TABLE1_NAME = configJson.getString("TABLE1_NAME");
TABLE2_NAME = configJson.getString("TABLE2_NAME");
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error loading configuration from " + CONFIG_FILE_PATH,
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private String readFile(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
}
return content.toString();
}
public static String getUSER() {
return USER;
}
public static void setUSER(String uSER) {
USER = uSER;
}
public static String getPASS() {
return PASS;
}
public static void setPASS(String pASS) {
PASS = pASS;
}
public static String getDB_URL() {
return DB_URL;
}
public static void setDB_URL(String dB_URL) {
DB_URL = dB_URL;
}
}

View file

@ -0,0 +1,410 @@
package com.tagger.old;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import org.json.JSONObject;
import org.json.JSONTokener;
public class TagrtGUI {
Tagrt tr = new Tagrt();
private JFrame mainFrame;
private JComboBox<String> moNameComboBox;
private JTextArea outputArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TagrtGUI tool = new TagrtGUI();
Tagrt tr = new Tagrt();
tr.loadConfig();
tool.createAndShowGUI();
});
}
private void createAndShowGUI() {
mainFrame = new JFrame("Tag Replacement Tool");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new BorderLayout());
createToolBar();
createInputPanel();
createOutputPanel();
mainFrame.pack();
mainFrame.setLocationRelativeTo(null); // Center the window
mainFrame.setVisible(true);
}
private void createToolBar() {
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JButton openButton = new JButton("Open");
JButton saveButton = new JButton("Save");
JButton loadButton = new JButton("Load");
toolBar.add(openButton);
toolBar.add(saveButton);
toolBar.add(loadButton);
JButton helpButton = new JButton("Help");
toolBar.add(Box.createHorizontalGlue());
toolBar.add(helpButton);
JButton aboutButton = new JButton("About");
toolBar.add(aboutButton);
// Add action listeners for the buttons here if needed
mainFrame.add(toolBar, BorderLayout.NORTH);
// Help button action
helpButton.addActionListener(e -> showHelpDialog());
// About button action
aboutButton.addActionListener(e -> showAboutDialog());
//Open button action
openButton.addActionListener(e -> openWebsite("https://google.com")); // Replace with your desired URL
saveButton.addActionListener(e -> saveData());
saveButton.addActionListener(e -> saveData());
// Add ActionListener to the "Load" button
loadButton.addActionListener(e -> loadData());
}
private static void showHelpDialog() {
JOptionPane.showMessageDialog(null,
"Help content goes here.",
"Help",
JOptionPane.INFORMATION_MESSAGE);
}
private static void showAboutDialog() {
JOptionPane.showMessageDialog(null,
"Tag Replacement Tool\nVersion 1.0\nAuthor: Your Name",
"About",
JOptionPane.INFORMATION_MESSAGE);
}
private void createInputPanel() {
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel moNameLabel = new JLabel("Select mo_name:");
moNameComboBox = new JComboBox<>(tr.getMoNames());
moNameComboBox.setEditable(true);
JButton processButton = new JButton("Process");
inputPanel.add(moNameLabel);
inputPanel.add(moNameComboBox);
inputPanel.add(processButton);
// Add action listener for the "Process" button
processButton.addActionListener(e -> processMoContent());
mainFrame.add(inputPanel, BorderLayout.CENTER);
}
private void createOutputPanel() {
outputArea = new JTextArea(20, 50);
outputArea.setEditable(false);
outputArea.setFont(new Font("Monospaced", Font.BOLD, 14));
JScrollPane outputScrollPane = new JScrollPane(outputArea);
mainFrame.add(outputScrollPane, BorderLayout.SOUTH);
}
@SuppressWarnings("static-access")
private void processMoContent() {
String moName = moNameComboBox.getSelectedItem().toString();
StringBuilder resultBuilder = new StringBuilder();
// Check if the selected mo name exists in the database
if (!tr.isMoNameExists(moName)) {
JOptionPane.showMessageDialog(mainFrame, "The selected mo_name does not exist in the database.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
try (Connection conn = DriverManager.getConnection(tr.getDB_URL(), tr.getUSER(), tr.getPASS())) {
tr.createTables();
String moContent = tr.getMoContent(moName);
List<String> tags = tr.extractTags(moContent);
for (String tag : tags) {
String tagName = tr.getTagName(tag);
String tagComment = tr.getTagComment(tagName);
resultBuilder.append("Mo Name: ").append(moName).append("\n");
resultBuilder.append("Tag Name: ").append(tagName).append("\n");
resultBuilder.append("Tag Comment: ").append(tagComment).append("\n");
String replacementText = showInputDialogWithInfo("Enter replacement text for the tag '" + tagName + "':",
moName, tagName, tagComment);
if (replacementText.equals("__ABORT__")) {
break; // Abort tag replacement for this mo_name
}
moContent = moContent.replace(tag, replacementText);
}
showFinalContentWindow(moContent);
outputArea.setText(resultBuilder.toString());
} catch (SQLException se) {
se.printStackTrace();
} finally {
}
}
// Implement the custom dialog logic here
private static String showInputDialogWithInfo(String message, String moName, String tagName, String tagComment) {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Mo Name: " + moName));
panel.add(new JLabel("Tag Name: " + tagName));
panel.add(new JLabel("\nTag Comments: "));
JTextArea commentArea = new JTextArea(tagComment);
commentArea.setEditable(false);
JScrollPane commentScrollPane = new JScrollPane(commentArea);
panel.add(commentScrollPane);
panel.add(new JLabel("\n\nReplacement: "));
JTextField textField = new JTextField(20);
panel.add(textField);
JButton abortButton = new JButton("Abort");
panel.add(abortButton);
int result = JOptionPane.showOptionDialog(null, panel, message, JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (result == JOptionPane.OK_OPTION) {
return textField.getText();
} else if (result == JOptionPane.CANCEL_OPTION) {
// Return a special value to indicate "Abort" button was clicked
return "__ABORT__";
} else {
return "";
}
}
// Implement the final content window logic here
private static void showFinalContentWindow(String moContent) {
JFrame finalContentFrame = new JFrame("Final Content");
finalContentFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
finalContentFrame.setLayout(new BorderLayout());
// Final content panel
JTextArea finalContentArea = new JTextArea(moContent);
finalContentArea.setFont(new Font("Monospaced", Font.BOLD, 14));
finalContentArea.setEditable(true);
JScrollPane finalContentScrollPane = new JScrollPane(finalContentArea);
// Add a popup menu to the final content area
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem editItem = new JMenuItem("Edit");
popupMenu.add(copyItem);
popupMenu.add(editItem);
finalContentArea.setComponentPopupMenu(popupMenu);
// "Copy" action to copy the content to the clipboard
copyItem.addActionListener(e -> {
StringSelection selection = new StringSelection(finalContentArea.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
});
// "Edit" action to enable editing of the content
editItem.addActionListener(e -> finalContentArea.setEditable(true));
// Disable editing when the popup menu is closed
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Do nothing
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
finalContentArea.setEditable(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// Do nothing
}
});
finalContentFrame.add(finalContentScrollPane, BorderLayout.CENTER);
finalContentFrame.setPreferredSize(new Dimension(800, 600));
finalContentFrame.pack();
// Center the final content window on the screen
finalContentFrame.setLocationRelativeTo(null);
finalContentFrame.setVisible(true);
}
// ... (unchanged)
private void openWebsite(String url) {
try {
// Use Desktop to open the default web browser
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI(url));
} else {
JOptionPane.showMessageDialog(mainFrame, "Opening the default web browser is not supported on this platform.",
"Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while trying to open the website.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void saveData() {
try {
// Get the current state of the application data
String moName = Objects.requireNonNull(moNameComboBox.getSelectedItem()).toString();
String moContent = outputArea.getText();
// Choose the save file location using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showSaveDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (!selectedFile.getAbsolutePath().toLowerCase().endsWith(".trt")) {
selectedFile = new File(selectedFile.getAbsolutePath() + ".trt");
}
if (selectedFile.exists()) {
// File already exists, ask for confirmation to overwrite
int overwriteConfirmation = JOptionPane.showConfirmDialog(mainFrame,
"The selected file already exists. Do you want to overwrite it?",
"File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (overwriteConfirmation == JOptionPane.NO_OPTION) {
// User chose not to overwrite, return without saving
return;
}
}
// Write the data to the selected file in custom save file format
try (PrintWriter writer = new PrintWriter(selectedFile)) {
writer.println("MO_NAME:" + moName);
writer.println("MO_CONTENT:");
writer.println(moContent);
writer.flush();
}
JOptionPane.showMessageDialog(mainFrame, "Data saved successfully!",
"Save", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while saving the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void loadData() {
try {
// Choose the file to load data from using JFileChooser with custom file filter
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TRTFileFilter());
int returnValue = fileChooser.showOpenDialog(mainFrame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
// Read the data from the selected file in custom save file format
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
StringBuilder moContentBuilder = new StringBuilder();
String line;
boolean readingMoContent = false;
while ((line = reader.readLine()) != null) {
if (line.startsWith("MO_NAME:")) {
moNameComboBox.setSelectedItem(line.substring(8));
} else if (line.startsWith("MO_CONTENT:")) {
readingMoContent = true;
} else if (readingMoContent) {
moContentBuilder.append(line).append("\n");
}
}
// Set the loaded MO content to the output area
outputArea.setText(moContentBuilder.toString());
JOptionPane.showMessageDialog(mainFrame, "Data loaded successfully!",
"Load", JOptionPane.INFORMATION_MESSAGE);
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(mainFrame, "An error occurred while loading the data.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// Custom file filter for ".trt" files
private class TRTFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getName().toLowerCase().endsWith(".trt");
}
public String getDescription() {
return "Tag Replacement Tool Files (*.trt)";
}
}
}

View file

@ -0,0 +1,71 @@
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 8.0.30 - MySQL Community Server - GPL
-- Server OS: Win64
-- HeidiSQL Version: 12.1.0.6537
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-- Dumping database structure for mydb
DROP DATABASE IF EXISTS `mydb`;
CREATE DATABASE IF NOT EXISTS `mydb` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mydb`;
-- Dumping structure for table mydb.table1
DROP TABLE IF EXISTS `table1`;
CREATE TABLE IF NOT EXISTS `table1` (
`mo_name` varchar(15) NOT NULL,
`mo_content` text,
`mo_tags` text,
PRIMARY KEY (`mo_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table mydb.table1: ~7 rows (approximately)
DELETE FROM `table1`;
INSERT INTO `table1` (`mo_name`, `mo_content`, `mo_tags`) VALUES
('mo_bstc', 'A registration was started online to set up an APE account.The account was activated. The seller listed {#tag_prodcat} priced {#tag_abatbe} their current market value A review of the account showed that the seller also controlled {#tag_singmul}, . {#tag_singmultt} used to place orders with the seller account.{#tag_ishnr} {#tag_isactiveall} {#tag_isactivesm} {#tag_isblocked} ', 'tag_prodcat,tag_abatbe,tag_singmul,tag_singmultt,tag_ishnr,tag_isactiveall,tag_isactivesm,tag_isblocked'),
('mo1', '{#tag1 this a tag} original mo content {#tag2 this is another tag} Some more content', 'tag1,tag2'),
('mo2', 'original mo content {#tag3 this a tag} Some more content', 'tag3'),
('mo2ss', 'original mo content {#tag3 this a tag} Some more content', 'tag3'),
('mo3', 'hi there {#tag_prodcat originalcontentss}', 'tag_prodcat'),
('mo4', 'A registration was started online to set up an APE account.\r\n\r\nThe account was activated. The seller listed {#tag_prodcat ss} priced {#tag_abatbe ss} their current market value.\r\n\r\nA review of the account showed that the seller also controlled {#tag_singmul ss}, {#tag_singmultt ss} used to place orders with the seller account.\r\n\r\n{#tag_ishnr ss} .\r\n\r\n{#tag_isactiveall ss} {#tag_isactivesm ss} {#tag_isblocked ss} .', 'tag_prodcat,tag_abatbe,tag_singmul,tag_singmultt,tag_ishnr,tag_isactiveall,tag_isactivesm,tag_isblocked'),
('mo5', 'original mo content {#tag_mytag this a tag /this,that/ notthis} Some more content', 'tag_mytag');
-- Dumping structure for table mydb.table2
DROP TABLE IF EXISTS `table2`;
CREATE TABLE IF NOT EXISTS `table2` (
`mo_tags` varchar(15) NOT NULL,
`tag_comment` text,
PRIMARY KEY (`mo_tags`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table mydb.table2: ~12 rows (approximately)
DELETE FROM `table2`;
INSERT INTO `table2` (`mo_tags`, `tag_comment`) VALUES
('tag_abatbe', 'Pricing Above / at / below'),
('tag_isactiveall', 'The APE account is active on the Amazon EU online stores'),
('tag_isactivesm', 'The APE account is active on the Amazon <marketplace names> online stores'),
('tag_isblocked', 'The APE account is currently blocked on the <Marketplace name> ONLINE STORES ONLY online store(s). '),
('tag_ishnr', 'Additionally, these items did not appear to have been sent to the related buyer [#account./accounts.#] '),
('tag_mytag', 'i am tag_mytag'),
('tag_prodcat', 'Type the Product Categries'),
('tag_singmul', '[#multiple buyer accounts/a buyer account#]'),
('tag_singmultt', '[#These buyer accounts were/This buyer account was#] '),
('tag1', 'I am tag 1'),
('tag2', 'I am tag 2'),
('tag3', 'I am tag3 ');
/*!40103 SET TIME_ZONE=IFNULL(@OLD_TIME_ZONE, 'system') */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;

71
tagger.sql Normal file
View file

@ -0,0 +1,71 @@
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 8.0.30 - MySQL Community Server - GPL
-- Server OS: Win64
-- HeidiSQL Version: 12.1.0.6537
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
-- Dumping database structure for mydb
DROP DATABASE IF EXISTS `mydb`;
CREATE DATABASE IF NOT EXISTS `mydb` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mydb`;
-- Dumping structure for table mydb.table1
DROP TABLE IF EXISTS `table1`;
CREATE TABLE IF NOT EXISTS `table1` (
`mo_name` varchar(15) NOT NULL,
`mo_content` text,
`mo_tags` text,
PRIMARY KEY (`mo_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table mydb.table1: ~7 rows (approximately)
DELETE FROM `table1`;
INSERT INTO `table1` (`mo_name`, `mo_content`, `mo_tags`) VALUES
('mo_bstc', 'A registration was started online to set up an APE account.The account was activated. The seller listed {#tag_prodcat} priced {#tag_abatbe} their current market value A review of the account showed that the seller also controlled {#tag_singmul}, . {#tag_singmultt} used to place orders with the seller account.{#tag_ishnr} {#tag_isactiveall} {#tag_isactivesm} {#tag_isblocked} ', 'tag_prodcat,tag_abatbe,tag_singmul,tag_singmultt,tag_ishnr,tag_isactiveall,tag_isactivesm,tag_isblocked'),
('mo1', '{#tag1 this a tag} original mo content {#tag2 this is another tag} Some more content', 'tag1,tag2'),
('mo2', 'original mo content {#tag3 this a tag} Some more content', 'tag3'),
('mo2ss', 'original mo content {#tag3 this a tag} Some more content', 'tag3'),
('mo3', 'hi there {#tag_prodcat originalcontentss}', 'tag_prodcat'),
('mo4', 'A registration was started online to set up an APE account.\r\n\r\nThe account was activated. The seller listed {#tag_prodcat ss} priced {#tag_abatbe ss} their current market value.\r\n\r\nA review of the account showed that the seller also controlled {#tag_singmul ss}, {#tag_singmultt ss} used to place orders with the seller account.\r\n\r\n{#tag_ishnr ss} .\r\n\r\n{#tag_isactiveall ss} {#tag_isactivesm ss} {#tag_isblocked ss} .', 'tag_prodcat,tag_abatbe,tag_singmul,tag_singmultt,tag_ishnr,tag_isactiveall,tag_isactivesm,tag_isblocked'),
('mo5', 'original mo content {#tag_mytag this a tag /this,that/ notthis} Some more content', 'tag_mytag');
-- Dumping structure for table mydb.table2
DROP TABLE IF EXISTS `table2`;
CREATE TABLE IF NOT EXISTS `table2` (
`mo_tags` varchar(15) NOT NULL,
`tag_comment` text,
PRIMARY KEY (`mo_tags`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table mydb.table2: ~12 rows (approximately)
DELETE FROM `table2`;
INSERT INTO `table2` (`mo_tags`, `tag_comment`) VALUES
('tag_abatbe', 'Pricing Above / at / below'),
('tag_isactiveall', 'The APE account is active on the Amazon EU online stores'),
('tag_isactivesm', 'The APE account is active on the Amazon <marketplace names> online stores'),
('tag_isblocked', 'The APE account is currently blocked on the <Marketplace name> ONLINE STORES ONLY online store(s). '),
('tag_ishnr', 'Additionally, these items did not appear to have been sent to the related buyer [#account./accounts.#] '),
('tag_mytag', 'i am tag_mytag'),
('tag_prodcat', 'Type the Product Categries'),
('tag_singmul', '[#multiple buyer accounts/a buyer account#]'),
('tag_singmultt', '[#These buyer accounts were/This buyer account was#] '),
('tag1', 'I am tag 1'),
('tag2', 'I am tag 2'),
('tag3', 'I am tag3 ');
/*!40103 SET TIME_ZONE=IFNULL(@OLD_TIME_ZONE, 'system') */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;

8
trtconfig.json Normal file
View file

@ -0,0 +1,8 @@
{
"DB_URL": "jdbc:mysql://localhost/mydb",
"USER": "root",
"PASS": "",
"DB_NAME": "mydb",
"TABLE1_NAME": "table1",
"TABLE2_NAME": "table2"
}