[转] Eclipse and HSQLDB: Embed relational database servers into Eclipse (1)

xiaoxiao2021-03-05  23

This article describes how to develop a plugin that integrates the HSQLDB pure Java relational database server into Eclipse Workbench. Although it is not as strong as DB2, it is worse than Mysql popular, but HSQLDB (supersonic SQL database) can meet the needs of Java applications, because it has scalability, and is not high on memory / processor.

The supersonic SQL database is later officially renamed HSQLDB, which is a type of pure Java composed embedded relational database server, you can use it in single-machine mode (using direct file access) or client / server mode, it supports a large number of concurrency user. Although it is not as strong as DB2, it is worse than Mysql popular, but HSQLDB (supersonic SQL database) can meet the needs of Java applications, because it has scalability, and is not high on memory / processor.

HSQLDB is a class of easy Java development databases because it supports Structured Query Language (SQL) rich subsets, and Java programmers do not need to install severely consumption, memory and disk space on their development workstations. server. It is an ideal tool that integrates into the Eclipse IDE, which can provide useful tools for newcomers to provide experienced developers.

This article and the same series of subsequent articles will show you how to build a group of Eclipse plugins to embed HSQLDB into the Eclipse Workbench. You will see an example in a real world that explains how to develop such plugins in consideration of the API and User Interface (UI), and how to evaluate alternative methods to bring the required features to users. . This article assumes that you are using the Eclipse SDK distribution, not Platform Runtime-binary plus JDT. But if it is just to develop a regular Java application, the latter is more suitable.

In this series, we will use the three steps to create and extend the plugin group using three steps in this article (see the links given in the reference) of this article).

Run an existing tool in Eclipse to easily access the required pre-existing tools from the Workbench menu. Explore how to use other features of Eclipse to add values ​​to pre-existing tool sets to improve the productivity of Java developers. Use SWT to override the tool to achieve seamless integration with Eclipse Workbench.

Learn about HSQLDB You can download HSQLDB from SourceForge (HSQLDB.SourceForge.net; see the links given in the reference) Download HSQLDB, including source code and documentation. Be careful not to be confused with the original SourceForge project that has been frozen (hsql.sourceforge.net).

The binary distribution is a standard ZIP file, and what you have to do is extracting this ZIP file into a place on your hard drive. All HSQLDB Components - Database Engine, Server Process, JDBC Drivers, Documents, and Some Utilities - All in a separate JAR package, this package is installed in lib / hsqldb.jar, with a size of about 260 kB. Running the database engine requires only 170 kB of RAM, which is even if the PDA (such as the Zaurus produced by Sharp) can also be met, including the entire download file, including the source file and document, is small to a standard 1.44 MB floppy disk. .

You can start the database server and utility from the command line, the specific method is to call the convenient class like org.hsqldb.server and org.hsqldb.util.DatabaseManager, these two classes can accept a group of orders Row option, such as "-url", "- Database" (for direct file access) and "-user". Another "-?" Option can also be accepted, and its role is to provide help with respect to the valid command line syntax. The key factor that causes HSQLDB simplicity is the sequentialization of SQL statement execution. That is, although many concurrent users can connect to the database (when the database is running in server mode), all SQL statements are put in a queue, and then execute one time. Therefore, there is no need to achieve complex locking and synchronous algorithms. Despite this, HSQLB also implements Acid (Atomicity, Constency, ISOLATION, AND DURABILITY, NEO, NEO, NEO, consistency, isolation, and persistence) semantics. In other words, it is a transactional database, but only is in a read uncommitted level, and does not have a transaction isolation function. HSQLDB is actually created for embedded applications instead of a common data center.

If you want to use triggers, aggregate functions, external join, views, and other SQL features, HSQLB can meet your needs (most of the lightweight relationship databases cannot do this). You can implement a stored procedure by adding your Java class to the HSQLB classpath. Then you have a CREATE FUNCTION statement to tell. In fact, many standard SQL functions such as SQRT and ABS are implemented as direct mappings of standard Java classes (such as java.lang.math).

HSQLDB's Run mode The HSQLDB engine can run in a variety of modes to adapt to different applications:

All database tables and indexes in memory mode are placed in memory, and will never be saved on disk. Before you send questions that you want to use the database that will be lost when the application is lost, consider you can use a standard SQL statement to query, sort, group, and updated database data with a local cache.

The stand-alone mode application creates a database connection with JDBC, and the HSQLDB engine is running in the application, and the database file is allowed to access directly. There is no concurrent user (the application exclusively access the database file), but there is no additional thread and TCP connection overhead. Single-machine mode is the preferred mode of many embedded applications.

Server Mode This is a standard client / server database configuration similar to other relational databases that allows concurrent connections to use TCP sockets. Most developers like this mode because it allows any JDBC client to connect and query / update the table in the case where the primary application is still running.

Web server mode HSQLDB can be used as a web server, can accept SQL queries via HTTP; can also be run as a servlet in any standard web container, can pass through the firewall or installed on a web host service without involving provider support group (And expensive database host options). Since HTTP is stateless, there is no transaction in this mode.

HSQLDB Database File Structure HSQLDB places all tables and index data in memory, saving all SQL statements to a file called Database.script, which also acts as the role of the transaction log. After the initialization engine, the file is read, then all SQL statements are run, thereby completing the reconstruction of the entire database. During the downtime, the HSQLDB engine will generate a new Database.script file, which contains only the least statement, with the purpose to make the database quickly start. In addition to the table defaults in memory, HSQLDB also supports the Cache table and Text table. The data of all cached tables is placed in a file called Database.Data, and the data of the text table is placed in any separated text file (like the CSV file) named by the SET TABLE source non-standard SQL statement. The cache table supports the data set than available RAM, and the text table can be used as a convenient means of importing data.

In addition to Database.Script and Database.Data files, any HSQLDB database may also contain a Database.properties file, and the administrator can set a number of parameters that affect the ANSI SQL compatibility in this file. All database files (except text table data files) must be placed in the same directory.

There is no explicit method for creating a HSQLDB database. If you ask the engine to open a database file currently existing database files (using the servers -Database option or the JDBC URL of the stand-alone mode), the file and its directory are created. So, if you affirms that there is data in the empty database, check if there is an entered error.

Let us start developing plugins!

Creating a HSQLDB Eclipse plugin group puts existing applications to eclipse so powerful tools are not an easy task. Fortunately, HSQLDB and Eclipse have reduced the difficulty of the above tasks, because the HSQLDB itself can embed other applications, and Eclipse provides clear and easy-to-understand plug-in infrastructure and a robust development environment for creating new plugins. PDE. Even if you have never been exposed to the Eclipse plugin development, PDE can make it easy. See the article describing the Eclipse basic knowledge in the Reference section of this article.

These guidance contents assume that you are using the Eclipse SDK distribution instead of Platform Runtime-binary plus JDT. But if you just want to develop regular Java applications, the latter is more suitable. You can use your favorite operating system because we will only use Java code, and you will not use this unit code at all.

In order to create a useful plug-in group and write code as little as possible, we will start from the least work. Later, in the next part of this series, we will see how to use the Eclipse feature to provide value-added for HSQLDB.

In this article, we will focus on the following features of our code:

Start the HSQLDB engine in the server mode, so that the user application and the SQL console (like the HSQLDB's own DatabaseManager utility) can run the SQL statement. Stop HSQLDB servers completely. Call the DatabaseManager utility so that the developer can enter the SQL statement interactively from Workbench. Run the SQL script file using the HSQLDB ScriptTool utility. Over the years, in order to create database tables and insert test data, I have already put a lot of * .sql files in my project folder, and I have long wish to have an easy way to run them. Configure HSQLDB connection properties, such as TCP ports and administrator passwords. How can these functions can be used for Workbench? The easiest way to complete the first three steps is to provide an ActionSet, which is added to the new top-level menu and can be accessed from its own toolbar. The operation running the SQL script file must only be bound to a file named "* .sql", so this will be an ObjectContribut, which is added to the pop-up menu on any view of these files. Finally, the connection parameters should be well compliant with the plug-in parameter selection page, and you can access this page from the Workbench Window menu.

Figure 1 shows a new menu and toolbar, while Figure 2 shows new items in the pop-up menu of the Navigator view, Figure 3 shows the property page, so you can see the first version of our plugin group. What looks like.

Figure 1.HSQLDB menu and related toolbar

Figure 2. Pop-up menu item added to the * .sql file

Figure 3. HSQLDB connection properties

Turn HSQLDB into an Eclipse plugin to build our plug-in group to pack HSQLDB itself into an Eclipse plugin. This plugin will only contain the necessary PLUGIN.XML files required by HSQLDB. Jar and Workbench. If you have already viewed the standard Eclipse plug-in directory, you may have discovered that JUnit, Xerces, Tomcat, and other common Java packages were isolated in their respective plugins, and all Eclipse details were packaged in other Insert. This type of division makes these third-party tools easy to update, and does not necessarily change the Eclipse itself. Another benefit is that it is easy to share these common libraries with many plugins.

Open your Eclipse SDK installation and create a new plugin item; name HSQLDB.CORE (I know that the name recommended is org.hsqldb.core, but I don't want to pretend to use the HSQLDB name space. Perhaps HSQLDB development The readers will end with this idea and recommend it to "formally" Eclipse integrated plugins; this name is very likely to be changed). Make sure the "EMPTY PLUGIN" option is checked, not any plug-in template; otherwise you will get a top-level plugin class where you have use, if you want to delete it, it can be safely removed. Copy hsqldb.jar from your HSQLDB to the project directory and add it to the project's runtime. You can do this using PDE PLUGIN Manifest Editor or simply copying the content in Qingda 1.

Listing 1. Plugin.xml manifest file for HSQLDB.Core plugins

ID = "hsqldb.core" name = "HSQLDB Core Plug-in"

Version = "0.0.1"

Provider-name = "Fernando Lozano (www.lozano.geti.br)>

Add Workbench Extension Next, create a second plugin item named HSQLDB.UI. This project will include all Eclipse extensions for the first revision of the plug-in group: an operation set of three operations, an object effect related to the * .sql file, and a property page. Name its main class (Plugin class) Pluginui, and accept the default name HSQLDB.UI of the package.

Use the Plugin Manifest Editor to open the plugin.xml file and select the Extensions tab. Change the assigned menu to HSQLDB and change the demonstration operation to display the tag "Runs HSQLDB Database Manager". Add additional operations to the same ActionSet with the label "Stops HSQLDB Database Server" and "Starts HSQLDB Database Server" and provide the unique operation ID and implementation of each operation. Note that the above operation will appear in the menu and toolbar in the order in which the creation is reversed.

Click the Add button to add two new extensions using the Extension template, pop-up menu, and property pages. The pop-up menu should be associated with the * .sql file mode, but the property page field should be set by programming.

Figure 4 shows the final appearance of the Plugin Manifest Editor and shows all plug-in extensions; Figure 5 shows the properties allocated by the object (note the filter for * .sql file), and Figure 6 shows the file resource pop-up menu The properties of the "Run SQL Script" operation. The icon is given in the source code in this article (see Resources), but I will definitely know that there is a better graphic expert than this!

Figure 4. HSQLDB operation on the list editor

Figure 5. HSQLDB object assignment on the list editor

Figure 6. Run SQL SCRIPT operation on the list editor

Before you add code to our operation, we need to distinguish this UI plugin with the corresponding core plugin, otherwise it will not access the HSQLDB class. Go to the "DependenCIES" page on the Plugin Manifest Editor and add a plugin dependence, as shown in Figure 7. Some dependencies, like "Eclipse.UI", automatically configured by PDE, while other dependence, like "org.eclipse.debug.core, add when the operation is encoded. If you are willing to edit the XML code directly, Listing 2 shows the full plugin.xml file for the HSQLDB.UI plugin.

To complete the installation of the plugin, add a new class to the HSQLDB.UI package and name it HSQLDBUTIL. This class will contain all the code directly handled the HSQLDB and keep the allocated extension code simple.

Figure 7. HSQLDB.UI plugin dependence

Listing 2. HSQLDB.UI plugin PLUGIN.XML inventory file

ID = "hsqldb.ui"

Name = "HSQLDB UI Plug-in"

Version = "0.0.1"

Provider-name = "Fernando Lozano (www.lozano.geti.br)"

Class = "hsqldb.ui.pluginui">

Point = "org.eclipse.ui.actionsets">

Label = "HSQLDB"

Visible = "True"

ID = "HSQLDB.UI.ActionSet">

Label = "HSQL & DB"

ID = "HSQLDBMENU">

Name = "dbservergroup">

Label = "Run HSQL & Database Manager"

Icon = "icons / dbman.gif"

Tooltip = "Runs The HSQL Database Manager"

Class = "hsqldb.ui.actions.hsqldbdatabasemanageraction"

MenuBarpath = "HSQLDBMENU / DBSERVERGROUP"

Toolbarpath = "dbservergroup"

ID = "hsqldb.ui.Actions.hsqldbdatabasemanageracration">

Value = "Activated"

ID = "hsqldb.ui">

Label = "S & TOP HSQLDB"

icon = "icons / stop.gif" tooltip = "stops the hsql database server"

Class = "hsqldb.ui.Actions.hsqldbstopaction"

MenuBarpath = "HSQLDBMENU / DBSERVERGROUP"

Toolbarpath = "dbservergroup"

ID = "hsqldb.ui.Actions.hsqldbstopaction">

Value = "Activated"

ID = "hsqldb.ui">

Label = "& Start HSQLDB"

Icon = "icons / start.gif"

Tooltip = "Starts The HSQL Database Server"

Class = "hsqldb.ui.Actions.hsqldbstartAction"

MenuBarpath = "HSQLDBMENU / DBSERVERGROUP"

Toolbarpath = "dbservergroup"

ID = "hsqldb.ui.Actions.hsqldbstartaction">

Value = "installed"

ID = "hsqldb.ui">

Point = "Org.eclipse.ui.PerspectiveExtensions">

Targetid = "org.eclipse.ui.resourceperspective">

ID = "HSQLDB.UI.ActionSet">

Point = "org.eclipse.ui.popupmenus">

ObjectClass = "Org.eclipse.core.Resources.ifile"

Namefilter = "*. sql"

ID = "hsqldb.ui.sqlscriptfiles">

Label = "Run SQL Script"

Class = "hsqldb.ui.popup.Actions.hsqldbrunscript"

MenuBarpath = "additions"

Enablesfor = "1"

ID = "hsqldb.ui.hsqldbrunscript">

Value = "Activated"

ID = "hsqldb.ui">

ID = "hsqldb.ui.preference"

Point = "org.eclipse.ui.preferencepages">

Name = "HSQLDB Server"

Class = "hsqldb.ui.preference ".hsqldbpreferencepage"

ID = "hsqldb.ui.preferences.hsqldbpreferencePage">

Start HSQLDB Use class org.hsqldb.server to start the HSQLDB engine in server mode is quite easy. With the HSQLDB database name (the basic name of the path database file), the TCP port used to listen to the connection request and a flag used to determine if it should call the system.exit () as the command line parameter. The following command line is a typical situation when running HSQLDB:

Java -cp /opt/hsqldb/hsqldb.jar org.hsqldb.server -Database / tmp / bd -port 9001 -system_exit = true

The above line command created three database files for /tmp/db.script, /tmp/db.properties, and /tmp/db.data.

We can use the Server class master method and pass a string array as its parameters. But we must do this in a new thread; otherwise, we will lock the entire Workbench. The unique plug-in class maintains a reference to this thread so that it can check if the server has been started before connecting to a server, and can also check if it is running, because any client can connect to this server On, then submit the shutdown statement to terminate it.

The code in Listing 3 shows the RUN method of hsqldb.ui.Actions.hsqldbStartAction, and Listing 4 shows the code of StartHsqldb in hsqldb.ui.hsqldbut, which actually launches the server. We will discuss technology for managing user feedback later.

The most interesting part of the above code is how we find a location to place the database file. A project called .HSQLDB If it does not exist, it will be created, and the engine will look for Database.script and other database files in the project.

Eclipse provides all plugins in a standard directory that can save any configuration file. You can get such a directory by calling Plugin.getStateLocation, but I don't think the database file is actually a plugin configuration file. They look more like user data files, and they are here, they should be located in the project in the developer workspace.

Listing 3. Start HSQLDB operation in server mode, from hsqldb.ui.Actions.hsqldbStartAction

Public void run (IAAADITION Action) {

// Check a Database Was Really Started by The Plug-in

Pluginui plugin = pluginui.getDefault (); if (plugin.gethsqldbserver ()! = Null) {

(ApplicationWindow) WINDOW) .SETSTATUS (

"HSQLDB Server Already Running.");

}

Else {

Cursor Waitcursor = New Cursor (Window.getshell (). GetDisplay (),

SWT.CURSOR_WAIT);

WINDOW.GETSHELL (). setCursor (Waitcursor);

Try {

Hsqldbutil.startHSQLDB ();

(ApplicationWindow) .SetStatus ("HSQLDB Server Started.");

}

Catch (CoreException E) {

MessageDialog.openerror (Window.getshell (),

HSQLDB Plugin,

"Could Not Create HSQLDB Database Project.");

E.PrintStackTrace (System.err);

}

Finally {

WINDOW.GETSHELL (). setCursor (NULL);

Waitcursor.dispose ();

}

}

}

Listing 4. Really starting HSQLDB code from HSQLDB.UI.HSQLDBUTIL

Public static void starthsqldb () throws coreException {

Pluginui plugin = pluginui.getDefault ();

// Finds Project Local Path for Database Files

IWorkspaceroot Root = pluginui.getWorkspace (). Getroot ();

IProject hsqldbproject = root.getproject (". Hsqldb");

IF (! hsqldbproject.exists ()) {

HSQLDBProject.create (null);

}

HSQLDBProject.open (null);

Ipath dbpath = hsqldbproject.getlocation ();

Final String Database = dbpath.toString () "/ database";

// Starts a new thread to run the database server

Final hsqldbparams params = getConnectionParams ();

Thread Server = new thread () {

Public void run () {

String [] args = {"-database", Database,

"-Port", string.valueof (params.port),

"-NO_SYSTEM_EXIT", "True"};

Server.main (ARGS);

}

}

Plugin.sethsqldb Server;

Server.Start ();

}

Stop HSQLDB To stop HSQLDB servers, just a shutdown command as a SQL statement. As shown in Listing 5, the stophsqldb method from hsqldb.ui.hsqldbutil has completed this task. The corresponding code corresponds to the code and the code described when the server is started almost identical, so it is not listed here. ClassNOTFoundException (from class.forname) and SQLException exception are thrown in Listing 5, so the operational code can provide sufficient feedback to the user. Listing 5. Code for stopping HSQLDB servers

Public static void stophsqldb () throws classnotfoundexception,

Sqlexception {

Pluginui plugin = pluginui.getDefault ();

Hsqldbparams params = getConnectionParams ();

// Submits the shutdown statement

Class.Forname ("org.hsqldb.jdbcdriver);

String Url = "JDBC: HSQLDB: HSQL: //127.0.0.1:" params.port;

Connection Con = DriverManager.getConnection (URL, Params.user,

Params.passwd;

String SQL = "shutdown";

Statement Stmt = con.createstatement ();

Stmt.executeUpdate (SQL);

Stmt.close ();

// no need to close a dead connection!

Plugin.sethsqldb Server (NULL);

}

Running HSQL Database Manager Running the Database Manager utility in HSQLDB than running the server itself. Because the server is created to be embedded in other applications, the above utility is scheduled to run as a stand-alone application or Java applet. Although both modes accept command line parameters (or applet parameters), we still don't want to get only a new Java VM overhead for a window that can get a user can enter the SQL statement. Direct calls Static void main (String [] args will not work as expected because it will call System.exit () terminate Workbench.

After browsing the org.hsqldb.util.databaseManager source code, we found that instantiation and initializing a JDBC connection is easy, but the necessary methods are not public. So we can create a class named org.hsqldb.util.patchedDatabaseManager in the HSQLDB source tree, and then generate a new HSQLDB.jar using the Ant build script provided, which contains the Database Manager that we have passed. Only two visibility needs to be changed to public: void main () and Void Connect (Connection Con). Listing 6 shows how the plugin uses these two methods to run patch.

Database Manager is an AWT application (see Figure 8), which will create your own event thread (independent of the Eclipse SWT thread) and terminate after calling System.exit () to turn off Workbench. Multiple instances of this utility can be run without problems unless there is no Workbench window to rely. For the first revision of our HSQLDB plug-in, this is good, but before this series, we must change it to a SWT application, embedded therefrom like the Eclipse view. Figure 8. HSQLDB Database Manager

Listing 6. Starting the Database Manager utility of the patch

Public Static Void RundatabaseManager () THROWS CLASSNOTFOUNDEXCEPTION,

Sqlexception {

Pluginui plugin = pluginui.getDefault ();

Hsqldbparams params = getConnectionParams ();

// Creates a connection to the Internal Database

String Url = "JDBC: HSQLDB: HSQL: //127.0.0.1:" params.port;

Class.Forname ("org.hsqldb.jdbcdriver);

Connection Con = DriverManager.getConnection (URL, Params.user,

Params.passwd;

IF (con! = null) {

// Needed to Patch DatabaseManager SO it Could

// be initialized and use the support connection

PATCHEDDATABASEMANAGER DM = New PatchdDatabaseManager ();

DM.MAIN ();

DM.Connect (con);

}

}

Run the SQL script HSQLDB Script Tool read the plain text file and rely on a given JDBC URL execute the SQL statement included in the file. SQL statement batch is separated by the go command, and the script can also write messages in the script using the print command.

The scripts that are familiar with other database systems can only contain SQL statements separated by semicolon (;), but this allows HSQLDB to run all scripts in a single batch, but only return the result of the last statement. You need to include a Go command between SQL statements to accept the results of each statement.

The easiest way to make users browse scripts is to put them in a console view, just like Java applications called from Workbench and Ant build scripts. This requires a Java Launch configuration, and the configuration creates another Java VM. Because the SQL script is short, we can think that its overhead is acceptable, and if you think that Database Manager should be called in its own VM, you can use the RunScriptTool method given in Listing 7 as an example. .

Listing 7 is the longest list in this article (the first one of this series), most of which is about establishing a HSQLDB that includes the correct JRE (must be explicitly set) and HSQLDB.Core plugins. Jar's class path. See the reference part of this article can get more information about running the framework provided by Eclipse and the extended information provided by JDT. For developers who are familiar with other GUI kits, how to get the path to the selected SQL script file is not an obvious thing. The IObjectActionDelegate interface is assigned by an object of the extended resource pop-up menu. After calling its RUN method, it is just a reference to the operation itself, just like a top menu operation, without including the selected resource or originating control Information. Resource references are actually provided to the SelectionChanged method, and must be saved as an instance variable for later use - see Listing 8.

Listing 7. Run HSQLDB Script Tool

Public Static Void RunscriptTool (ifile currentscript) throws coreException {

Pluginui plugin = pluginui.getDefault ();

// deStroys Any Preexisting Configuration and Create A New One

IlaunchManager Manager = DebugPlugin.getDefault (). GetLaunchManager ();

IlaunchConfigurationType type = manager.getlaunchConfigurationType

IjavaalaunchConfigurationConstants.id_java_application);

Ilaunchconfiguration [] configurations = manager.getlaunchConfigurations

TYPE);

For (int i = 0; I> configurations.length; i ) {

IlaunchConfiguration Config = Configurations [i];

IF (config.getname (). Equals ("SQL Script")) {

CONFIG.DELETE ();

}

}

Ilaunchconfigurationworkingcopy wc = type.newinstance (NULL,

"SQL Script");

// Constructs a classpath from the default jre ...

Ipath systemlibs = new path (javaruntime.jre_container);

IruntimeClassPathentry SystemLibsentry =

Javaruntime.newruntimeContainerClassPathenTry (

Systemlibs, IruntimeClassPathenTry.standard_classes;

Systemlibsentry.setClassPathproperty

IruntimeclassPathenTry.bootstrap_classes;

// ... Plus Hsqldb.core Plugin

IpluginRegistry registry = platform.getpluginregistry ();

Iplugindescriptor hsqldbcore = registry.getplugindescriptor

"hsqldb.core");

Ilibrary [] libs = hsqldbcore.getRuntimelibraries ();

String installdir = hsqldbcore.getInstallURL (). TOEXTERNALFORM ();

URL HSQLDBJAR = NULL;

Try {

Hsqldbjar = Platform.ASLOCALURL (New URL (InstallDir

Libs [0] .GetPath ()));

}

Catch (Exception E) {

// Ignore URL Exceptions

}

IruntimeClassPathentry HSQLDBENTRY =

Javaruntime.newarchiveruntimeclassPathentry (new path

Hsqldbjar.getPath ()));

HSQLDBENTRY.SETCLASSPATHPROPERTY (IRuntimeClassPathenTry.user_Classes);

// sets the launch configuration classpath

List classpath = new arraylist ();

ClassPath.Add (SystemLibsentry.getMEmento ());

ClassPath.Add (HSQLDBENTRY.GETMEMEMEMEMENTO ());

Wc.setttribute (ijavaalaunchConfigurationConstants.attr_classpath,

ClassPath);

Wc.setttribute (ijavaalaunchConfigurationConstants.attr_default_classpath,

FALSE);

// Current Directory Should Be The Script Container

Ipath Dir = currentscript.getparent (). GetLocation ();

Wc.setttribute (ijavalaunchConfigurationConstants.attr_working_directory,

Dir.tostring ());

// Gets the path for the selected SQL Script File

Wc.setttribute (ijavalaunchConfigurationConstants.attr_main_type_name,

"org.hsqldb.util.scriptttool");

// builds scripttool command line

Hsqldbparams params = getConnectionParams ();

String args = "-driver org.hsqldb.jdbcdriver"

"-url JDBC: HSQLDB: HSQL:"

"-database //127.0.0.1:" params.port "" "

"-user" params.user ""

"-script" currentscript.getname ();

IF (params.passwd.length ()> 0)

Args = "-Password" params.passwd "";

Wc.setttribute (ijavaalaunchConfigurationConstants.attr_Program_arguments, args);

// SAVES The New Config and Launches IT

Ilaunchconfiguration config = wc.dosave ();

Debuguitools.launch (config, ilaunchmanager.run_mode);

}

Listing 8. How to get SQL script to be executed, from hsqldb.ui.popup.Actions.hsqldbrunscript

Public void SelectionChanged (IADITION Action, ISELECTION Selection) {

Currentscript = null;

IF (Selection! = NULL) {

IF (Selection InstanceOf IstructureDSelection) {

IstructuredSelection SS = (istructureDselection) Selection;

// AS this action is enabled Only for a single selection,

// it's enough to get the first element

Object obj = ss.getfirstlement ();

IF (Obj InstanceOf ifile) {

Currentscript = (ifile) OBJ;

}

}

}

}

HSQLDB Properties Now our functionality has been in place, just missing the method of configuring server connection parameters: It listens for TCP ports, administrator user names, and administrator user passwords. The TCP port may have to change, thereby avoiding conflicts with other applications installed on the developer machine; users and passwords can be changed from any client using SQL statements. These parameters can be placed in a class similar to a C structure (or similar PASCAL record), as shown in Listing 9. It also declares that the constants used by the PLUGIN Preferences Store and Property Page are also available and saved the parameters (reference) value.

Listing 9. Parameter selection structure for HSQLDB server connection parameters

Package hsqldb.ui;

Public class hsqldbparams {

// Preference Names for the Plugin

Public static factory string p_port = "serverport";

Public static final string p_user = "serveruser";

Public static factory string p_passwd = "serverpasswd";

Public Int port = 9001;

Public String User = "sa";

Public String Passwd = ""

}

Unfortunately, the parameter selection page generated by PDE New Extension Wizard plans a misleading, which includes a method for setting the default parameter selection value that is not stored by the plugin parameter. The correct location of the initialization default value should be the main PLUGIN class itself. Otherwise, all parameter selection using the default value will be stored by the parameter to store the store to 0 or NULL.

Therefore, the parameter selection page class becomes more simple, as shown in Listing 10, and method initializedefaultpreference is added to the PluginUI class, as shown in Listing 11. Note that the default values ​​for each parameter selection are defined by the parameter selection structure instead of the selection page class by the plug-in class or parameter. Listing 10. Parameter selection page for HSQLDB plugin

Public Class HsqldbPReferencePage

Extends FieldEditorPreferencePage

Implements iWorkbenchPreferencePage {

Public hsqldbpreferencePage () {

Super (grid);

SetPreferenceore (Pluginui.getDefault (). getPreferenceOrEncestore ());

SetDescription ("Connection Parameters for the Embedded HSQLDB Server");

}

Public void createfieldeditors () {

Addfield (new integerfieldeditor (hsqldbparams.p_port,

& TCP port: ",

GetfieldeditorParent ()));

Addfield (new stringfieldedite (hsqldbparams.p_user,

"Administrator & User:",

GetfieldeditorParent ()));

Addfield (New Stringfieldeditor (hsqldbparams.p_passwd,

"Administrator & Password:",

GetfieldeditorParent ()));

}

Public void init (iWorkbench Workbench) {

}

}

Listing 11. Changed method from the generated Plugin class

Public void shutdown () throws coreexception {

// Shuts Down the Server IF Running

Thread server = gethsqldbserver ();

IF (Server! = null && server.isalive ()) {

Try {

HSQLDBUTIL.STONSQLDB ();

}

Catch (Exception E) {

E.PrintStackTrace ();

}

}

Super.shutdown ();

}

Protected Void InitializedEfaultPreference (iPreferenceore Store) {

Super.initializedefaultPreference (Store);

Hsqldbparams params = new hsqldbparams ();

Store.setDefault (hsqldbparams.p_port, params.port);

Store.setDefault (hsqldbparams.p_user, params.user);

Store.setDefault (hsqldbparams.p_passwd, params.passwd);

}

Provide feedback to the user because the plug group does not provide both the view nor the editor to Workbench, there is only a few limited methods to provide feedback from the user. We can use the status bar of the Workbench window and a SWT MessageDialog so that users will not miss important events (usually errors).

The visibility and implementation model of Workbench operations are mainly concentrated in workspace resource selection, but most plug-in operations (starting and stopping HSQLDB servers, but also launching Database Manager) do not depend on resource selection, but depending on whether the server is running - This condition must be explicitly checked by each operational RUN method. WARNING: The plug-in class and the operation class are definitely needed to reduce Workbench will be initialized when the demand for memory. The list file content is used to represent menus selection and enable / disabling them, but because the HSQLDB server is not workspace resource, it cannot enable operation. As described in the list code in Listing 2, you can enable / disable an action on the basis of the activation plug-in, so only "start hsqldb server" operations can be enabled at startup. However, after this, if the server is already in operation, there is no easy way to disable this operation and re-enable it after it stops.

Note that the code for placing a hourglass cursor on the Workbench window, and the code for setting the status bar message is not easy to find in the PDE document or Eclipse.org article.

The last step plug-in class rewrites the shutdown method, so it can clean the server when Workbench is turned off, and we end the entire process. Of course, you have to get a complete plug-in group, you need to do additional tasks here, such as:

Pack two plugins into a function so they can be installed, removed, enabled, and disabled as a unit. Provide a help documentation for the plugin itself and use a format suitable for the Workbench Help Manager to include the HSQLDB document in it.

Conclusions How to create a set of plugins that can introduce the HSQLDB database into Eclipse Workbench to add boot and stop servers and the ability to run SQL statements and scripts. We have learned how PDE makes it easy for this type of plug-in to create jobs, that is, use the wizard and editor for most tasks, and the task left to developers is just the code that is really realizing the functionality.

In this series of next sections, you will learn how to develop add values ​​to HSQLDB using Workbench's function, not just a pre-existing tool.

Reference

转载请注明原文地址:https://www.9cbs.com/read-38124.html

New Post(0)