--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="src-test"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="var" path="ECLIPSE_HOME/plugins/org.junit_3.8.1/junit.jar"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
--- /dev/null
+bin
+com.quantum
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>net.sourceforge.phpeclipse.quantum.sql</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+Changes: Changes from 2.2.3\r
+\r
+Most changes to this version are trivial, and fall \r
+into two main categories:\r
+\r
+- JDK 1.3 should now be supported. \r
+\r
+- Eclipse 3.0 M5/M6 should be supported (although \r
+ there's a different jar to install\r
+\r
+In addition:\r
+\r
+- Schema handling has been revised.\r
+\r
+\r
+\r
+\r
+\r
+Changes: Changes from 2.2.2\r
+\r
+Most of the changes to the code are structural and\r
+won't have an effect on the use of the plug-in. Some\r
+of the changes that you will see include:\r
+\r
+- Better refresh support (Issuing a refresh on the \r
+ bookmark list does not collapse any previously-open\r
+ selections.\r
+ \r
+- Properties available for items in the bookmark list\r
+\r
+- Key mapping (Ctl-Shift-Q) to execute queries in the \r
+ Query view\r
+ \r
+- Bug fix for mixed-case tables in PostGres\r
+\r
+- Bug fix for SQL Queries on Oracle with column type\r
+ of CHAR\r
+ \r
+- Added an explicit checkbox to indicate that you want\r
+ to be prompted for a password at connection time.\r
+ \r
+- When you've selected multiple nodes at the same time,\r
+ you can perform the same action on each of them.\r
+ \r
+- The status line from the Bookmark View now appears in\r
+ the standard status line window area.\r
+ \r
+- Queries are persisted so that you can keep a list of \r
+ queries.\r
+ \r
+Changes: Changes from 2.2.1\r
+\r
+- Now you can leave blank the password field in the bookmark, \r
+ as suggested by Erik Dick in the Forum. You will be asked for \r
+ its value when trying to connect. There is a property \r
+ (Window->Properties->QuantumDB) to modify in case you use \r
+ blank passwords and don't want to be pestered with dialogs. \r
+ In this case, change the default (nothing) to a string \r
+ (e.g. "") and only when you use that string as bookmark \r
+ password you'll be asked for a new password.\r
+ \r
+- The Query History View now registers all the queries, even \r
+ before being activated, fixing bug #773726.\r
+ \r
+- The case sensitivity when using Postgres in Windows should \r
+ go now (bug #804353).\r
+ \r
+- Fixed bug #811591, the Copy/Paste of bookmarks wasn't properly \r
+ initialized.\r
+ \r
+- Now if the connection is implicit (created when using the SQL \r
+ Editor before opening the bookmark), the bookmark is connected \r
+ but the tables and views are not loaded till you try to expand \r
+ the node.\r
+ \r
+- Fixed (really avoided) the problem with the Oracle jdbc driver \r
+ and its bug with getIndexInfo(). Bug reference #819846. \r
+
\ No newline at end of file
--- /dev/null
+bin.includes = icons/,\
+ doc/,\
+ *.jar,\
+ plugin.xml,\
+ plugin.properties,\
+ install.txt,\
+ .classpath,\
+ .project,\
+
+source.quantum.jar = src/
--- /dev/null
+
+<p>Author: jparrai<br>
+ Date: 26-08-2003<br>
+ Subject: Using the Custom Copy facility<br>
+</p>
+<p> The "Custom Copy" feature is meant to allow the user to customize the copy
+ format of tables and columns.</p>
+<p><b>How to use </b>: You are in the Bookmarks View, or the Subset View. You
+ select the tables, views and columns that you want to copy. Be sure that only
+ tables, views and columns are selected. Then you select "Custom Copy" in the
+ context menu. By default, a blank sub-menu will appear. You have to customize
+ it to do something. </p>
+<p><b>How to customize</b> : You go to the <b>Window->Preferences</b> , then <b>QuantumDB->Copy->Custom
+ Copy 1</b>. You can have up to three different templates, that will appear in
+ the sub-menu with the names you give to them. So you start the Custom Copy 1
+ preferences page. </p>
+<p>There you have some boxes to fill up. The idea is that you will have a list
+ of tables (from now on, tables will mean "tables and views"). This list of tables
+ is composed of the directly selected tables plus the implicitely selected (because
+ a column of it is selected). You choose a general template format, and the formats
+ of the lists and items. The possible variables you have to play are: </p>
+<blockquote>
+ <p><b>${schema}</b> The schema of the table or column. Valid in all format specifiers
+ except Template. </p>
+ <p><b>${table}</b> The table name, without schema. Valid in all format specifiers
+ except Template. </p>
+ <p><b>${qualified}</b> Same as ${schema}.${table} Valid in all format specifiers
+ except Template. </p>
+ <p><b>${column}</b> The column name. Only valid for Column specifiers. </p>
+ <p><b>${column_list}</b> The list of all columns. Only valid for Table specifiers.
+ </p>
+ <p><b>${table_list}</b> The list of all tables. Only valid in Template. This
+ is the only variable that can be used in Template. </p>
+ <p><b>\n</b> Inserts a new line </p>
+ <p><b>\t</b> Inserts a tab character</p>
+</blockquote>
+<p>It's faster to explain by example. Suppose I select the columns ENAME and JOB
+ from the table BONUS in schema SCOTT, and also the entire table DEPT from same
+ schema. </p>
+<blockquote>
+ <p> </p>
+ <table width="75%" border="1">
+ <tr>
+ <td>BONUS<i> (implicit)</i></td>
+ <td>ENAME<i> (selected)</i></td>
+ </tr>
+ <tr>
+ <td> </td>
+ <td>JOB<i> (selected)</i></td>
+ </tr>
+ <tr>
+ <td>DEPT <i>(selected)</i></td>
+ <td>DEPTO <i>(implicit)</i></td>
+ </tr>
+ <tr>
+ <td> </td>
+ <td>DNAME <i>(implicit)</i></td>
+ </tr>
+ <tr>
+ <td> </td>
+ <td>LOC<i> (implicit)</i></td>
+ </tr>
+ </table>
+</blockquote>
+<p>Now I have the specifiers : </p>
+<ul>
+ <li><b>Name</b>: AnyName </li>
+ <li><b>Table Item</b>: Call_Func(${column_list}) </li>
+ <li><b>Table Separator</b>: \n </li>
+ <li><b>Column Item</b>:${column} </li>
+ <li><b>Column Separator</b>: , </li>
+ <li><b>Template</b>: //Generated code\n${table_list}\n//End of generated code
+ </li>
+</ul>
+<p>The result will be: </p>
+<blockquote>
+ <blockquote>
+ <p><i>// Generated code</i></p>
+ <p><i> Call_Func(ENAME, JOB)</i></p>
+ <p><i> Call_Func(DEPTNO, DNAME, LOC)</i></p>
+ <p><i> //End of generated code</i></p>
+ </blockquote>
+</blockquote>
+<p> If I want only a list of columns, I can set: </p>
+<ul>
+ <li><b>Name</b>: AnyName </li>
+ <li><b>Table Item:</b> ${column_list} </li>
+ <li><b>Table Separator</b>:, </li>
+ <li><b>Column Item</b>:${qualified}.${column} </li>
+ <li><b>Column Separator</b>: , </li>
+ <li><b>Template</b>: (${table_list}) </li>
+</ul>
+<p>The result will be: </p>
+<blockquote>
+ <blockquote>
+ <p><i>(SCOTT.BONUS.ENAME, SCOTT.BONUS.JOB, SCOTT.DEPT.DEPTNO, SCOTT.DEPT.DNAME,
+ SCOTT.DEPT.LOC) </i></p>
+ </blockquote>
+</blockquote>
--- /dev/null
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML>
+<HEAD>
+ <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=windows-1252">
+ <TITLE></TITLE>
+ <META NAME="GENERATOR" CONTENT="OpenOffice.org 1.1Beta (Win32)">
+ <META NAME="CREATED" CONTENT="20030628;15450300">
+ <META NAME="CHANGED" CONTENT="20030703;16152310">
+ <STYLE>
+ <!--
+ @page { size: 21.59cm 27.94cm; margin: 2cm }
+ P { margin-bottom: 0.21cm }
+ H3 { margin-bottom: 0.21cm }
+ H3.western { font-family: "Arial", sans-serif }
+ H3.cjk { font-family: "MS Mincho" }
+ -->
+ </STYLE>
+</HEAD>
+<BODY LANG="" DIR="LTR">
+Author: jparrai<br>
+Date: 28-06-2003<br>
+Subject: Highlights of the structure of data in Quantum.<br>
+<H3 CLASS="western">Quantum program data structure</H3>
+<P>After loading the Quantum plug-in, the saved-state file (an xml file) is loaded
+ up. Bookmarks are loaded into the <font face="Courier New, Courier, mono">BookmarkContentProvider
+ </font>and the <font face="Courier New, Courier, mono">SubsetContentProvider</font>
+ classes, where they are stored in the form of a vector of <font face="Courier New, Courier, mono">BookmarkNode</font>
+ and SubsetNode respectively.</P>
+<P>A <font face="Courier New, Courier, mono">SubsetNode</font> has a number of
+ children, objects of class <font face="Courier New, Courier, mono">ObjectNode</font>.
+ Each <font face="Courier New, Courier, mono">ObjectNode</font> has an <font face="Courier New, Courier, mono">ObjectMetaData</font>
+ instance that will hold the metadata (columns names, sizes and that stuff) of
+ the table or view that it (the <font face="Courier New, Courier, mono">ObjectNode</font>)
+ references. That metadata is loaded from the saved-state file also on load-up
+ of the plug-in (three hypen-words in a single-sentence, wow! :)</P>
+<P>A <font face="Courier New, Courier, mono">BookmarkNode</font> represents a
+ connection with a database. It will be displayed by the <font face="Courier New, Courier, mono">BookmarView</font>
+ view. When you double-click on one of the bookmarks, the function <font face="Courier New, Courier, mono">MultiSQLServer.connect(current)</font>
+ willl be called. <font face="Courier New, Courier, mono">MultiSQLServer</font>
+ is a Singleton (a class that will have a single instance), so we can get the
+ instance of it with <font face="Courier New, Courier, mono">MultiSQLServer.getInstance()</font>.</P>
+<P>The <font face="Courier New, Courier, mono">connect()</font> function will
+ use the JDBC driver and connect to the database. After that, the BookmarkNode
+ will have its <font face="Courier New, Courier, mono">con</font> member assigned
+ (not null). After the connection, the function that is answering your double-clicking
+ (<font face="Courier New, Courier, mono">ConnectAction.run()</font>), will try
+ to get the tables, views, etc from that connection. To do that, it will call
+ <font face="Courier New, Courier, mono">BookmarkView.refreshBookmarkData()</font>,
+ that will query the database. As the procedure to get the tables may be different
+ for each database, the actual querying is delegated to another class <font face="Courier New, Courier, mono">SQLHelper</font>,
+ that will centralize that kind of procedures (the ones that depend on the type
+ of the database). The called function in this case is <font face="Courier New, Courier, mono">getTableList()</font>.
+ <font face="Courier New, Courier, mono">SQLHelper</font> is not a Singleton,
+ although it could be, but we don't really need an instance because the functions
+ are all static.</P>
+<P>The <font face="Courier New, Courier, mono">getTableList()</font> will try
+ to get the tables from the function <font face="Courier New, Courier, mono">MultiSQLServer.listTables()</font>,
+ if the jdbc adapter of the bookmark is generic. listTables will ask the jdbc
+ driver directly for the list of tables, using the <font face="Courier New, Courier, mono">DatabaseMetadata.getTables()
+ </font>call. If the adapter is not generic, it will use a SQL statement to get
+ the list of table names. This SQL statement will be of course different in every
+ database, so it will come from the <font face="Courier New, Courier, mono">DatabaseAdapter</font>
+ class. </P>
+<P>The <font face="Courier New, Courier, mono">DatabaseAdapter</font> class is
+ the one where you should put all the functions that will be different for each
+ database. Then for each database, you create an "adapter" class derived
+ from <font face="Courier New, Courier, mono">DatabaseAdapter</font>, and implement
+ all the necessary abstract functions. So you get a proper adapter using <font face="Courier New, Courier, mono">DatabaseAdapter
+ adapter = AdapterFactory.getInstance().getAdapter(current.getType())</font>,
+ and the returned adapter will have the proper type (always a derived type from
+ <font face="Courier New, Courier, mono">DatabaseAdapter</font>). Then calls
+ to the adapter object will be redirected to the proper function.</P>
+<P>The <font face="Courier New, Courier, mono">TableNode</font> objects generated
+ will have metadata, i.e. columns. That information is saved in an object of
+ class <font face="Courier New, Courier, mono">ObjectMetaData</font> in the TableNode
+ object. This ObjectMetaData class is part of the metadata package, that has
+ basically four classes:</P>
+<P><font face="Courier New, Courier, mono">MetaDataJDBCInterface</font> : Basically
+ takes care (through static functions) of passing the metadata from the jdbc
+ driver to the ObjectMetadata class.</P>
+<P><font face="Courier New, Courier, mono">MetaDataXMLInterface</font> : Handles
+ interface between an ObjectMetaData and XML storage. It can write an existing
+ metadata object to XML and generate a new ObjectMetaData from existing XML.</P>
+<P><font face="Courier New, Courier, mono">ObjectMetaData</font> : The class that
+ has all the metadata. Rather underdeveloped, one must add functions as needed.
+ The metadata is saved in the form of StringMatrix objects.</P>
+<P><font face="Courier New, Courier, mono">StringMatrix</font> : A matrix of strings.
+ Saves the results from the jdbc driver, usually given as ResultSet objects,
+ that are very similar in structure but sequential in nature (you access the
+ records one at a time). The first line of the matrix are the names of the columns,
+ and the rest hold the values.</P>
+<P> </P>
+<P><img src="structure.gif" width="749" height="313"></P>
+<P><br>
+</P>
+<P> </P>
+</BODY>
+</HTML>
\ No newline at end of file
--- /dev/null
+P.Code {\r display: block;\r text-align: left;\r text-indent: 0.00pt;\r margin-top: 0.000000pt;\r margin-bottom: 0.000000pt;\r margin-right: 0.000000pt;\r margin-left: 15pt;\r font-size: 10.000000pt;\r font-weight: medium;\r font-style: Regular;\r color: #4444CC;\r text-decoration: none;\r vertical-align: baseline;\r text-transform: none;\r font-family: "Courier New";\r}\rH6.CaptionFigColumn {\r display: block;\r text-align: left;\r text-indent: 0.000000pt;\r margin-top: 3.000000pt;\r margin-bottom: 11.000000pt;\r margin-right: 0.000000pt;\r margin-left: 0.000000pt;\r font-size: 9.000000pt;\r font-weight: medium;\r font-style: Italic;\r color: #000000;\r text-decoration: none;\r vertical-align: baseline;\r text-transform: none;\r font-family: "Arial";\r}\rP.Note {\r display: block;\r text-align: left;\r text-indent: 0pt;\r margin-top: 19.500000pt;\r margin-bottom: 19.500000pt;\r margin-right: 0.000000pt;\r margin-left: 30pt;\r font-size: 11.000000pt;\r font-weight: medium;\r font-style: Italic;\r color: #000000;\r text-decoration: none;\r vertical-align: baseline;\r text-transform: none;\r font-family: "Arial";\r}\rEM.UILabel {\r font-weight: Bold;\r font-style: Regular;\r text-decoration: none;\r vertical-align: baseline;\r text-transform: none;\r}\rEM.CodeName {\r font-weight: Bold;\r font-style: Regular;\r text-decoration: none;\r vertical-align: baseline;\r text-transform: none;\r font-family:"Courier New";\r}\r\r\r\r\r/* following font face declarations need to be removed for DBCS */\r\rbody, h1, h2, h3, h4, ,h5, h6, p, table, td, caption, th, ul, ol, dl, li, dd, dt {font-family: Arial, Helvetica, sans-serif; color: #000000}\rpre { font-family: Courier, monospace}\r\r/* end font face declarations */\r\r/* following font size declarations should be OK for DBCS */\rbody, h1, h2, h3, h4, h5, h6, p, table, td, caption, th, ul, ol, dl, li, dd, dt {font-size: 10pt; }\rpre { font-size: 10pt}\r\r/* end font size declarations */\r\rbody { background: #FFFFFF}\rh1 { font-size: 18pt; margin-top: 5; margin-bottom: 1 } \rh2 { font-size: 14pt; margin-top: 25; margin-bottom: 3 }\rh3 { font-size: 11pt; margin-top: 20; margin-bottom: 3 }\rh4 { font-size: 10pt; margin-top: 20; margin-bottom: 3; font-style: italic }\rp { margin-top: 10px; margin-bottom: 10px }\rpre { margin-left: 6; font-size: 9pt }\ra:link { color: #0000FF }\ra:hover { color: #000080 }\ra:visited { text-decoration: underline }\rul { margin-top: 0; margin-bottom: 10 }\rli { margin-top: 0; margin-bottom: 0 } \rli p { margin-top: 0; margin-bottom: 0 } \rol { margin-top: 0; margin-bottom: 10 }\rdl { margin-top: 0; margin-bottom: 10 }\rdt { margin-top: 0; margin-bottom: 0; font-weight: bold }\rdd { margin-top: 0; margin-bottom: 0 }\rstrong { font-weight: bold}\rem { font-style: italic}\rvar { font-style: italic}\rdiv.revision { border-left-style: solid; border-left-width: thin; \r border-left-color: #7B68EE; padding-left:5 }\rth { font-weight: bold }\r
\ No newline at end of file
--- /dev/null
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+ <meta http-equiv="content-type"
+ content="text/html; charset=ISO-8859-1">
+ <title>Making a Quantumdb connexion (bookmark)</title>
+</head>
+<body>
+Author: jparrai<br>
+Date: 28-03-2003<br>
+Subject: Making a Quantumdb connexion<br>
+<br>
+To connect to a database (create a bookmark in quantum) you use the <span
+ style="font-weight: bold;">New Bookmark</span> menu item that appears
+when right-clicking on the blank space in the <span
+ style="font-weight: bold;">Database Bookmarks</span> view.<br>
+<br>
+The data that the form asks of you is:<br>
+<br>
+<ul>
+ <li><big><b>Bookmark name:</b></big> Is your private name of the bookmark you
+ are creating. It will appear in the view after is created. For example <span
+ style="font-weight: bold;">Test</span>.</li>
+ <li><big><b>Username:</b></big> The username for accessing the database. For
+ example <span style="font-weight: bold;">SCOTT</span> for the classical Oracle
+ examples.</li>
+ <li><big><b>Password:</b></big> The password for that username. For example
+ <span
+ style="font-weight: bold;">TIGER</span> for the SCOTT user. If you leave the
+ password blank, it'll ask you for it when connection is attempted.This behaviour
+ can be customized.</li>
+ <li><big><b>Schema</b>: (optional):</big> The schema of the user. We can leave
+ it blank.</li>
+ <li><big><b>Connect</b>:</big> Connect string, the format is (for Oracle) <font
+ face="Geneva, Arial, Helvetica, sans-serif" size="2"><span
+ style="font-weight: bold;">jdbc:[database]:[type]:@[host]:[port]:[database]</span>,
+ for example, for an Oracle database called DEV based on the same computer
+ you could put <span style="font-weight: bold;">jdbc:oracle:thin:@localhost:1521:DEV</span>.</font></li>
+ <li><big><b>Driver</b>:</big> The driver name, it should be in the documentation
+ of the JDBC driver. For Oracle, is usually <span
+ style="font-weight: bold;">oracle.jdbc.OracleDriver</span> or <span
+ style="font-weight: bold;">oracle.jdbc.driver.OracleDriver </span> (Oracle before
+ version 9)</li>
+ <li><big><b>Type</b>:</big> The type of the database. It will be used by Quantum
+ to adapt the SQL queries to the particular incompatibilites of each. The generic
+ should work for most of the features, so if you don't find your database on
+ the drop-down, use the <span
+ style="font-weight: bold;">Generic SQL</span>.<br>
+ </li>
+ <li><big><b>Driver Filename</b>:</big> You can select the <span
+ style="font-weight: bold;">.jar</span> or <span
+ style="font-weight: bold;">.zip</span> file where the driver is located. For
+ example in Oracle is usually at <span
+ style="font-weight: bold;">C:\Oracle\jdbc\lib\classes12.jar</span>, being C:\Oracle
+ the installation directory of oracle.</li>
+</ul>
+<br>
+Other examples (only as orientation, your particular data may be
+different)<br>
+<br>
+For <span style="font-weight: bold;">MySql</span> (in Windows):<br>
+<pre>Connect: <span style="font-weight: bold;">jdbc:mysql://localhost/test</span><br>Driver: <span
+ style="font-weight: bold;">com.mysql.jdbc.Driver</span><br>Driver Filename: <span
+ style="font-weight: bold;">C:\mysql\jdbc\mysql-connector-java-2.0.4-bin.jar</span><br><br>For <span
+ style="font-weight: bold;">PostgreSql</span> (in Linux):<br><br>Connect: <span
+ style="font-weight: bold;">jdbc:postgresql://localhost/emsdevel</span><br>Driver: <span
+ style="font-weight: bold;">org.postgresql.Driver</span><br>driver filename: <span
+ style="font-weight: bold;">/opt/postgresql/share/java/postgresql.jar</span><br><br><br></pre>
+<br>
+</body>
+</html>
--- /dev/null
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+ <meta http-equiv="content-type"
+ content="text/html; charset=ISO-8859-1">
+ <title>Tutorial of developing and changing QuantumDb</title>
+</head>
+<body>
+Author: jparrai<br>
+Date: 28-03-2003<br>
+Subject: Tutorial of developing and changing QuantumDb<br>
+<br>
+To modify the quantumdb plug-in, first you get it to a development
+system, usually Eclipse itself.<br>
+<h3> 1. Getting the project from CVS.<br>
+</h3>
+First you go to <span style="font-weight: bold;">Open a Perspective</span>
+and open the <span style="font-weight: bold;">CVS repository exploring
+perspective</span>. It can be in the <span style="font-weight: bold;">Others...</span>.
+You get a perspective. You right-click on the <span
+ style="font-weight: bold;">CVS Repositories</span> view and create a <span
+ style="font-weight: bold;">New -> Repository Location...</span><br>
+The data to access quantum is:<br>
+<br>
+Host: <span style="font-weight: bold;">cvs.sourceforge.net</span><br>
+Repository Path: <span style="font-weight: bold;">/cvsroot/quantum</span><br>
+User: <span style="font-weight: bold;">anonymous</span><br>
+Password:<br>
+<br>
+There is no password for <span style="font-style: italic;">anonymous</span>.
+You can substitute the User and Password for you own, if you are
+registered in <a href="http://sourceforge.net">sourcefoge.net</a>. If
+you want developer access, remember to use <span
+ style="font-style: italic;">extssh</span> as the connexion type, so as
+to be able to update the cvs repository with your changes (that need a
+ssh connection in <a href="http://sourceforge.net">sourceforge</a>)<br>
+<br>
+After that, if you are connected to the Net, you will be able to get
+the project files. You will see a <span style="font-weight: bold;">HEAD</span>
+sub-item, a <span style="font-weight: bold;">Branches</span>, and a <span
+ style="font-weight: bold;">Versions</span>. You select the <span
+ style="font-weight: bold;">HEAD</span>, and then right-click onto <span
+ style="font-weight: bold;">quantum-plugin</span>. Then select <span
+ style="font-weight: bold;">Check Out As...</span>. You cannot check it
+out as a Project, because some files are not present, mainly the <span
+ style="font-style: italic;">.project</span> and <span
+ style="font-style: italic;">.classpath</span>.<br>
+<br>
+<h3> 2. Configuring the project.<br>
+</h3>
+So you "Check Out As..." and select an Plug-In project, call it as you
+wish, (I will use "com.quantum") and then select an Empty Plug In. If
+everything goes ok, you should end with a new project and about 1600
+errors. The errors are caused because you have now a default classpath,
+and the quantumdb project uses some plug-ins, so these plug-ins
+directories must be referenced.<br>
+<br>
+My classpath for Eclipse 2.0 is as follows:<br>
+<br>
+<span style="font-family: monospace;"><nobr> <?xml version="1.0"
+encoding="UTF-8"?></nobr></span><br style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr> <classpath></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="src" path="src"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="var" path="JRE_LIB" rootpath="JRE_SRCROOT"
+sourcepath="JRE_SRC"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="lib"</nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+
+path="C:/Parsec/eclipse/plugins/org.eclipse.core.boot_2.0.2/boot.jar"
+sourcepath="C:/Parsec/eclipse/plugins/org.eclipse.platform.source_2.0.2/src/org.eclipse.core.boot_2.0.2/bootsrc.zip"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="lib"</nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+
+path="C:/Parsec/eclipse/plugins/org.eclipse.core.runtime_2.0.2/runtime.jar"
+sourcepath="C:/Parsec/eclipse/plugins/org.eclipse.platform.source_2.0.2/src/org.eclipse.core.runtime_2.0.2/runtimesrc.zip"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="lib"</nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+
+path="C:/Parsec/eclipse/plugins/org.eclipse.core.resources_2.0.1/resources.jar"
+sourcepath="C:/Parsec/eclipse/plugins/org.eclipse.platform.source_2.0.2/src/org.eclipse.core.resources_2.0.1/resourcessrc.zip"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="lib"</nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+
+path="C:/Parsec/eclipse/plugins/org.eclipse.swt.win32_2.0.2/ws/win32/swt.jar"
+sourcepath="C:/Parsec/eclipse/plugins/org.eclipse.platform.win32.source_2.0.2/src/org.eclipse.swt.win32_2.0.2/ws/win32/swtsrc.zip"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="lib"</nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+
+path="C:/Parsec/eclipse/plugins/org.eclipse.ui_2.0.2/workbench.jar"
+sourcepath="C:/Parsec/eclipse/plugins/org.eclipse.platform.source_2.0.2/src/org.eclipse.ui_2.0.2/workbenchsrc.zip"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="lib"</nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+
+path="C:/Parsec/eclipse/plugins/org.eclipse.ui.win32_2.0.0/workbenchwin32.jar"</nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+ rootpath=""
+sourcepath="C:/Parsec/eclipse/plugins/org.eclipse.platform.win32.source_2.0.2/src/org.eclipse.ui.win32_2.0.0/workbenchwin32src.zip"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr>
+<classpathentry kind="output" path="bin"/></nobr></span><br
+ style="font-family: monospace;">
+<span style="font-family: monospace;"><nobr> </classpath></nobr></span><br
+ style="font-family: monospace;">
+<br>
+Where, as you can see, my Eclipse home is <span
+ style="font-family: monospace;">C:\Parsec\eclipse</span>. In any case,
+you need to reference those plug-ins you see below, from org.eclipse:<br>
+<ul>
+ <li> core.boot</li>
+ <li> core.runtime</li>
+ <li> core.resources</li>
+ <li> ui</li>
+ <li> swt.win32 (substitute by your platform)</li>
+ <li> ui.win32 (substitute by your platform)</li>
+</ul>
+<p><br>
+ Remember after changing manually the <span style="font-style: italic;">.classpath</span>
+ file that you have to <span style="font-weight: bold;">Refresh</span> the project
+ to take the changes in.<br>
+ <br>
+ If you want to reference those plug-ins using the workspace, select <span
+ style="font-weight: bold;">Properties </span>from the newly created <span
+ style="font-weight: bold;">com.quantum</span> project and go to <span
+ style="font-weight: bold;">Java Build Path</span>, then <span
+ style="font-weight: bold;">Libraries </span>tab, and select the <span
+ style="font-weight: bold;">.jar</span> files the project needs.<br>
+ <br>
+ It should now build without errors.<br>
+ <br>
+ In Eclipse 2.1 that won't work. Dependencies amongs plug-ins have changed and
+ instead of redoing all of them again I chose to use the new "classpath container"
+ facility. When I say that won't work I mean if linking against the 2.1 libraries.
+ If you link against the 2.0 libraries will work all right.<br>
+</p>
+<p>The libraries for 2.1 are as follows (I copy my classpath) :</p>
+<p><font face="Courier New, Courier, mono"><classpath><br>
+ <classpathentry kind="src" path="src"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.core.boot_2.1.0/boot.jar" sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.core.boot_2.1.0/bootsrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.core.runtime_2.1.0/runtime.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.core.runtime_2.1.0/runtimesrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.core.resources_2.1.0/resources.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.core.resources_2.1.0/resourcessrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.swt.win32_2.1.0/ws/win32/swt.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_WIN32_SOURCE_SRC/org.eclipse.swt.win32_2.1.0/ws/win32/swtsrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.ui_2.1.0/ui.jar" sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.ui_2.1.0/uisrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.text_2.1.0/text.jar" sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.text_2.1.0/textsrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.jface_2.1.0/jface.jar" sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.jface_2.1.0/jfacesrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.jface.text_2.1.0/jfacetext.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.jface.text_2.1.0/jfacetextsrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.ui.views_2.1.0/views.jar" sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.ui.views_2.1.0/viewssrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.ui.workbench_2.1.0/workbench.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.ui.workbench_2.1.0/workbenchsrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.ui.win32_2.1.0/workbenchwin32.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_WIN32_SOURCE_SRC/org.eclipse.ui.win32_2.1.0/workbenchwin32src.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.ui.workbench.texteditor_2.1.0/texteditor.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.ui.workbench.texteditor_2.1.0/texteditorsrc.zip"/><br>
+ <classpathentry kind="var"<br>
+ path="ECLIPSE_HOME/plugins/org.eclipse.ui.editors_2.1.0/editors.jar"
+ sourcepath="ORG_ECLIPSE_PLATFORM_SOURCE_SRC/org.eclipse.ui.editors_2.1.0/editorssrc.zip"/><br>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><br>
+ <classpathentry kind="output" path="bin"/><br>
+ </classpath><br>
+ <br>
+ </font></p>
+<h3>3. Running the project.<br>
+</h3>
+First go to <span style="font-weight: bold;">Window -> Preferences
+-> Plug-in Development -> Target Platform</span> and to select all
+the plug-ins that should be used when running a platform from the
+plug-in development. I select all of them not in the workspace because I
+don't want to resolve all the cross-references.<br>
+<br>
+Then go to <span style="font-weight: bold;">Run -> Run As ->
+Run-time Workbench</span>. If all is well, a new workbench should
+appear, that has you just-compiled quantum plug-in installed. To check
+it, open the quantumdb perspective (<span style="font-weight: bold;">Perspective
+Button -> Others... ->QuantumDb Perspective</span>), and see if
+it appears. This is not<br>
+the usual QuantumDb perspective, but the one you are developing. Of
+course, if you have made no change to the standard source, there is no
+difference. <br>
+<br>
+<h3>4. Making a small change.<br>
+</h3>
+To check that we are really using our modified QuantumDb, and not the
+standard, let's make a change. Open the <span
+ style="font-style: italic;">QuantumResources.properties</span> file,
+(in the <span style="font-weight: bold;">com.quantum</span> package),
+and modify the line<br>
+<br>
+<span style="font-family: monospace;"><nobr> bookmarkview.newBookmark =
+New Bookmark...</nobr></span><br>
+<br>
+to <br>
+<br>
+<span style="font-family: monospace;"><nobr> bookmarkview.newBookmark =
+Add New Bookmark...</nobr></span><br>
+<br>
+(for example)<br>
+<br>
+Then Run the testing workbench again, you can now use simply <span
+ style="font-weight: bold;">Ctrl+F11</span> to run the last launched
+environment. Now, in the bookmark view, when you right-click on it, it
+should show your modified string. So you are now ready to change the
+plug-in.<br>
+<h3> 5. Creating a .jar file.<br>
+</h3>
+<p>You may simply want to make a <span style="font-style: italic;">.jar</span>
+ file from some configuration taken from the CVS, so as to have the latest version
+ available to you. You have to follow the same instructions as before for installation.
+ When it's installed and built, select the <span style="font-weight: bold;">com.quantum</span>
+ project, right-click on it and select <span style="font-weight: bold;">Export</span>.<br>
+ <br>
+ In Eclipse 2.0: Select <span style="font-weight: bold;">jar File</span> and
+ then choose a directory. The name of the jar file should be <span
+ style="font-weight: bold;">Quantum.jar</span> as that's the name stated in the
+ <span style="font-style: italic;">plugin.xml</span> file.<br>
+ <br>
+ To install this jar file as a plug-in, create a directory called <span
+ style="font-style: italic;">com.quantum</span> in the directory <span
+ style="font-style: italic;">plugins</span> under your local Eclipse installation
+ directory. Copy the jar file to that directory, and uncompress it (without deleting
+ it) into that same directory. In fact, I think you only need the <span style="font-style: italic;">icons</span>
+ directory and the <span style="font-style: italic;">plugin.xlm</span>, but you
+ can leave the rest of the files so they feel not so alone.<br>
+ <br>
+ You close your Eclipse IDE and open it up again, and the QuantumDB perspective
+ should be available.<br>
+</p>
+<h3>6. Uploading the change to CVS.</h3>
+<p>(I copy directly from the Eclipse Help, so as to have all the info in the same
+ place) </p>
+<h4>Synchronizing with a CVS repository</h4>
+<p><br>
+ In the CVS team programming environment, there are two distinct processes involved
+ in synchronizing resources: updating with the latest changes from a branch and
+ committing to the branch. </p>
+<p>When you make changes in the Workbench, the resources are saved locally. Eventually
+ you will want to commit your changes to the branch so others can have access
+ to them. Meanwhile, others may have committed changes to the branch. You will
+ want to update your Workbench resources with their changes.</p>
+<p>Important!: It is preferable to update before committing, in case there are
+ conflicts with the resources in your Workbench and the resources currently in
+ the branch. </p>
+<p>The synchronize view contains filters to control whether you want to view only
+ incoming changes or outgoing changes. Incoming changes come from the branch.
+ If accepted, they will update the Workbench resource to the latest version currently
+ committed into the branch. Outgoing changes come from the Workbench. If committed,
+ they will change the branch resources to match those currently present in the
+ Workbench. </p>
+<p>Regardless of which mode (filter) you select, the Synchronize view always shows
+ you conflicts that arise when you have locally modified a resource for which
+ a more recent version is available in the branch. In this situation you can
+ choose to do one of three things: update the resource from the branch, commit
+ your version of the resource to the branch ,or merge your work with the changes
+ in the branch resource. Typically you will want to merge, as the other two options
+ will result in loss of work. </p>
+<p>(End of copy from Eclipse Help, there are lots more, just go there and have
+ a look) Basically to get all the changes since the last time you took the sources,
+ then accept all the files that have changed in the CVS and you haven't touched.
+ If there are some that you have touched and are also touched by someone else
+ at CVS then you have to inspect the changes, see if they conflict with yours,
+ and merge both until you have a working set. Then you can upload that "working"
+ set to CVS. That's more or less the idea.</p>
+</body>
+</html>
--- /dev/null
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+ <meta http-equiv="content-type"
+ content="text/html; charset=ISO-8859-1">
+ <title>Creating a QuantumDB Bookmark</title>
+ <link rel="stylesheet" href="book.css" charset="ISO-8859-1" type="text/css"></head>
+</head>
+<body>
+<h1>Creating a QuantumDB Bookmark</h1>
+<p>Author: jparrai<br>
+Date: 28-03-2003<br>
+<p>To connect to a database (create a bookmark in quantum) you use the <span
+ style="font-weight: bold;">New Bookmark</span> menu item that appears
+when right-clicking on the blank space in the <span
+ style="font-weight: bold;">Database Bookmarks</span> view.</p>
+
+<img src="images/newbookmark_menu.gif" />
+
+<p>Once this menu item is selected, you will see the "New Bookmark" wizard:</p>
+
+<img src="images/newbookmark_wizard.gif" />
+
+<p>The data that the form asks of you is:
+<ul>
+ <li><b>Bookmark name:</b> Is your private name of the bookmark you
+ are creating. It will appear in the view after is created. For example <span
+ style="font-weight: bold;">Test</span>.</li>
+ <li><b>Username:</b> The username for accessing the database. For
+ example <span style="font-weight: bold;">SCOTT</span> for the classical Oracle
+ examples.</li>
+ <li><b>Password:</b> The password for that username. For example
+ "TIGER" for the "SCOTT" user.</li>
+ <li><b>Prompt for Password:</b> Check this box if you want to be prompted for a password
+ every time you try to connect to the database.</li>
+ <li><b>Schema</b>: (optional): The schema of the user. We can leave
+ it blank.</li>
+ <li><b>Connect</b>: Connect string, the format is (for Oracle) <font
+ face="Geneva, Arial, Helvetica, sans-serif" size="2"><span
+ style="font-weight: bold;">jdbc:[database]:[type]:@[host]:[port]:[database]</span>,
+ for example, for an Oracle database called DEV based on the same computer
+ you could put <span style="font-weight: bold;">jdbc:oracle:thin:@localhost:1521:DEV</span>.</font></li>
+ <li><b>Driver</b>: The driver name, it should be in the documentation
+ of the JDBC driver. For Oracle, is usually <span
+ style="font-weight: bold;">oracle.jdbc.OracleDriver</span> or <span
+ style="font-weight: bold;">oracle.jdbc.driver.OracleDriver </span> (Oracle before
+ version 9)</li>
+ <li><b>Type</b>: The type of the database. It will be used by Quantum
+ to adapt the SQL queries to the particular incompatibilites of each. The generic
+ should work for most of the features, so if you don't find your database on
+ the drop-down, use the <span
+ style="font-weight: bold;">Generic SQL</span>.<br>
+ </li>
+ <li><b>Driver Filename</b>: You can select the <span
+ style="font-weight: bold;">.jar</span> or <span
+ style="font-weight: bold;">.zip</span> file where the driver is located. For
+ example in Oracle is usually at <span
+ style="font-weight: bold;">C:\Oracle\jdbc\lib\classes12.jar</span>, being C:\Oracle
+ the installation directory of oracle.</li>
+</ul>
+<p>Other examples (only as orientation, your particular data may be
+different)<br>
+<p>
+For <span style="font-weight: bold;">MySql</span> (in Windows):</p>
+<pre>Connect: <span style="font-weight: bold;">jdbc:mysql://localhost/test</span><br>Driver: <span
+ style="font-weight: bold;">com.mysql.jdbc.Driver</span><br>Driver Filename: <span
+ style="font-weight: bold;">C:\mysql\jdbc\mysql-connector-java-2.0.4-bin.jar</span><br>
+</pre>
+ <p>For <span
+ style="font-weight: bold;">PostgreSql</span> (in Linux):</p>
+<pre>
+ <br>Connect: <span
+ style="font-weight: bold;">jdbc:postgresql://localhost/emsdevel</span><br>Driver: <span
+ style="font-weight: bold;">org.postgresql.Driver</span><br>driver filename: <span
+ style="font-weight: bold;">/opt/postgresql/share/java/postgresql.jar</span></pre>
+</body>
+</html>
--- /dev/null
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>Opening the Quantum DB Perspective</title>
+ <link rel="stylesheet" href="book.css" charset="ISO-8859-1" type="text/css"></head>
+</head>
+
+<body>
+<h1>Opening the Quantum DB Perspective</h1>
+<p>Typically, the first thing you do with the Quantum plug-in is to open the Quantum DB Perspective.
+Go to <code>Window -> Open Perspective -> Other...</code> to get the "Select Perspective"
+dialog.</p>
+
+<img src="images/open_perspective.gif"/>
+
+<p>Choose the "Quantum DB Perspective" option from the list:</p>
+
+<img src="images/select_perspective_dialog.gif" />
+
+<p>The Quantum DB Perspective looks like this:</p>
+
+<img src="images/quantum_perspective.gif" />
+
+<p>The first time you open the Quantum DB perspective, you won't see any bookmarks defined.
+</body>
+</html>
\ No newline at end of file
--- /dev/null
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>Quantum DB User's Guide</title>
+ <link rel="stylesheet" href="book.css" charset="ISO-8859-1" type="text/css"></head>
+</head>
+
+<body>
+<img src="images/logo.gif" />
+<h1>QuantumDB User's Guide</h1>
+<p>Quantum is a database access plugin for Eclipse.
+It can be used to connect to databases, list tables and views, and issue ad-hoc queries.
+<p>The Quantum <a href="http://quantum.sourceforge.net/">home page</a> is hosted by Sourceforge.
+</body>
+</html>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<?NLS TYPE="org.eclipse.help.toc"?>
+
+<toc label="QuantumDB User's Guide" topic="doc/index.html">
+ <topic label="Getting Started">
+ <topic label="Opening the Quantum DB Perspective" href="doc/getting_started_perspective.html" />
+ <topic label="Creating bookmarks" href="doc/getting_started_connections.html" />
+ </topic>
+</toc>
--- /dev/null
+P7 332
+#IMGINFO:16x16 Greyscale (883 bytes)
+#END_OF_COMMENTS
+16 16 255
+I$IIÛ¶¶¶IH%IÛ¶¶ÚI$IIÛ¶¶¶IH%IÛ¶¶ÚI$IImIIIIHJl%Û¶¶I$II¶’’¶‘’¶’$Û¶ÛÛ¶¶H“H%H%IH“HI$IÛ¶¶H“µ’’¶’’‘II$IÛ¶¶H“H%H%IH“HI$IÛ¶¶H“µ’’¶’’‘II$II$II¶%H%H%I¶$Û¶ÛI$II¶’’¶‘’¶’$Û¶ÛI$II¶%H%H%I¶$Û¶ÛI$II¶’’¶‘’¶’$Û¶ÛÛ¶¶H“H%H%IH“HI$IÛ¶¶H“µ’’¶’’‘II$IÛ¶¶HI%IHÛ¶·¶H%IHÛ¶¶¶I$IIÛ¶¶Ú%H%I
\ No newline at end of file
--- /dev/null
+Quick and Dirty Install Instructions:
+1. Download and unpack eclipse 2.1.1 into a directory [e.g. C:\Test\eclipse]
+2. Download Quantum
+3. Unzip quantum into the parent directory of eclipse [e.g. C:\Test]. The zip file has the relative path
+ eclipse/plugins/com.quantum.Quantum_2.2.0 So if you have called the eclipse directory by any other
+ name you should unzip into a temporary directory, take the com.quantum.Quantum_2.2.0 directory,
+ and copy it into your plugins directory.
+4. Launch eclipse. You need java 1.4 or higher to run Quantum. So if you don't have it installed,
+ you can install it to use only with Eclipse. Install it into some directory, and run eclipse with
+ the -vm parameter:
+
+ Eclipse.exe -d C:\Test\workspace -vm C:\java\jre1.4.2\bin\javaw.exe
+
+ or
+
+ Eclipse.exe -d /home/panic/workspace -vm /usr/java/bin/
+
+5. Open the Quantum DB Perspective [Go to Windows -> Open Perspective -> Other and select Quantum DB Perspective]
+6. Right click any where on the Bookmark view and select "New Bookmark..."
+7. If you need more instructions, check the documentation (/doc directory under com.quantum.Quantum_2.2.0), and
+ the online documentation in the sourceforge page (http://sourceforge.net/docman/?group_id=7746).
+
+8. If you update to Quantum 2.2.3 from a previous version, you may get warnings about not being able
+ to restore some views. Close your Quantum perspective and re-open it.
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin
+ id="com.quantum.Quantum"
+ name="%quantum.name"
+ version="2.2.4"
+ provider-name="Tom Schneider"
+ class="com.quantum.QuantumPlugin">
+
+ <runtime>
+ <library name="quantum.jar"/>
+ </runtime>
+ <requires>
+ <import plugin="org.eclipse.core.boot"/>
+ <import plugin="org.eclipse.core.runtime"/>
+ <import plugin="org.eclipse.core.resources"/>
+ <import plugin="org.eclipse.swt"/>
+ <import plugin="org.eclipse.ui"/>
+ <import plugin="org.eclipse.ui.ide"/>
+ <import plugin="org.eclipse.text"/>
+ <import plugin="org.eclipse.jface.text"/>
+ <import plugin="org.apache.xerces"/>
+ <import plugin="org.eclipse.core.runtime.compatibility"/>
+ <import plugin="org.eclipse.ui.editors"/>
+ <import plugin="org.eclipse.ui.workbench.texteditor"/>
+ </requires>
+
+
+<!-- Pop-up Menus -->
+ <extension
+ point="org.eclipse.ui.popupMenus">
+ <objectContribution
+ objectClass="org.eclipse.core.resources.IFile"
+ nameFilter="*.sql"
+ id="com.quantum">
+ <menu
+ label="Quantum"
+ path="additions"
+ id="com.quantum.menu1">
+ <separator
+ name="group1">
+ </separator>
+ </menu>
+ <action
+ label="Execute Against..."
+ class="com.quantum.actions.ExecuteAgainstAction"
+ menubarPath="com.quantum.menu1/group1"
+ enablesFor="1"
+ id="com.quantum.actions.ExecuteAgainstAction">
+ </action>
+ </objectContribution>
+ </extension>
+<!-- <extension
+ point="org.eclipse.ui.actionSets">
+ <actionSet
+ label="Execute Query"
+ visible="true"
+ id="com.quantum.actionssets">
+ <action
+ label="Execute Query"
+ icon="icons/play.gif"
+ class="com.quantum.actions.ExecuteAction"
+ tooltip="Execute Query"
+ toolbarPath="quantumGroup"
+ id="com.quantum.actions.ExecuteAction">
+ </action>
+ </actionSet>
+ </extension> -->
+ <extension
+ point="org.eclipse.ui.commands">
+ <category
+ name="%category.name"
+ description="%category.description"
+ id="com.quantum.category">
+ </category>
+ <command
+ name="%command.execute.name"
+ category="com.quantum.category"
+ description="%command.execute.description"
+ id="com.quantum.actions.ExecuteAction">
+ </command>
+ <keyBinding
+ string="Ctrl+Shift+Q"
+ scope="com.quantum.view.sql"
+ command="com.quantum.actions.ExecuteAction"
+ configuration="org.eclipse.ui.defaultAcceleratorConfiguration">
+ </keyBinding>
+ <scope
+ name="%scope.name"
+ description="%scope.description"
+ id="com.quantum.view.sql">
+ </scope>
+ </extension>
+<!-- Perspective -->
+ <extension
+ point="org.eclipse.ui.perspectives">
+ <perspective
+ name="%perspective.name"
+ icon="icons/quantum-ng.gif"
+ class="com.quantum.perspective.DBPerspective"
+ id="com.quantum.dbperspective">
+ </perspective>
+ </extension>
+<!-- Views -->
+ <extension
+ point="org.eclipse.ui.views">
+ <category
+ name="%category.name"
+ id="com.quantum.views">
+ </category>
+ <view
+ name="%sqllogview.name"
+ icon="icons/log.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.SQLLogView"
+ id="com.quantum.view.logview">
+ </view>
+ <view
+ name="%tableview.name"
+ icon="icons/table.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.tableview.TableView"
+ id="com.quantum.view.tableview.TableView">
+ </view>
+ <view
+ name="%bookmarkview.name"
+ icon="icons/bookmarks.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.bookmark.BookmarkView"
+ id="com.quantum.view.bookmarkview">
+ </view>
+ <view
+ name="%subsetview.name"
+ icon="icons/subset.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.subset.SubsetView"
+ id="com.quantum.view.subsetview">
+ </view>
+ <view
+ name="%sqlqueryview.name"
+ icon="icons/script.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.SQLQueryView"
+ id="com.quantum.view.sqlqueryview">
+ </view>
+ </extension>
+<!-- Editors -->
+ <extension
+ point="org.eclipse.ui.editors">
+ <editor
+ name="Quantum SQL Editor"
+ extensions="sql,ddl"
+ icon="icons/script.gif"
+ class="com.quantum.editors.SQLEditor"
+ contributorClass="org.eclipse.ui.texteditor.BasicTextEditorActionContributor"
+ id="com.quantum.editors.SQLEditor">
+ </editor>
+ <editor
+ name="Table Data Editor"
+ icon="icons/greentable.gif"
+ class="com.quantum.editors.dataeditor.DataEditor"
+ id="com.quantum.editors.dataeditor.DataEditor">
+ </editor>
+ </extension>
+<!-- Preferences -->
+ <extension
+ point="org.eclipse.ui.preferencePages">
+ <page
+ name="Quantum DB"
+ class="com.quantum.preferences.GlobalPreferences"
+ id="com.quantum.preferences">
+ </page>
+ <page
+ name="SQL Editor"
+ category="com.quantum.preferences"
+ class="com.quantum.preferences.SQLEditorPreferences"
+ id="com.quantum.preferences.editor">
+ </page>
+ <page
+ name="Copy"
+ category="com.quantum.preferences"
+ class="com.quantum.preferences.CopyPreferences"
+ id="com.quantum.preferences.copy">
+ </page>
+ <page
+ name="Custom Copy 1"
+ category="com.quantum.preferences.copy"
+ class="com.quantum.preferences.CustomCopyPreferences"
+ id="com.quantum.preferences.customcopy">
+ </page>
+ <page
+ name="Custom Copy 2"
+ category="com.quantum.preferences.copy"
+ class="com.quantum.preferences.CustomCopyPreferences2"
+ id="com.quantum.preferences.customcopy2">
+ </page>
+ <page
+ name="Custom Copy 3"
+ category="com.quantum.preferences.copy"
+ class="com.quantum.preferences.CustomCopyPreferences3"
+ id="com.quantum.preferences.customcopy3">
+ </page>
+ </extension>
+<!-- Menu for Bookmark View -->
+ <extension
+ point="org.eclipse.ui.viewActions">
+ <viewContribution
+ targetID="com.quantum.view.bookmarkview"
+ id="com.quantum.view.bookmarkview.menu">
+<!-- Export Bookmarks -->
+ <action
+ label="%bookmarkview.exportbookmarks"
+ icon="icons/export.gif"
+ class="com.quantum.actions.ExportBookmarksAction"
+ tooltip="Exports bookmarks to a file"
+ menubarPath="additions"
+ id="com.quantum.action.importbookmarks">
+ </action>
+<!-- Import Bookmarks -->
+ <action
+ label="%bookmarkview.importboomarks "
+ icon="icons/import.gif"
+ class="com.quantum.actions.ImportBookmarksAction"
+ tooltip="Imports bookmarks from a file"
+ menubarPath="additions"
+ id="com.quantum.action.importbookmarks">
+ </action>
+ </viewContribution>
+ </extension>
+ <extension
+ point="org.eclipse.ui.perspectiveExtensions">
+ <perspectiveExtension
+ targetID="org.eclipse.ui.resourcePerspective">
+ </perspectiveExtension>
+ </extension>
+<!-- Property Pages -->
+ <extension
+ point="org.eclipse.ui.propertyPages">
+ <page
+ objectClass="com.quantum.view.bookmark.TreeNode"
+ name="Database"
+ class="com.quantum.properties.DatabaseInformationPropertyPage"
+ nameFilter="*"
+ id="com.quantum.properties.DatabaseInformationPropertyPage">
+ </page>
+ <page
+ objectClass="com.quantum.view.bookmark.BookmarkNode"
+ name="Bookmark"
+ class="com.quantum.properties.BookmarkPropertyPage"
+ nameFilter="*"
+ id="com.quantum.properties.BookmarkPropertyPage">
+ </page>
+ <page
+ objectClass="com.quantum.view.bookmark.BookmarkNode"
+ name="Schemas"
+ class="com.quantum.properties.SchemaPropertyPage"
+ nameFilter="*"
+ id="com.quantum.properties.SchemaPropertyPage">
+ </page>
+ <page
+ objectClass="com.quantum.view.bookmark.EntityNode"
+ name="Tables, Views and Sequences"
+ class="com.quantum.properties.EntityPropertyPage"
+ nameFilter="*"
+ id="com.quantum.properties.EntityPropertyPage">
+ </page>
+ </extension>
+ <extension
+ point="org.eclipse.ui.exportWizards">
+ <wizard
+ name="Export to Quantum Bookmark File"
+ icon="./icons/bookmarkfile.gif"
+ class="com.quantum.wizards.ExportBookmarkWizard"
+ id="com.quantum.wizards.ExportBookmarkWizard">
+ <description>
+ A wizard that exports the list of database bookmarks to a Quantum bookmark file.
+ </description>
+ </wizard>
+ <wizard
+ name="Export to Torque Configuration File"
+ icon="./icons/torque.gif"
+ class="com.quantum.wizards.ExportTorqueWizard"
+ id="com.quantum.wizards.ExportTorqueWizard">
+ <description>
+ A wizard that exports the database structure to a Torque-compatible XML file.
+ </description>
+ <selection
+ class="com.quantum.view.bookmark.BookmarkNode">
+ </selection>
+ </wizard>
+ </extension>
+ <extension
+ point="org.eclipse.help.toc">
+ <toc
+ file="doc/toc.xml"
+ primary="true">
+ </toc>
+ </extension>
+
+</plugin>
--- /dev/null
+quantum.name = Quantum DB Utility
+perspective.name = Quantum DB Perspective
+sqllogview.name = Quantum SQL Log
+tableview.name = Quantum Table View
+sqlqueryview.name = Quantum SQL Query Editor
+bookmarkview.name = Database Bookmarks
+bookmarkview.importboomarks = Import Bookmarks
+bookmarkview.exportbookmarks = Export Bookmarks
+subsetview.name = Subsets
+category.name = QuantumDB
+category.description = Quantum Database Tools
+scope.name = Quantum UI Scope
+scope.description = Quantum UI Scope
+command.execute.name = Execute SQL
+command.execute.description = Execute the SQL statements against a database bookmark
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+<plugin
+ id="com.quantum.Quantum"
+ name="%quantum.name"
+ version="2.3.0"
+ provider-name="Tom Schneider"
+ class="com.quantum.QuantumPlugin">
+
+ <runtime>
+ <library name="quantum.jar"/>
+ </runtime>
+ <requires>
+ <import plugin="org.eclipse.core.runtime.compatibility"/>
+ <import plugin="org.eclipse.ui.ide"/>
+ <import plugin="org.eclipse.ui.views"/>
+ <import plugin="org.eclipse.jface.text"/>
+ <import plugin="org.eclipse.ui.workbench.texteditor"/>
+ <import plugin="org.eclipse.ui.editors"/>
+ <import plugin="org.eclipse.core.boot"/>
+ <import plugin="org.eclipse.core.runtime"/>
+ <import plugin="org.eclipse.core.resources"/>
+ <import plugin="org.eclipse.swt"/>
+ <import plugin="org.eclipse.ui"/>
+ <import plugin="org.apache.xerces"/>
+ </requires>
+
+
+ <extension-point id="metadata" name="Metadata" schema="schema/metadata.exsd"/>
+ <extension-point id="data" name="Data" schema="schema/data.exsd"/>
+
+<!-- Pop-up Menus -->
+ <extension
+ point="org.eclipse.ui.popupMenus">
+ <objectContribution
+ objectClass="org.eclipse.core.resources.IFile"
+ nameFilter="*.sql"
+ id="com.quantum">
+ <menu
+ label="Quantum"
+ path="additions"
+ id="com.quantum.menu1">
+ <separator
+ name="group1">
+ </separator>
+ </menu>
+ <action
+ label="Execute Against..."
+ class="com.quantum.actions.ExecuteAgainstAction"
+ menubarPath="com.quantum.menu1/group1"
+ enablesFor="1"
+ id="com.quantum.actions.ExecuteAgainstAction">
+ </action>
+ </objectContribution>
+ </extension>
+<!-- <extension
+ point="org.eclipse.ui.actionSets">
+ <actionSet
+ label="Execute Query"
+ visible="true"
+ id="com.quantum.actionssets">
+ <action
+ label="Execute Query"
+ icon="icons/play.gif"
+ class="com.quantum.actions.ExecuteAction"
+ tooltip="Execute Query"
+ toolbarPath="quantumGroup"
+ id="com.quantum.actions.ExecuteAction">
+ </action>
+ </actionSet>
+ </extension> -->
+ <extension
+ point="org.eclipse.ui.commands">
+ <category
+ name="%category.name"
+ description="%category.description"
+ id="com.quantum.category">
+ </category>
+ <command
+ name="%command.execute.name"
+ description="%command.execute.description"
+ category="com.quantum.category"
+ id="com.quantum.actions.ExecuteAction">
+ </command>
+ <keyBinding
+ string="Ctrl+Shift+Q"
+ scope="com.quantum.view.sql"
+ command="com.quantum.actions.ExecuteAction"
+ configuration="org.eclipse.ui.defaultAcceleratorConfiguration">
+ </keyBinding>
+ <scope
+ name="%scope.name"
+ description="%scope.description"
+ id="com.quantum.view.sql">
+ </scope>
+ </extension>
+<!-- Perspective -->
+ <extension
+ point="org.eclipse.ui.perspectives">
+ <perspective
+ name="%perspective.name"
+ icon="icons/quantum-ng.gif"
+ class="com.quantum.perspective.DBPerspective"
+ id="com.quantum.dbperspective">
+ </perspective>
+ </extension>
+<!-- Views -->
+ <extension
+ point="org.eclipse.ui.views">
+ <category
+ name="%category.name"
+ id="com.quantum.views">
+ </category>
+ <view
+ name="%sqllogview.name"
+ icon="icons/log.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.SQLLogView"
+ id="com.quantum.view.logview">
+ </view>
+ <view
+ name="%tableview.name"
+ icon="icons/table.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.tableview.TableView"
+ id="com.quantum.view.tableview.TableView">
+ </view>
+ <view
+ name="%bookmarkview.name"
+ icon="icons/bookmarks.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.bookmark.BookmarkView"
+ id="com.quantum.view.bookmarkview">
+ </view>
+ <view
+ name="%subsetview.name"
+ icon="icons/subset.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.subset.SubsetView"
+ id="com.quantum.view.subsetview">
+ </view>
+ <view
+ name="%sqlqueryview.name"
+ icon="icons/script.gif"
+ category="com.quantum.views"
+ class="com.quantum.view.SQLQueryView"
+ id="com.quantum.view.sqlqueryview">
+ </view>
+ </extension>
+<!-- Editors -->
+ <extension
+ point="org.eclipse.ui.editors">
+ <editor
+ name="Quantum SQL Editor"
+ icon="icons/script.gif"
+ extensions="sql,ddl"
+ contributorClass="org.eclipse.ui.texteditor.BasicTextEditorActionContributor"
+ class="com.quantum.editors.SQLEditor"
+ id="com.quantum.editors.SQLEditor">
+ </editor>
+ <editor
+ name="Table Data Editor"
+ icon="icons/greentable.gif"
+ class="com.quantum.editors.dataeditor.DataEditor"
+ id="com.quantum.editors.dataeditor.DataEditor">
+ </editor>
+ </extension>
+<!-- Preferences -->
+ <extension
+ point="org.eclipse.ui.preferencePages">
+ <page
+ name="Quantum DB"
+ class="com.quantum.preferences.GlobalPreferences"
+ id="com.quantum.preferences">
+ </page>
+ <page
+ name="SQL Editor"
+ category="com.quantum.preferences"
+ class="com.quantum.preferences.SQLEditorPreferences"
+ id="com.quantum.preferences.editor">
+ </page>
+ <page
+ name="Copy"
+ category="com.quantum.preferences"
+ class="com.quantum.preferences.CopyPreferences"
+ id="com.quantum.preferences.copy">
+ </page>
+ <page
+ name="Custom Copy 1"
+ category="com.quantum.preferences.copy"
+ class="com.quantum.preferences.CustomCopyPreferences"
+ id="com.quantum.preferences.customcopy">
+ </page>
+ <page
+ name="Custom Copy 2"
+ category="com.quantum.preferences.copy"
+ class="com.quantum.preferences.CustomCopyPreferences2"
+ id="com.quantum.preferences.customcopy2">
+ </page>
+ <page
+ name="Custom Copy 3"
+ category="com.quantum.preferences.copy"
+ class="com.quantum.preferences.CustomCopyPreferences3"
+ id="com.quantum.preferences.customcopy3">
+ </page>
+ </extension>
+<!-- Menu for Bookmark View -->
+ <extension
+ point="org.eclipse.ui.viewActions">
+ <viewContribution
+ targetID="com.quantum.view.bookmarkview"
+ id="com.quantum.view.bookmarkview.menu">
+<!-- Export Bookmarks -->
+ <action
+ label="%bookmarkview.exportbookmarks"
+ icon="icons/export.gif"
+ tooltip="Exports bookmarks to a file"
+ class="com.quantum.actions.ExportBookmarksAction"
+ menubarPath="additions"
+ id="com.quantum.action.importbookmarks">
+ </action>
+<!-- Import Bookmarks -->
+ <action
+ label="%bookmarkview.importboomarks "
+ icon="icons/import.gif"
+ tooltip="Imports bookmarks from a file"
+ class="com.quantum.actions.ImportBookmarksAction"
+ menubarPath="additions"
+ id="com.quantum.action.importbookmarks">
+ </action>
+ </viewContribution>
+ </extension>
+ <extension
+ point="org.eclipse.ui.perspectiveExtensions">
+ <perspectiveExtension
+ targetID="org.eclipse.ui.resourcePerspective">
+ </perspectiveExtension>
+ </extension>
+<!-- Property Pages -->
+ <extension
+ point="org.eclipse.ui.propertyPages">
+ <page
+ objectClass="com.quantum.view.bookmark.TreeNode"
+ name="Database"
+ nameFilter="*"
+ class="com.quantum.properties.DatabaseInformationPropertyPage"
+ id="com.quantum.properties.DatabaseInformationPropertyPage">
+ </page>
+ <page
+ objectClass="com.quantum.view.bookmark.BookmarkNode"
+ name="Bookmark"
+ nameFilter="*"
+ class="com.quantum.properties.BookmarkPropertyPage"
+ id="com.quantum.properties.BookmarkPropertyPage">
+ </page>
+ <page
+ objectClass="com.quantum.view.bookmark.BookmarkNode"
+ name="Schemas"
+ nameFilter="*"
+ class="com.quantum.properties.SchemaPropertyPage"
+ id="com.quantum.properties.SchemaPropertyPage">
+ </page>
+ <page
+ objectClass="com.quantum.view.bookmark.EntityNode"
+ name="Tables, Views and Sequences"
+ nameFilter="*"
+ class="com.quantum.properties.EntityPropertyPage"
+ id="com.quantum.properties.EntityPropertyPage">
+ </page>
+ </extension>
+ <extension
+ point="org.eclipse.ui.exportWizards">
+ <wizard
+ name="Export to Quantum Bookmark File"
+ icon="./icons/bookmarkfile.gif"
+ class="com.quantum.wizards.ExportBookmarkWizard"
+ id="com.quantum.wizards.ExportBookmarkWizard">
+ <description>
+ A wizard that exports the list of database bookmarks to a Quantum bookmark file.
+ </description>
+ </wizard>
+ <wizard
+ name="Export to Torque Configuration File"
+ icon="./icons/torque.gif"
+ class="com.quantum.wizards.ExportTorqueWizard"
+ id="com.quantum.wizards.ExportTorqueWizard">
+ <description>
+ A wizard that exports the database structure to a Torque-compatible XML file.
+ </description>
+ <selection
+ class="com.quantum.view.bookmark.BookmarkNode">
+ </selection>
+ </wizard>
+ </extension>
+ <extension
+ point="org.eclipse.help.toc">
+ <toc
+ file="doc/toc.xml"
+ primary="true">
+ </toc>
+ </extension>
+
+</plugin>
--- /dev/null
+<?xml version='1.0' encoding='UTF-8'?>\r
+<!-- Schema file written by PDE -->\r
+<schema targetNamespace="com.quantum.Quantum">\r
+<annotation>\r
+ <appInfo>\r
+ <meta.schema plugin="com.quantum.Quantum" id="data" name="Data"/>\r
+ </appInfo>\r
+ <documentation>\r
+ This extension point allow other plug-ins to act on data information extracted by Quantum.
+For each registered extension, Quantum will add a menu entry in the context menu of the Table View.\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <element name="extension">\r
+ <complexType>\r
+ <sequence>\r
+ <element ref="dataActor" minOccurs="1" maxOccurs="unbounded"/>\r
+ </sequence>\r
+ <attribute name="point" type="string" use="required">\r
+ <annotation>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ <attribute name="id" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ <attribute name="name" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ </complexType>\r
+ </element>\r
+\r
+ <element name="dataActor">\r
+ <complexType>\r
+ <attribute name="label" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ The label of the dataActor. Will be used to appear in the context menu.\r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ <attribute name="class" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ The class acting on the data. Will be supplied by the external plug-in, not by Quantum.\r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ </complexType>\r
+ </element>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="since"/>\r
+ </appInfo>\r
+ <documentation>\r
+ 2.3\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="examples"/>\r
+ </appInfo>\r
+ <documentation>\r
+ [Enter extension point usage example here.]\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="apiInfo"/>\r
+ </appInfo>\r
+ <documentation>\r
+ [Enter API information here.]\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="implementation"/>\r
+ </appInfo>\r
+ <documentation>\r
+ [Enter information about supplied implementation of this extension point.]\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="copyright"/>\r
+ </appInfo>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+\r
+</schema>\r
--- /dev/null
+<?xml version='1.0' encoding='UTF-8'?>\r
+<!-- Schema file written by PDE -->\r
+<schema targetNamespace="com.quantum.Quantum">\r
+<annotation>\r
+ <appInfo>\r
+ <meta.schema plugin="com.quantum.Quantum" id="metadata" name="Metadata"/>\r
+ </appInfo>\r
+ <documentation>\r
+ This extension point allow other plug-ins to act on metadata information extracted by Quantum.
+For each registered extension, Quantum will add a menu entry in the context menu of the Bookmarks View.\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <element name="extension">\r
+ <complexType>\r
+ <sequence>\r
+ <element ref="metadataActor" minOccurs="1" maxOccurs="unbounded"/>\r
+ </sequence>\r
+ <attribute name="point" type="string" use="required">\r
+ <annotation>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ <attribute name="id" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ <attribute name="name" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ </complexType>\r
+ </element>\r
+\r
+ <element name="metadataActor">\r
+ <complexType>\r
+ <attribute name="label" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ The label of the metadataActor. Will be used to appear in the context menu.\r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ <attribute name="class" type="string">\r
+ <annotation>\r
+ <documentation>\r
+ The class acting on the metadata. Will be supplied by the external plug-in, not by Quantum.\r
+ </documentation>\r
+ </annotation>\r
+ </attribute>\r
+ </complexType>\r
+ </element>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="since"/>\r
+ </appInfo>\r
+ <documentation>\r
+ 2.3\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="examples"/>\r
+ </appInfo>\r
+ <documentation>\r
+ [Enter extension point usage example here.]\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="apiInfo"/>\r
+ </appInfo>\r
+ <documentation>\r
+ [Enter API information here.]\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="implementation"/>\r
+ </appInfo>\r
+ <documentation>\r
+ [Enter information about supplied implementation of this extension point.]\r
+ </documentation>\r
+ </annotation>\r
+\r
+ <annotation>\r
+ <appInfo>\r
+ <meta.section type="copyright"/>\r
+ </appInfo>\r
+ <documentation>\r
+ \r
+ </documentation>\r
+ </annotation>\r
+\r
+</schema>\r
--- /dev/null
+/* Created on Jan 19, 2004 */
+package com.quantum.util;
+
+import java.lang.reflect.Method;
+
+import junit.framework.TestCase;
+
+/**
+ * @author holmesbc
+ */
+public class StringUtilTest extends TestCase {
+ public void testSubstituteString() throws Exception {
+
+ String sample = "This is a test of ${variable} substitution.";
+ String replaceAll = replaceAll(sample, "\\$\\{variable\\}", "parameter");
+
+ assertEquals("replaceAll", "This is a test of parameter substitution.", replaceAll);
+ System.out.println(StringUtil.substituteString(sample, "${variable}", "parameter"));
+ assertEquals("substitute String", replaceAll, StringUtil.substituteString(sample, "${variable}", "parameter"));
+ }
+
+ public void testSubstituteStringAtEnd() throws Exception {
+
+ String sample = "Substitute ${variable}";
+ String replaceAll = replaceAll(sample, "\\$\\{variable\\}", "parameter");
+
+ System.out.println(StringUtil.substituteString(sample, "${variable}", "parameter"));
+ assertEquals("substitute String", replaceAll, StringUtil.substituteString(sample, "${variable}", "parameter"));
+ }
+
+ public void testSubstituteStringAtBeginning() throws Exception {
+
+ String sample = "${variable} substitution";
+ String replaceAll = replaceAll(sample, "\\$\\{variable\\}", "parameter");
+
+ System.out.println(StringUtil.substituteString(sample, "${variable}", "parameter"));
+ assertEquals("substitute String", replaceAll, StringUtil.substituteString(sample, "${variable}", "parameter"));
+ }
+
+ public void testSubstituteStringMultipleTokens() throws Exception {
+
+ String sample = "${variable}${variable}";
+ String replaceAll = replaceAll(sample, "\\$\\{variable\\}", "parameter");
+
+ System.out.println(StringUtil.substituteString(sample, "${variable}", "parameter"));
+ assertEquals("substitute String", replaceAll, StringUtil.substituteString(sample, "${variable}", "parameter"));
+ }
+
+ public void testSubstituteStringZeroLength() throws Exception {
+
+ String sample = "This is a test of ${variable} substitution.";
+ String replaceAll = replaceAll(sample, "\\$\\{variable\\}", "");
+
+ System.out.println(StringUtil.substituteString(sample, "${variable}", ""));
+ assertEquals("substitute String", replaceAll, StringUtil.substituteString(sample, "${variable}", ""));
+ }
+
+ public void testSubstituteStringSpecialChars() throws Exception {
+
+ String sample = "This is a test of \r substitution.";
+ String replaceAll = replaceAll(sample, "\r", "");
+
+ System.out.println(StringUtil.substituteString(sample, "\r", ""));
+ assertEquals("substitute String", replaceAll, StringUtil.substituteString(sample, "\r", ""));
+ }
+
+ private String replaceAll(String original, String regex, String newValue) throws Exception {
+ Method method = String.class.getMethod("replaceAll", new Class[] { String.class, String.class } );
+ return (String) method.invoke(original, new Object[] { regex, newValue } );
+ }
+}
--- /dev/null
+/*
+ * Created on 12-jul-2003
+ *
+ */
+package com.quantum;
+
+/**
+ * @author panic
+ *
+ * Constants for general use in the quantum plug-in
+ */
+public interface IQuantumConstants {
+ public static final String PLUGIN_ID ="com.quantum"; //$NON-NLS-1$
+ public static final String PREFIX = PLUGIN_ID+"."; //$NON-NLS-1$
+
+ public static final String ADD_SCHEMA_DIALOG_CONTEXT = PREFIX+"add_schema_dialog_context"; //$NON-NLS-1$
+
+ //Constants for specifying Tables, Views and Sequences to the JDBC driver
+ public static final String Table = "TABLE";
+ public static final String View = "VIEW";
+ public static final String Sequence = "SEQUENCE";
+
+ public static final String autoCommitTrue = "Always True";
+ public static final String autoCommitFalse = "Always False";
+ public static final String autoCommitSaved = "Last Saved";
+}
--- /dev/null
+package com.quantum;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class Messages {
+
+ private static final String BUNDLE_NAME = "com.quantum.QuantumResources"; //$NON-NLS-1$
+
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+
+ private Messages() {
+ }
+
+ public static String getString(Class resourceClass, String key) {
+ return getString(
+ createKey(resourceClass, key));
+ }
+
+ private static String createKey(Class resourceClass, String key) {
+ return resourceClass.getName() + (key.startsWith(".") ? key : "." + key);
+ }
+
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
+
+ public static String getString(Class resourceClass, String key, Object[] arguments) {
+ return getString(createKey(resourceClass, key), arguments);
+ }
+
+ public static String getString(String key, Object[] arguments) {
+ String string = getString(key);
+ return MessageFormat.format(string, arguments);
+ }
+}
--- /dev/null
+package com.quantum;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.net.URL;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.quantum.model.BookmarkCollection;
+import com.quantum.util.xml.XMLHelper;
+import com.quantum.view.subset.SubsetContentProvider;
+
+import org.eclipse.core.resources.ISaveContext;
+import org.eclipse.core.resources.ISaveParticipant;
+import org.eclipse.core.resources.ISavedState;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IPluginDescriptor;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferenceConverter;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.swt.dnd.Clipboard;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+/**
+ * @author root
+ * Main class of the quantum plugin, sets defaults, saves and recovers state.
+ */
+public class QuantumPlugin extends AbstractUIPlugin {
+
+ private static QuantumPlugin plugin;
+ private Clipboard sysClip;
+
+
+ public QuantumPlugin(IPluginDescriptor descriptor) {
+ super(descriptor);
+ plugin = this;
+ }
+
+ public static QuantumPlugin getDefault() {
+ return plugin;
+ }
+ /**
+ * Reads the Quantum Plugin state from a file. The file has been created with writeImportantState
+ * @param target
+ */
+ protected void readStateFrom(File target) {
+ String fileName = target.getName();
+ if (!fileName.endsWith(Messages.getString("QuantumPlugin.saveFileExtension"))){ //$NON-NLS-1$
+ try {
+ // It's the 2.0 format for preferences
+ BookmarkCollection.getInstance().load(target);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ } else {
+ //It's the 2.1 format for preferences and subsets
+ FileInputStream source = null;
+ try {
+ source = new FileInputStream(target);
+ } catch (FileNotFoundException e1) {
+ e1.printStackTrace();
+ return;
+ }
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder parser;
+ try {
+ parser = factory.newDocumentBuilder();
+ Document doc = parser.parse(source);
+
+ Element root = doc.getDocumentElement();
+ BookmarkCollection.getInstance().importXML(root);
+ BookmarkCollection.getInstance().setChanged(false);
+ SubsetContentProvider.getInstance().importXML(root);
+
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ } catch (SAXException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.core.runtime.Plugin#startup()
+ */
+ public void startup() throws CoreException {
+ super.startup();
+ ISaveParticipant saveParticipant = new QuantumSaveParticipant();
+ ISavedState lastState =
+ ResourcesPlugin.getWorkspace().addSaveParticipant(
+ this,
+ saveParticipant);
+ if (lastState != null) {
+ IPath location = lastState.lookup(new Path(Messages.getString("QuantumPlugin.saveDir"))); //$NON-NLS-1$
+ if (location != null) {
+ // the plugin instance should read any important state from the file.
+ File f = getStateLocation().append(location).toFile();
+ readStateFrom(f);
+
+ }
+ }
+ sysClip = new Clipboard(null);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.core.runtime.Plugin#shutdown()
+ */
+ public void shutdown() throws CoreException {
+ super.shutdown();
+ sysClip.dispose();
+ }
+
+ /**
+ * Write the bookmarks and subsets to a file, saving them for next use of the quantum plugin
+ * @param target
+ */
+ protected void writeImportantState(File target) {
+ try {
+ Document document = XMLHelper.createEmptyDocument();
+
+ Element root = (Element) document.appendChild(
+ document.createElement(Messages.getString("ExportXMLAction.SavedData"))); //$NON-NLS-1$
+
+ BookmarkCollection.getInstance().exportXML(root);
+ SubsetContentProvider.getInstance().exportXML(root);
+
+ FileWriter writer = new FileWriter(target);
+ try {
+ XMLHelper.createDOMSerializer(writer).serialize(document);
+ } finally {
+ writer.close();
+ }
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Gets an image descriptof from a file in the icons directory
+ * @param name of the file to get
+ * @return ImageDescriptor or null if not found
+ */
+ public static ImageDescriptor getImageDescriptor(String name) {
+ ImageDescriptor descriptor = null;
+ try {
+ URL installURL =
+ QuantumPlugin.getDefault().getDescriptor().getInstallURL();
+ URL url = new URL(installURL, Messages.getString("QuantumPlugin.iconsDir") + name); //$NON-NLS-1$
+ descriptor = ImageDescriptor.createFromURL(url);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return descriptor;
+ }
+ public static Image getImage(String name) {
+ ImageDescriptor imageDescriptor = getImageDescriptor(name);
+ return imageDescriptor == null ? null : imageDescriptor.createImage();
+ }
+
+ protected void initializeDefaultPluginPreferences() {
+ RGB BACKGROUND = new RGB(255, 255, 255);
+ RGB COMMENT = new RGB(88, 148, 64);
+ RGB KEYWORD = new RGB(126, 0, 75);
+ RGB STRING = new RGB(0, 0, 255);
+ RGB NUMERIC = new RGB(255, 0, 0);
+ RGB DEFAULT = new RGB(0, 0, 0);
+ IPreferenceStore store = getPreferenceStore();
+ PreferenceConverter.setDefault(store,
+ "quantum.background.color", BACKGROUND); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.text.color", DEFAULT); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.keyword.color", KEYWORD); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.comment.color", COMMENT); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.string.color", STRING); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.numeric.color", NUMERIC); //$NON-NLS-1$
+ getPreferenceStore().setDefault("quantum.text.bold", false); //$NON-NLS-1$
+ getPreferenceStore().setDefault("quantum.keyword.bold", true); //$NON-NLS-1$
+ getPreferenceStore().setDefault("quantum.string.bold", false); //$NON-NLS-1$
+ getPreferenceStore().setDefault("quantum.comment.bold", false); //$NON-NLS-1$
+ getPreferenceStore().setDefault("quantum.numeric.bold", false); //$NON-NLS-1$
+ PreferenceConverter.setDefault(getPreferenceStore(), "quantum.font", (FontData) null); //$NON-NLS-1$
+ getPreferenceStore().setDefault("com.quantum.model.Bookmark.queryHistorySize", 20); //$NON-NLS-1$
+ }
+ // Returns the active page
+ public IWorkbenchPage getActivePage()
+ {
+ IWorkbench workbench = getWorkbench();
+ IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
+ if (window == null) return null;
+ IWorkbenchPage page = window.getActivePage();
+ return page;
+ }
+ /**
+ * returns a view in the active page, creating it if needed
+ * @param view, the name of the view (e.g com.quantum.view.tableview)
+ * @return true if successful, false if not
+ */
+ public IViewPart getView(String view)
+ {
+ IViewPart tableView = null;
+ try {
+ IWorkbenchPage page = QuantumPlugin.getDefault().getActivePage();
+ tableView = page.findView(view);
+ if (tableView == null){
+ // showView will give focus to the created view, we don't want that
+ // so we save the active part
+ IWorkbenchPart part = page.getActivePart();
+ tableView = page.showView(view);
+ // and return the focus to it
+ page.activate(part);
+ }
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ return tableView;
+ }
+
+
+
+ class QuantumSaveParticipant implements ISaveParticipant {
+ /**
+ * @see org.eclipse.core.resources.ISaveParticipant#doneSaving(ISaveContext)
+ */
+ public void doneSaving(ISaveContext context) {
+ }
+ /**
+ * @see org.eclipse.core.resources.ISaveParticipant#prepareToSave(ISaveContext)
+ */
+ public void prepareToSave(ISaveContext context) throws CoreException {
+ }
+
+ /**
+ * @see org.eclipse.core.resources.ISaveParticipant#rollback(ISaveContext)
+ */
+ public void rollback(ISaveContext context) {
+ }
+
+ /**
+ * @see org.eclipse.core.resources.ISaveParticipant#saving(ISaveContext)
+ */
+ public void saving(ISaveContext context) throws CoreException {
+ switch (context.getKind()) {
+ case ISaveContext.FULL_SAVE :
+ QuantumPlugin quantumPluginInstance = QuantumPlugin.getDefault();
+ // save the plug in state
+ if (BookmarkCollection.getInstance().isAnythingChanged()
+ || SubsetContentProvider.getInstance().hasChanged()) {
+
+ int saveNumber = context.getSaveNumber();
+ String saveFileName = Messages.getString("QuantumPlugin.saveDir") + "-" + Integer.toString(saveNumber) + Messages.getString("QuantumPlugin.saveFileExtension"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ File f = quantumPluginInstance.getStateLocation().append(saveFileName).toFile();
+
+ // if we fail to write, an exception is thrown and we do not update the path
+ quantumPluginInstance.writeImportantState(f);
+
+ context.map(new Path(Messages.getString("QuantumPlugin.saveDir")), new Path(saveFileName)); //$NON-NLS-1$
+ context.needSaveNumber();
+
+ } else {
+ System.out.println("Not saving unchanged bookmarks"); //$NON-NLS-1$
+ }
+ break;
+ case ISaveContext.PROJECT_SAVE :
+ // get the project related to this save operation
+ //IProject project = context.getProject();
+ // save its information, if necessary
+ break;
+ case ISaveContext.SNAPSHOT :
+ // This operation needs to be really fast because
+ // snapshots can be requested frequently by the
+ // workspace.
+ break;
+ }
+ }
+ }
+ /**
+ * @return
+ */
+ public Clipboard getSysClip() {
+ return sysClip;
+ }
+}
\ No newline at end of file
--- /dev/null
+bookmarkview.done = Done
+bookmarkview.editBookmark = Edit Bookmark...
+bookmarkview.refresh = Refresh
+bookmarkview.viewTableDetails = View Table Details
+bookmarkview.exportXML = Export XML
+bookmarkview.noSequence = Database type does not support sequences
+bookmarkview.noViews = Database type does not support views
+bookmarkview.noTables = Database type does not support tables
+bookmarkview.retrieveDbElementData = Retrieving data of type
+bookmarkview.retrieveEntities = Retrieving table/view/sequence information
+bookmarkview.done = Done
+bookmarkview.metaDataError = Error while retrieving metadata
+bookmarkview.confirm = Are you sure you want to delete bookmark
+bookmarkview.disconnect = Disconnecting from
+bookmarkview.deleteAllRows = Delete all rows from
+bookmarkview.deleteRowsAction = Delete all rows
+bookmarkview.customCopyAction = Custom Copy
+bookmarkview.confirmDeleteAllRows = Are you sure you want to delete all the rows from this table?
+sqlqueryview.executeQuery = Execute Query (Ctrl+Shift+Q)
+sqlqueryview.importQuery = Import Query
+sqlqueryview.exportQuery = Export Query
+sqlqueryview.clear = Clear
+sqlqueryview.copy = Copy
+sqlqueryview.paste = Paste
+sqlqueryview.done = Done
+tableview.refresh = Refresh Table
+tableview.copy = Copy Table Selection To Clipboard
+tableview.selectAll = Select All Table Rows
+tableview.close = Close Table
+tableview.update = Update...
+tableview.insert = Insert...
+tableview.delete = Delete...
+tableview.filterSort = Sort or Filter Table...
+tableview.showAll = Toggle Show All Table Rows
+tableview.defaultEncoding = Set Default Encoding
+tableview.UTF8Encoding = Set UTF-8
+tableview.UTF16Encoding = Set UTF-16
+tableview.QuantumTableViewName=Quantum Table View
+tableview.ViewNameFinalDecoration=)
+tableview.BookmarkSeparator=:
+tableview.ViewNameInitialDecoration=\ (
+filedialog.preferences = Preferences (*.ini)
+filedialog.allfiles = All Files (*.*)
+filedialog.sqlFiles = SQL query (*.sql)
+filedialog.ddlFiles = SQL query (*.ddl)
+filedialog.exportxml.name = XML files (*.xml)
+filedialog.exportxml.filter = *.xml
+filedialog.exportxml.name = XML files (*.xml)
+filedialog.exportxml.filter = *.xml
+filedialog.exportxml.name = XML files (*.xml)
+filedialog.exportxml.filter = *.xml
+filedialog.allfiles.name = All Files (*.*)
+filedialog.allfiles.filter = *.*
+filedialog.message.CannotOpenFileTitle=Cannot open file
+filedialog.message.CannotOpenFileMessage=Cannot open file to write :
+filedialog.message.CannotOpenFileExplain=\n\nProbably is\'t read-only or used by another process.
+filedialog.options.ConfirmOverwrite = y
+filedialog.message.ConfirmOverwriteTitle = Confirm Overwrite
+filedialog.message.ConfirmOverwriteMessage = This file already exists :
+filedialog.message.ConfirmOverwriteQuestion= \n\nDo you want to overwrite it?
+adapters.generic = Generic JDBC
+adapters.oracle = Oracle
+adapters.postgres = Postgres
+adapters.mysql = MySQL
+adapters.db2 = DB2
+adapters.db2as400 = DB2 for AS400
+adapters.adabasd = Adabas-D
+adapters.informix = Informix
+adapters.redbrick = Red Brick
+adapters.sybase = Sybase
+QuantumPlugin.save_2=save
+QuantumPlugin.icons_3=icons/
+QuantumPlugin.quantum.keyword.color_6=quantum.keyword.color
+QuantumPlugin.quantum.string.bold_12=quantum.string.bold
+QuantumPlugin.save_espace=save
+QuantumPlugin.Not_saving_unchanged_bookmarks_18=Not saving unchanged bookmarks
+QuantumPlugin.iconsDir=icons/
+QuantumPlugin.saveDir=save
+QuantumPlugin.saveFileExtension=.xml
+ExecuteAction.Executing_Query3=Executing Query...
+ExecuteAction.Executing_Query2=Executing Query..
+ExecuteAction.Parsing_sql_script3=Parsing sql script...
+ExecuteAction.QueriesExecuted=\ queries executed,
+ExecuteAction.RowsUpdated=\ rows updated,
+ExecuteAction.Errors=\ errors,
+ExecutAction.TimeExec=\ seconds
+ExecuteAction.Done=Done
+ExecuteAction.RowUpdated=\ rows updated,
+ExecuteAction.ResultsDisplayed=\ results displayed,
+ExportXMLAction.XMLExporting=XML struct: Exporting to file:
+ExportXMLAction.Metadata=Metadata
+ExportXMLAction.Author=Author
+ExportXMLAction.Quantum=Quantum
+ExportXMLAction.Version=Version
+ExportXMLAction.XMLVersionNumber=0.4
+ExportXMLAction.Table=TABLE
+ExportXMLAction.View=VIEV
+ExportXMLAction.TableName=NAME
+ExportXMLAction.SchemaName=SCHEMA
+ExportXMLAction.OtherSchemas=Other_Schemas
+ExportXMLAction.BookmarkName=BOOKMARK
+ExportXMLAction.Subsets=SUBSETS
+ExportXMLAction.Subset=SUBSET
+ExportXMLAction.SubsetName=NAME
+ExportXMLAction.SavedData=SAVED_DATA
+ExportXMLAction.TableColumn=COLUMN
+ExportXMLAction.ColumnName=NAME
+ExportXMLAction.UNKNOWN=UNKNOWN
+ExportXMLAction.NO=NO
+ExportXMLAction.YES=YES
+ExportXMLAction.ColumnNullable=Nullable
+ExportXMLAction.ColumnAutoIncrement=Auto_Increment
+ExportXMLAction.PrimaryKey=Primary_Key
+ExportXMLAction.PKName=Name
+ExportXMLAction.PKColumn=Column
+ExportXMLAction.PKColumnName=Name
+ExportXMLAction.PKSequence=Sequence
+ExportXMLAction.ForeignKey=Foreign_Key
+ExportXMLAction.FKName=Name
+ExportXMLAction.FKType=Type
+ExportXMLAction.FKImported=Imported
+ExportXMLAction.FKExported=Exported
+ExportXMLAction.FKCascadeUpdate=Cascade_Update
+ExportXMLAction.FKCascadeDelete=Cascade_Delete
+ExportXMLAction.FKColumn=Column
+ExportXMLAction.FKSequence=Sequence
+ExportXMLAction.FKPrimarySchema=Primary_Schema
+ExportXMLAction.FKPrimaryTable=Primary_Table
+ExportXMLAction.FKPrimaryColumn=Primary_Column
+ExportXMLAction.FKForeignSchema=Foreign_Schema
+ExportXMLAction.FKForeignTable=Foreign_Table
+ExportXMLAction.FKForeignColumn=Foreign_Column
+SetSchemaAction.SetSchema=Set Schema
+SetSchemaAction.PleaseEnterName=Please enter the name of new schema:
+MetaDataKey=METADATA
+MetaDataKeySeparator=:
+NoFeature.Views=Views
+NoFeature.Sequences=Sequences
+Error.NoDatabase=Database not supported:
+PreferencesPage.PickFont=Pick Font
+PreferencesPage.DefaultFont=Default Font
+PreferencesPage.BackgroundColor=Background Color
+PreferencesPage.DefaultTextColor=Default Text Color
+PreferencesPage.quantum.keyword.color_26=quantum.keyword.color
+PreferencesPage.KeywordTextColor=Keyword Text Color
+PreferencesPage.Bold=Bold
+PreferencesPage.CommentTextColor=Comment Text Color
+PreferencesPage.StringTextColor=String Text Color
+PreferencesPage.NumericTextColor=Numeric Text Color
+PreferencesPage.Font_Default=Font: default
+PreferencesPage.regular=regular
+PreferencesPage.bold=bold
+PreferencesPage.italic=italic
+PreferencesPage.boldItalic=bold italic
+PreferencesPage.FontPrompt=Font:
+BookmarkLabelProvider.TablePrefix=
+BookmarkLabelProvider.ViewPrefix=
+BookmarkLabelProvider.SequencePrefix=
+DeleteColumnAction.DeleteColumns=Delete Columns...
+DeleteColumnAction.ConfirmDeleteColumns=Are you sure you want to delete the selected columns?
+DeleteObjectAction.DeleteSubset=Delete Subset...
+DeleteObjectAction.ConfirmDeleteSubset=Are you sure you want to delete the selected subset ?
+DeleteObjectAction.DeleteItems=Delete items...
+DeleteObjectAction.ConfirmDeleteItems=Are you sure you want to delete the selected tables/views?
+DeleteSubsetAction.DeleteSubset=Delete Subset...
+DeleteSubsetAction.ConfirmDeleteSubset=Are you sure you want to delete the selected subset?
+NewSubsetAction.CreatingNewSubset=Creating new subset..
+NewSubsetAction.NameOfNewSubset=Name of the new Subset
+NewSubsetAction.PleaseEnterName=Please enter name
+OracleAdapter.._3=.
+BookmarkView.ShowTableSizes=Show Table Sizes
+BookmarkView.ShowDatabaseData=Show Database Info
+BookmarkView.Paste=Paste
+BookmarkView.Copy=Copy
+BookmarkView.CopyOf=Copy of
+SQLLogView.ClearLog=Clear Log
+SQLQueryView.Commit=Commit
+SQLQueryView.RollBack=RollBack
+SQLQueryView.AutoCommit=AutoCommit
+SubsetView.Paste=Paste
+SubsetView.Delete=Delete
+SubsetView.CreatesANewEmptySubset=Creates a new empty subset
+SubsetView.DeletesTheSelectedColumns=Deletes the selected column
+SubsetView.DeletesTheSelectedObject=Deletes the selected object
+SubsetView.DeletesTheSelectedSubset=Deletes the selected subset
+TableView.FilterAndSort=Filter and Sort
+TableView.UpdateRow=Update Row
+TableView.InsertRow=Insert Row
+TableView.DeleteRow=Delete Row
+TableAdapter.to=\ to
+TableAdapter.of=\ of
+TableAdapter.full=\ (FULL)
+BookmarkWizard.NewBookmark=New Bookmark
+BookmarkWizard.Testing=Testing...
+BookmarkWizard.JarFiles=Jar Files (*.jar)
+BookmarkWizard.ZipFiles=Zip Files (*.zip)
+BookmarkWizard.AllFiles=All Files (*.*)
+BookmarkWizard.BookmarkNameAst=*Bookmark Name
+BookmarkWizard.UsernameAst=*Username
+BookmarkWizard.PasswordAst=Password
+BookmarkWizard.Schema=Schema (optional)
+BookmarkWizard.ConnectAst=*JDBC URL
+BookmarkWizard.DriverAst=*Driver
+BookmarkWizard.TypeAst=*Type
+BookmarkWizard.Prompt=Prompt for password
+BookmarkWizard.DriverFilenameAst=*Driver Filename
+BookmarkWizard.Browse=Browse...
+DeleteRowPage.ColumnName=Column Name
+DeleteRowPage.Value=Value
+DeleteRowPage.IncludeIn=Include in?
+DeleteRowPage.WhereClause=Where clause
+DeleteRowPage.UpdatingQuery=Updating query
+DeleteRowPage.WarningNoWhere=Warning: no \"where clause\" columns selected, all rows will be deleted
+InsertRowPage.ColumnName=Column Name
+InsertRowPage.Value=Value
+UpdateRowPage.ColumnName=Column Name
+UpdateRowPage.OldValue=Old Value
+UpdateRowPage.NewValue=New Value
+UpdateRowPage._13=
+UpdateRowPage.SetValue=Set Value
+ConnectAction.ConnectingTo=Connecting to
+ConnectAction.ErrorConnecting=Error while connecting to
+BookmarkView.SetExtraSchemas=Set Extra Schemas
+BookmarkView.CopyColumnSeparator=\
+MultiSQLServer.Enter_Password=Enter Password
+MultiSQLServer.PasswordNotProvided=Password not provided in Bookmark
+BookmarkSelectionDialog.text=Select a bookmark
+BookmarkSelectionDialog.title=Bookmark Selection
+ExecuteAgainstAction.IOException=An I/O Exception was encountered while \ntrying to read the input file.
+ExecuteAgainstAction.SQLException=A database error was encountered while \ntrying to execute the SQL statements.
+ExecuteAgainstAction.title=Problem Encountered
+ExceptionDisplayDialog.stackTrace=Stack trace:
+
+# Actions
+com.quantum.actions.AddToQuickListAction.text=Add to Quick List
+com.quantum.actions.RemoveFromQuickListAction.text=Remove from Quick List
+com.quantum.actions.ConnectAction.text = Connect
+com.quantum.actions.ConnectAction.singleSuccessMessage = Connected to {0}
+com.quantum.actions.ConnectAction.singleFailureMessage = Could not connect to {0}
+com.quantum.actions.ConnectAction.multiSuccessMessage = {0} databases successfully connected.
+com.quantum.actions.ConnectAction.multiFailureMessage = {0} database(s) successfully connected. {1} error(s).
+com.quantum.actions.DisconnectAction.text = Disconnect
+com.quantum.actions.DisconnectAction.message = Disconnected
+com.quantum.actions.ViewTableAction.text = View Table
+com.quantum.actions.OpenQueryAction.text = Open
+com.quantum.actions.DeleteBookmarkAction.text = Delete
+com.quantum.actions.RefreshBookmarkAction.text = Refresh
+com.quantum.actions.NextSequenceAction.text = Increment Sequence Value
+com.quantum.actions.PrevSequenceAction.text = Current Sequence Value
+com.quantum.actions.NewBookmarkAction.text = New Bookmark...
+com.quantum.actions.NewBookmarkAction.toolTip = Create a new bookmark
+com.quantum.actions.DeleteAllRowsAction.text = Delete All Rows
+com.quantum.actions.DeleteAllRowsAction.confirmTitle = Warning
+com.quantum.actions.DeleteAllRowsAction.confirmText = Are you sure you want to delete all the rows from the table {0}?
+com.quantum.actions.ViewTableDetailsAction.text = View Table Details
+
+com.quantum.util.connection.ConnectionUtil.title = Connection Not Established
+com.quantum.util.connection.ConnectionUtil.message = The bookmark could not be connected.
+
+com.quantum.view.bookmark.CopyAction.text = Copy
+com.quantum.view.bookmark.PasteAction.text = Paste
+com.quantum.view.bookmark.RenameAction.text = Rename
+com.quantum.view.bookmark.QuickListNode.labelName=Quick List
+com.quantum.view.bookmark.QueryListNode.labelName=Recent SQL Statements
+com.quantum.view.bookmark.GroupNode.TABLE=Tables
+com.quantum.view.bookmark.GroupNode.VIEW=Views
+com.quantum.view.bookmark.GroupNode.SEQUENCE=Sequences
+
+com.quantum.preferences.GlobalPreferences.com.quantum.model.Bookmark.queryHistorySize=Maximum size of query history:
+
+com.quantum.wizards.ExportBookmarkWizardPage.title = Export Bookmark List
+com.quantum.wizards.ExportBookmarkWizardPage.selectAll = Select All
+com.quantum.wizards.ExportBookmarkWizardPage.deselectAll = Deselect All
+com.quantum.wizards.ExportBookmarkWizardPage.fileName = File name:
+com.quantum.wizards.ExportBookmarkWizardPage.browse = Browse
+com.quantum.wizards.ExportBookmarkWizardPage.error.IOException.title = I/O Exception
+com.quantum.wizards.ExportBookmarkWizardPage.error.IOException.message = A problem was encountered with the file: "{0}"
+
+
+# Exception Dialog
+com.quantum.ui.dialog.ExceptionDisplayDialog.java.sql.IOException.title=I/O Exception
+com.quantum.ui.dialog.ExceptionDisplayDialog.java.sql.IOException.message=A problem was encountered while trying to access the file.
+com.quantum.ui.dialog.ExceptionDisplayDialog.java.sql.SQLException.title=SQL Exception
+com.quantum.ui.dialog.ExceptionDisplayDialog.java.sql.SQLException.message=An SQL Exception was encountered while trying to process your request.
+BookmarkWizard.Error=Error
+BookmarkWizard.bookmarkAlreadyExists=The selected bookmark name already exists.
--- /dev/null
+package com.quantum.actions;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import com.quantum.Messages;
+import com.quantum.view.bookmark.EntityNode;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * <p>This action takes an EntityNode and adds a copy of it to the quicklist
+ * of a bookmark.</p>
+ *
+ * @author bcholmes
+ */
+public class AddToQuickListAction extends SelectionListenerAction {
+ private IViewPart view;
+ private List entities = Collections.synchronizedList(new ArrayList());
+
+ public AddToQuickListAction(IViewPart view) {
+ super(Messages.getString(AddToQuickListAction.class.getName() + ".text"));
+ this.view = view;
+ }
+
+ public void run() {
+ for (Iterator i = this.entities.iterator(); i.hasNext(); ) {
+ EntityNode entityNode = (EntityNode) i.next();
+ entityNode.getBookmark().addQuickListEntry(entityNode.getEntity());
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ this.entities.clear();
+ for (Iterator i = selection.iterator(); enabled && i.hasNext(); ) {
+ Object object = i.next();
+ if (object != null && object instanceof EntityNode) {
+ EntityNode node = (EntityNode) object;
+ enabled &= !(node.getBookmark().isInQuickList(node.getEntity()));
+ this.entities.add(node);
+ } else {
+ enabled = false;
+ }
+ }
+
+ return enabled;
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.sql.Connection;
+
+import com.quantum.model.Bookmark;
+import com.quantum.util.connection.ConnectionUtil;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * @author BC
+ */
+public abstract class BaseSQLAction extends Action {
+
+ private ConnectionUtil connectionUtil = new ConnectionUtil();
+
+ protected abstract Shell getShell();
+
+ protected abstract Bookmark getBookmark();
+
+ protected Connection getConnection() {
+ return this.connectionUtil.getConnection(getBookmark(), getShell());
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.sql.Connection;
+import java.util.List;
+
+import com.quantum.model.Bookmark;
+import com.quantum.util.connection.ConnectionUtil;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.bookmark.TreeNode;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * @author BC
+ */
+public abstract class BaseSequenceAction extends SelectionListenerAction {
+
+ protected IViewPart view;
+ private ConnectionUtil connectionUtil = new ConnectionUtil();
+
+ protected BaseSequenceAction(String text, IViewPart view) {
+ super(text);
+
+ }
+
+ protected Bookmark getBookmark() {
+ TreeNode node = getEntityNode();
+ return node.getBookmark();
+ }
+
+ protected Connection getConnection() {
+ return connectionUtil.getConnection(getBookmark(), getShell());
+ }
+
+ protected EntityNode getEntityNode() {
+ List list = getSelectedNonResources();
+ return (EntityNode) list.get(0);
+ }
+
+ protected Shell getShell() {
+ return this.view.getViewSite().getShell();
+ }
+
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ return enabled && selection.size() == 1
+ && (selection.getFirstElement() instanceof EntityNode)
+ && ((EntityNode) selection.getFirstElement()).isSequence();
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author root
+ *
+ */
+public class CloseTableAction extends Action implements IViewActionDelegate {
+ TableView view;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (TableView) view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+ public void run() {
+ view.closeCurrent();
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.sql.Connection;
+import java.util.Iterator;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.util.connection.ConnectionUtil;
+import com.quantum.view.bookmark.BookmarkNode;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+public class ConnectAction extends SelectionListenerAction {
+ /**
+ * @param text
+ */
+ public ConnectAction(IViewPart view) {
+ super(Messages.getString(ConnectAction.class.getName() + ".text"));
+ this.view = view;
+ setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("connect.gif")); //$NON-NLS-1$
+ }
+
+ private IViewPart view;
+ private ConnectionUtil connectionUtil = new ConnectionUtil();
+
+ /**
+ * @see IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = view;
+ }
+
+ /**
+ * @see org.eclipse.jface.action.IAction#run()
+ */
+ public void run() {
+
+ int bookmarks = 0;
+ int errors = 0;
+ String lastBookmarkName = null;
+ for (Iterator i = getSelectedNonResources().iterator(); i.hasNext();) {
+ Bookmark bookmark = ((BookmarkNode) i.next()).getBookmark();
+ Connection connection = this.connectionUtil.connect(bookmark, getShell());
+ if (connection == null) {
+ errors++;
+ }
+ bookmarks++;
+ lastBookmarkName = bookmark.getName();
+ }
+
+ if (bookmarks == 1 && errors == 0) {
+ updateStatusLine(getMessage("singleSuccessMessage",
+ new Object[] {lastBookmarkName}));
+ } else if (bookmarks == 1 && errors == 1) {
+ updateStatusLine(getMessage("singleFailureMessage",
+ new Object[] {lastBookmarkName}));
+ } else if (bookmarks > 1 && errors == 0) {
+ updateStatusLine(getMessage("multiSuccessMessage",
+ new Object[] {String.valueOf(bookmarks)}));
+ } else if (bookmarks > 1 && errors > 0) {
+ updateStatusLine(getMessage("multiFailureMessage",
+ new Object[] {String.valueOf(bookmarks - errors),
+ String.valueOf(errors)}));
+ }
+ }
+
+ private String getMessage(String key, Object[] arguments) {
+ return Messages.getString(getClass().getName() + "." + key, arguments);
+ }
+
+ /**
+ * Updates the message shown in the status line.
+ *
+ * @param message the message to display
+ */
+ protected void updateStatusLine(String message) {
+ this.view.getViewSite().getActionBars().getStatusLineManager().setMessage(message);
+ }
+
+ protected Shell getShell() {
+ return this.view.getSite().getShell();
+ }
+
+ /**
+ *
+ */
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ for (Iterator i = selection.iterator();
+ enabled && i.hasNext();
+ ) {
+ Object object = i.next();
+ if (object instanceof BookmarkNode) {
+ BookmarkNode node = (BookmarkNode) object;
+ enabled &= !node.getBookmark().isConnected();
+ } else {
+ enabled = false;
+ }
+ }
+ return enabled;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Created on 11/08/2003
+ *
+ */
+package com.quantum.actions;
+
+import java.util.Iterator;
+
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Column;
+import com.quantum.model.EntityHolder;
+import com.quantum.util.NthLevelConverter;
+import com.quantum.util.QuantumUtil;
+import com.quantum.util.StringUtil;
+import com.quantum.view.bookmark.ColumnNode;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+
+public class CustomCopyAction extends SelectionListenerAction {
+ private final IViewPart view;
+ private final int ind;
+ /**
+ * @param BookmarkView
+ */
+ public CustomCopyAction(IViewPart view, int ind) {
+ super(null);
+ this.view = view;
+ this.ind = ind;
+ }
+ public void run() {
+ String copyText = "";
+ Iterator iter = getSelectedNonResources().iterator();
+ NthLevelConverter converter = new NthLevelConverter();
+ // Fill up the converter. We iterate the selection items
+ while (iter.hasNext()) {
+ Object current = iter.next();
+ if (current instanceof ColumnNode) {
+ ColumnNode column = (ColumnNode) current;
+ if (column != null) {
+ converter.add(column.getColumn().getName(),
+ column.getColumn().getParentEntity().getCondQualifiedName(), 0);
+ }
+ } else if (current instanceof EntityHolder) {
+ EntityHolder currentSelec = (EntityHolder) current;
+ converter.add(currentSelec.getEntity().getCondQualifiedName(), null, 1);
+ Column[] columns = currentSelec.getEntity().getColumns();
+ for (int i = 0, length = (columns == null) ? 0 : columns.length;
+ i < length;
+ i++) {
+ converter.add(columns[i].getName(),
+ currentSelec.getEntity().getCondQualifiedName(), 0);
+ }
+ }
+ }
+ IPreferenceStore store = QuantumPlugin.getDefault().getPreferenceStore();
+
+
+ converter.convert(Integer.toString(ind));
+
+ String template = QuantumUtil.trasposeEscape(store.getString("customCopyTemplate" + Integer.toString(ind)));
+ copyText = StringUtil.substituteString(template, "${table_list}", converter.getTableList());
+
+
+ QuantumPlugin.getDefault().getSysClip().setContents(
+ new Object[] { copyText },
+ new Transfer[] { TextTransfer.getInstance()});
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.sql.SQLException;
+
+import com.quantum.Messages;
+import com.quantum.model.ConnectionException;
+import com.quantum.model.Table;
+import com.quantum.ui.dialog.ExceptionDisplayDialog;
+import com.quantum.view.bookmark.EntityNode;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * @author root
+ *
+ */
+public class DeleteAllRowsAction extends SelectionListenerAction {
+ private IViewPart view;
+
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public DeleteAllRowsAction(IViewPart view) {
+ super(Messages.getString(DeleteAllRowsAction.class.getName() + ".text"));
+ this.view = view;
+ }
+
+ public void run() {
+ try {
+ Table table = getTable();
+ if (table != null) {
+ boolean flag = MessageDialog.openConfirm(
+ view.getSite().getShell(),
+ Messages.getString(DeleteAllRowsAction.class.getName() + ".confirmTitle"),
+ Messages.getString(DeleteAllRowsAction.class.getName() + ".confirmText",
+ new Object[] { table.getCondQualifiedName() }));
+ if (flag) {
+ table.deleteAllRows();
+ }
+ }
+ } catch (SQLException e) {
+ ExceptionDisplayDialog.openError(getShell(),
+ Messages.getString("ExecuteAgainstAction.title"),
+ Messages.getString("ExecuteAgainstAction.ConnectionException"), e);
+ } catch (ConnectionException e) {
+ ExceptionDisplayDialog.openError(getShell(),
+ Messages.getString("ExecuteAgainstAction.title"),
+ Messages.getString("ExecuteAgainstAction.ConnectionException"), e);
+ }
+ }
+
+ private Table getTable() {
+ EntityNode node = (EntityNode) getSelectedNonResources().get(0);
+ return node == null ? null : (Table) node.getEntity();
+ }
+
+
+
+ protected Shell getShell() {
+ return this.view.getViewSite().getShell();
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.actions.SelectionListenerAction#updateSelection(org.eclipse.jface.viewers.IStructuredSelection)
+ */
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ return enabled && selection.size() == 1 &&
+ (selection.getFirstElement() instanceof EntityNode) &&
+ ((EntityNode) selection.getFirstElement()).isTable();
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.util.Iterator;
+import java.util.List;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.BookmarkCollection;
+import com.quantum.view.bookmark.BookmarkNode;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * @author root
+ *
+ */
+public class DeleteBookmarkAction extends SelectionListenerAction {
+
+ private IViewPart view;
+
+ public DeleteBookmarkAction(IViewPart view) {
+ super(Messages.getString(DeleteBookmarkAction.class.getName() + ".text"));
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("delete.gif"));
+ this.view = view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+ List bookmarkNodes = getSelectedNonResources();
+ boolean flag = MessageDialog.openConfirm(view.getSite().getShell(), Messages.getString("bookmarkview.deleteBookmark"), Messages.getString("bookmarkview.confirm")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ for (Iterator i = bookmarkNodes.iterator(); flag && i.hasNext();) {
+ BookmarkNode bookmarkNode = (BookmarkNode) i.next();
+ if (bookmarkNode != null) {
+ BookmarkCollection.getInstance().removeBookmark(bookmarkNode.getBookmark());
+ }
+ }
+ }
+
+ public boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ for (Iterator i = selection.iterator(); enabled && i.hasNext(); ) {
+ enabled &= (i.next() instanceof BookmarkNode);
+ }
+
+ return enabled;
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.util.Iterator;
+
+import com.quantum.Messages;
+import com.quantum.view.bookmark.ColumnNode;
+import com.quantum.view.subset.SubsetView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * Deletes the selected columns from the Subset items (Tables)
+ * @author root
+ *
+ */
+public class DeleteColumnAction extends Action implements IViewActionDelegate {
+ SubsetView view;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (SubsetView) view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+ StructuredSelection selection = view.getSelection();
+ Iterator iter = selection.iterator();
+ if (! MessageDialog.openConfirm(view.getSite().getShell(),
+ Messages.getString("DeleteColumnAction.DeleteColumns"), //$NON-NLS-1$
+ Messages.getString("DeleteColumnAction.ConfirmDeleteColumns") )) //$NON-NLS-1$
+ return;
+
+ while (iter.hasNext()) {
+ Object current = iter.next();
+ if (current instanceof ColumnNode) {
+ ColumnNode column = (ColumnNode) current;
+ if (column != null) {
+ view.deleteColumn(column);
+ }
+ }
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.util.Iterator;
+
+import com.quantum.Messages;
+import com.quantum.view.subset.ObjectNode;
+import com.quantum.view.subset.SubsetNode;
+import com.quantum.view.subset.SubsetView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * Deletes an entire object (Table) from the SubsetView
+ * @author root
+ *
+ */
+public class DeleteObjectAction extends Action implements IViewActionDelegate {
+ SubsetView view;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (SubsetView) view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+ Object selection = view.getCurrent();
+ if (selection instanceof SubsetNode) {
+ SubsetNode node = (SubsetNode) selection;
+ if (node != null) {
+ boolean flag = MessageDialog.openConfirm(view.getSite().getShell(),
+ Messages.getString("DeleteObjectAction.DeleteSubset"), //$NON-NLS-1$
+ Messages.getString("DeleteObjectAction.ConfirmDeleteSubset") + node.getName()); //$NON-NLS-1$
+ if (flag) {
+ view.deleteCurrent();
+ }
+ }
+ } else if (selection instanceof ObjectNode) {
+ StructuredSelection allSelected = view.getSelection();
+ Iterator iter = allSelected.iterator();
+ if (! MessageDialog.openConfirm(view.getSite().getShell(),
+ Messages.getString("DeleteObjectAction.DeleteItems"), //$NON-NLS-1$
+ Messages.getString("DeleteObjectAction.ConfirmDeleteItems") )) //$NON-NLS-1$
+ return;
+
+ while (iter.hasNext()) {
+ Object current = iter.next();
+ if (current instanceof ObjectNode) {
+ ObjectNode node = (ObjectNode) current;
+ if (node != null) {
+ view.deleteObject(node);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.Messages;
+import com.quantum.view.subset.SubsetNode;
+import com.quantum.view.subset.SubsetView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author root
+ * Deletes a complete subset from the subset view
+ */
+public class DeleteSubsetAction extends Action implements IViewActionDelegate {
+ SubsetView view;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (SubsetView) view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+ Object selection = view.getCurrent();
+ if (selection instanceof SubsetNode) {
+ SubsetNode node = (SubsetNode) selection;
+ if (node != null) {
+ boolean flag = MessageDialog.openConfirm(view.getSite().getShell(),
+ Messages.getString("DeleteSubsetAction.DeleteSubset"), //$NON-NLS-1$
+ Messages.getString("DeleteSubsetAction.ConfirmDeleteSubset") + node.getName()); //$NON-NLS-1$
+ if (flag) {
+ view.deleteCurrent();
+ }
+ }
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.ConnectionException;
+import com.quantum.view.bookmark.BookmarkNode;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * Disconnects from the database
+ *
+ * @author root
+ */
+public class DisconnectAction extends SelectionListenerAction {
+ private IViewPart view;
+ private List selections = new Vector();
+
+ /**
+ * @param text
+ */
+ public DisconnectAction(IViewPart view) {
+ super(Messages.getString(DisconnectAction.class.getName() + ".text"));
+ this.view = view;
+ setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("disconnect.gif")); //$NON-NLS-1$
+ }
+
+
+ public void run() {
+ for (Iterator i = this.selections.iterator(); i.hasNext();) {
+ Bookmark bookmark = (Bookmark) i.next();
+ try {
+ bookmark.disconnect();
+ } catch (ConnectionException e) {
+ e.printStackTrace();
+ }
+ }
+ updateStatusLine(getMessage("message"));
+ }
+
+ private String getMessage(String key) {
+ return Messages.getString(getClass().getName() + "." + key);
+ }
+
+ /**
+ * Updates the message shown in the status line.
+ *
+ * @param message the message to display
+ */
+ protected void updateStatusLine(String message) {
+ this.view.getViewSite().getActionBars().getStatusLineManager().setMessage(message);
+ }
+
+
+ /**
+ *
+ */
+ public boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ this.selections.clear();
+ for (Iterator i = selection.iterator(); enabled && i.hasNext(); ) {
+ Object object = i.next();
+ if (object instanceof BookmarkNode) {
+ BookmarkNode node = (BookmarkNode) object;
+ this.selections.add(node.getBookmark());
+ enabled &= node.getBookmark().isConnected();
+ } else {
+ enabled = false;
+ }
+ }
+ return enabled;
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Vector;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.sql.MultiSQLServer;
+import com.quantum.sql.SQLParser;
+import com.quantum.sql.SQLResults;
+import com.quantum.view.LogProxy;
+import com.quantum.view.SQLQueryView;
+import com.quantum.view.bookmark.BookmarkNode;
+import com.quantum.view.bookmark.BookmarkView;
+import com.quantum.view.tableview.DefaultSizes;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author panic
+ *
+ * Executes a query from the QueryView
+ */
+public class ExecuteAction extends BaseSQLAction implements IViewActionDelegate {
+ SQLQueryView view;
+ boolean flag = false;
+ String execute1 = Messages.getString("ExecuteAction.Executing_Query3"); //$NON-NLS-1$
+ String execute2 = Messages.getString("ExecuteAction.Executing_Query2"); //$NON-NLS-1$
+
+ public ExecuteAction() {
+ setActionDefinitionId("com.quantum.actions.ExecuteAction");
+ }
+
+ public void init(IViewPart view) {
+ this.view = (SQLQueryView) view;
+ }
+
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+ BookmarkNode current = BookmarkView.getInstance().getCurrentBookmark();
+ if (current == null)
+ {
+ MessageDialog.openInformation(
+ view.getSite().getShell(),"Sorry","Please select a bookmark to use as connection.");
+ return;
+ }
+ Connection con = getConnection();
+ view.setStatus(execute1);
+ MultiSQLServer server = MultiSQLServer.getInstance();
+ view.setStatus(Messages.getString("ExecuteAction.Parsing_sql_script3")); //$NON-NLS-1$
+ Vector queries = new Vector();
+ String viewQuery = view.getQuery();
+ // We parse the executable units to send to the JDBC driver
+ queries = SQLParser.parse(viewQuery);
+ for (int i = 0; i < queries.size(); i++) {
+ String query = (String) queries.elementAt(i);
+ System.out.println(query);
+ }
+ int resultCount = 0;
+ int resultUpdateCount = 0;
+ int errorCount = 0;
+ int resultsDisplayed = 0;
+ double startTime = 0.0; // stores the time when query is started
+ double queryDuration= 0.0; // stores query's execution time
+
+ for (int i = 0; i < queries.size(); i++) {
+ if (flag) {
+ view.setStatus(execute1);
+ } else {
+ view.setStatus(execute2);
+ }
+
+ String query = (String) queries.elementAt(i);
+ System.out.println(">" + query + "<"); //$NON-NLS-1$ //$NON-NLS-2$
+ if (con != null && !query.equals("")) { //$NON-NLS-1$
+
+ SQLResults results;
+ try {
+ startTime = System.currentTimeMillis(); // Start the measure of execution time
+ results = server.execute(con, query, 1, DefaultSizes.PAGE_SIZE, DefaultSizes.MAX_COLUMN_SIZE);
+ queryDuration = (System.currentTimeMillis() - startTime)/1000; // calculate the execution time (in seconds)
+ current.getBookmark().addQuery(query);
+ } catch (SQLException e) {
+ errorCount++;
+ LogProxy log = LogProxy.getInstance();
+ log.addText(
+ LogProxy.ERROR,
+ "Error Executing: " + query + ":" + e.toString(), e); //$NON-NLS-1$ //$NON-NLS-2$
+ MessageDialog.openConfirm(view.getSite().getShell(), "Database returned error", e.getLocalizedMessage()); //$NON-NLS-1$
+ continue;
+ }
+ resultCount++;
+ if (results.isResultSet()) {
+ TableView.getInstance().loadQuery(current.getBookmark(), results);
+ resultsDisplayed++;
+ } else {
+ int count = results.getUpdateCount();
+ if (count > 0) {
+ resultUpdateCount += results.getUpdateCount();
+ }
+ }
+ }
+ flag = !flag;
+ view.setProgress(i + 1, queries.size());
+ }
+ Image statImage = QuantumPlugin.getImage((errorCount > 0) ? "stop.gif" : "success.gif"); //$NON-NLS-1$ //$NON-NLS-2$
+ view.setStatus(statImage, Messages.getString("ExecuteAction.Done") + "(" + //$NON-NLS-1$ //$NON-NLS-2$
+ resultCount + Messages.getString("ExecuteAction.QueriesExecuted") + //$NON-NLS-1$
+ resultUpdateCount + Messages.getString("ExecuteAction.RowsUpdated") + //$NON-NLS-1$
+ resultsDisplayed + Messages.getString("ExecuteAction.ResultsDisplayed") + //$NON-NLS-1$
+ errorCount + Messages.getString("ExecuteAction.Errors") + //$NON-NLS-1$
+ queryDuration + Messages.getString("ExecutAction.TimeExec") + ")"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ view.setProgress(0, 1);
+ }
+
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+ protected Bookmark getBookmark() {
+ BookmarkNode current = BookmarkView.getInstance().getCurrentBookmark();
+ return current.getBookmark();
+ }
+
+ /* (non-Javadoc)
+ * @see com.quantum.actions.BaseSQLAction#getShell()
+ */
+ protected Shell getShell() {
+ return this.view.getViewSite().getShell();
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import com.quantum.Messages;
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkCollection;
+import com.quantum.model.ConnectionException;
+import com.quantum.sql.MultiSQLServer;
+import com.quantum.sql.SQLParser;
+import com.quantum.sql.SQLResults;
+import com.quantum.ui.dialog.BookmarkSelectionDialog;
+import com.quantum.ui.dialog.ExceptionDisplayDialog;
+import com.quantum.util.io.InputStreamHelper;
+import com.quantum.view.tableview.DefaultSizes;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.ErrorDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IObjectActionDelegate;
+import org.eclipse.ui.IWorkbenchPart;
+
+/**
+ * This action can be executed against any .sql file, regardless of
+ * whether or not the Quantum perspective is open.
+ *
+ * @author BC
+ */
+public class ExecuteAgainstAction extends BaseSQLAction
+ implements IObjectActionDelegate, PropertyChangeListener {
+
+ private String selectedBookmark = null;
+ private IFile[] files = null;
+
+ private IWorkbenchPart workbenchPart;
+
+ /**
+ * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
+ */
+ public void setActivePart(IAction action, IWorkbenchPart targetPart) {
+ this.workbenchPart = targetPart;
+ }
+
+ protected Shell getShell() {
+ return this.workbenchPart.getSite().getShell();
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
+ */
+ public void run(IAction action) {
+
+ BookmarkSelectionDialog dialog = new BookmarkSelectionDialog(getShell());
+ dialog.addPropertyChangeListener(this);
+ int result = dialog.open();
+
+ if (result == Window.OK) {
+ try {
+ executeAgainstBookmark();
+ } catch (SQLException e) {
+ ExceptionDisplayDialog.openError(getShell(),
+ null,
+ null, e);
+ } catch (IOException e) {
+ ExceptionDisplayDialog.openError(getShell(),
+ Messages.getString("ExecuteAgainstAction.title"),
+ Messages.getString("ExecuteAgainstAction.IOException"), e);
+ } catch (ConnectionException e) {
+ ExceptionDisplayDialog.openError(getShell(),
+ null,
+ null, e);
+ } catch (CoreException e) {
+ ErrorDialog.openError(getShell(), null, null, e.getStatus());
+ }
+ }
+ }
+
+ protected Bookmark getBookmark() {
+ return BookmarkCollection.getInstance().find(this.selectedBookmark);
+ }
+
+ private void executeAgainstBookmark()
+ throws SQLException, IOException, CoreException, ConnectionException {
+ Bookmark bookmark = getBookmark();
+ if (bookmark != null) {
+ boolean alreadyConnected = bookmark.isConnected();
+ Connection connection = getConnection();
+ try {
+ for (int i = 0,
+ length = (this.files == null) ? 0 : this.files.length;
+ connection != null && i < length;
+ i++) {
+ executeAgainstBookmark(bookmark, connection, this.files[i]);
+ }
+ } finally {
+ if (!alreadyConnected && connection != null) {
+ bookmark.disconnect();
+ }
+ }
+ }
+ }
+
+ private void executeAgainstBookmark(
+ Bookmark bookmark,
+ Connection connection,
+ IFile file)
+ throws SQLException, IOException, CoreException {
+ executeAgainstBookmark(
+ bookmark,
+ connection,
+ InputStreamHelper.readIntoString(file.getContents()));
+ }
+
+ private void executeAgainstBookmark(
+ Bookmark bookmark,
+ Connection connection,
+ String queries)
+ throws SQLException {
+ List queryList = SQLParser.parse(queries);
+ MultiSQLServer server = MultiSQLServer.getInstance();
+
+ for (Iterator i = queryList.iterator(); i.hasNext();) {
+ String query = (String) i.next();
+ SQLResults results =
+ server.execute(
+ connection,
+ query,
+ 1,
+ DefaultSizes.PAGE_SIZE,
+ DefaultSizes.MAX_COLUMN_SIZE);
+ if (results.isResultSet()) {
+ TableView view = TableView.getInstance();
+ if (view != null) {
+ view.loadQuery(bookmark, results);
+ }
+ }
+ }
+ }
+
+ /**
+ * This method is called with a new selection has been made on one
+ * of the views.
+ *
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection structuredSelection =
+ (IStructuredSelection) selection;
+ List list = new ArrayList();
+
+ for (Iterator i = structuredSelection.iterator(); i.hasNext();) {
+ Object temp = i.next();
+ if (temp != null && temp instanceof IFile) {
+ System.out.println(((IFile) temp).getName());
+ list.add(temp);
+ }
+ }
+ this.files = (IFile[]) list.toArray(new IFile[list.size()]);
+ }
+ }
+
+ /**
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ if ("selection".equals(event.getPropertyName())) {
+ this.selectedBookmark = (String) event.getNewValue();
+ }
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.wizards.ExportBookmarkWizard;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author root
+ * Asks the user for a file name and saves there the bookmarks in xml format
+ */
+public class ExportBookmarksAction implements IViewActionDelegate {
+
+ private IViewPart view;
+
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+
+ ExportBookmarkWizard wizard = new ExportBookmarkWizard();
+ WizardDialog dialog =
+ new WizardDialog(this.view.getSite().getShell(), wizard);
+ dialog.open();
+ }
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.StringTokenizer;
+
+import com.quantum.Messages;
+import com.quantum.util.StringUtil;
+import com.quantum.view.LogProxy;
+import com.quantum.view.SQLLogView;
+import com.quantum.view.SQLQueryView;
+import com.quantum.view.ViewHelper;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+public class ExportQueryAction extends Action implements IViewActionDelegate {
+ SQLQueryView view;
+
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (SQLQueryView) view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+ FileOutputStream out = ViewHelper.askSaveFile("exportquery", view.getSite().getShell(),
+ new String[]{"*.sql", "*.ddl", "*.*"},
+ new String[]{
+ Messages.getString("filedialog.sqlFiles"),
+ Messages.getString("filedialog.ddlFiles"),
+ Messages.getString("filedialog.allfiles")
+ });
+ if (out == null)
+ return;
+
+ try {
+ FileWriter fileWriter = new FileWriter(out.getFD());
+ PrintWriter writer = new PrintWriter(fileWriter);
+ String output = view.getQuery();
+ output = StringUtil.substituteString(output, "\r", "");
+ StringTokenizer tokenizer = new StringTokenizer(output, "\n", true); //$NON-NLS-1$
+ String prevToken = "";
+ while (tokenizer.hasMoreElements()) {
+ String token = (String) tokenizer.nextElement();
+ // If it's a normal line end, we won't write it, because the println() will
+ // adapting it to the OS (have to test that). But if it's a line end after
+ // another, then it's a blank line.
+ if (token.equals("\n"))
+ if (prevToken.equals("\n"))
+ writer.println(); // Two consecutives "\n", means a separate line
+ else
+ ; // Do nothing, the end of line is already written
+ else
+ writer.println(token); //Normal line
+ prevToken = token;
+ }
+ writer.close();
+ } catch (IOException e) {
+ LogProxy.getInstance().addText(SQLLogView.ERROR, e.toString());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Iterator;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.quantum.Messages;
+import com.quantum.model.xml.ModelToXMLConverter;
+import com.quantum.sql.metadata.MetaDataXMLInterface;
+import com.quantum.util.xml.XMLHelper;
+import com.quantum.view.ViewHelper;
+import com.quantum.view.bookmark.BookmarkView;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.bookmark.TreeNode;
+import com.quantum.view.subset.SubsetView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * @author root
+ */
+public class ExportXMLAction extends Action implements IViewActionDelegate {
+
+ IViewPart view;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+
+ FileOutputStream out = ViewHelper.askSaveFile("exportxml", view.getSite().getShell());
+ if (out == null)
+ return;
+ StructuredSelection selection = null;
+ if (view instanceof BookmarkView){
+ BookmarkView bookmarkView = (BookmarkView) view;
+ selection = bookmarkView.getSelection();
+ } else if (view instanceof SubsetView){
+ SubsetView subsetView = (SubsetView) view;
+ selection = subsetView.getSelection();
+ }
+
+ try {
+ Document doc = XMLHelper.createEmptyDocument();
+ exportXMLSelection(doc, selection);
+ try {
+ XMLHelper.write(out, doc);
+ } finally {
+ out.close();
+ }
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+
+ }
+
+ /**
+ * Exports to an XmlDocument the items selected in a StructuredSelection.
+ * @param doc
+ * @param selection
+ */
+ public void exportXMLSelection(Document doc, StructuredSelection selection) {
+ Element root = (Element) doc.appendChild(doc.createElement(Messages.getString("ExportXMLAction.Metadata"))); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(root, Messages.getString("ExportXMLAction.Author"), //$NON-NLS-1$
+ Messages.getString("ExportXMLAction.Quantum")); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(root, Messages.getString("ExportXMLAction.Version"), //$NON-NLS-1$
+ Messages.getString("ExportXMLAction.XMLVersionNumber")); //$NON-NLS-1$
+ Iterator iter = selection.iterator();
+ while (iter.hasNext()) {
+ TreeNode current = (TreeNode) iter.next();
+// TODO: reinstate this
+// if (current instanceof SubsetNode){
+// SubsetNode subset = (SubsetNode) current;
+// MetaDataXMLInterface.createElementText(root, Messages.getString("ExportXMLAction.Subset"), //$NON-NLS-1$
+// subset.getName()); //$NON-NLS-1$
+// Object[] children = subset.getChildren();
+// for (int i = 0; i < children.length; i++) {
+// TreeNode objectNode = (TreeNode) children[i];
+// if (objectNode instanceof SelectableNode)
+// ExportXMLAction.exportObject(root, (SelectableNode)objectNode);
+// }
+// } else {
+ exportObject(root, current);
+// }
+ }
+
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+ /**
+ * Exports a TreeNode metadata representation to an XmlDocument, based on a an already-created root Element
+ * @param doc The XmlDocument to receive the metadata representation
+ * @param node The node with the metadata to export
+ * @param root The root element (already present in the XmlDocument) that will hold the metadata
+ */
+ public void exportObject(Element root, TreeNode node) {
+ if (node instanceof EntityNode) {
+ EntityNode entityNode = (EntityNode) node;
+ ModelToXMLConverter.getInstance().convert(root, entityNode.getEntity());
+ }
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.BookmarkCollection;
+import com.quantum.util.xml.XMLHelper;
+import com.quantum.view.bookmark.BookmarkView;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+/**
+ * @author root
+ *
+ * To change this generated comment edit the template variable "typecomment":
+ * Window>Preferences>Java>Templates.
+ * To enable and disable the creation of type comments go to
+ * Window>Preferences>Java>Code Generation.
+ */
+public class ImportBookmarksAction implements IViewActionDelegate {
+ BookmarkView view;
+ FileDialog dialog;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (BookmarkView) view;
+ dialog = new FileDialog(view.getSite().getShell(), SWT.OPEN);
+ dialog.setFilterExtensions(new String[]{"*.xml","*.*"}); //$NON-NLS-1$ //$NON-NLS-2$
+ dialog.setFilterNames(new String[]{Messages.getString("filedialog.xmlFiles"),Messages.getString("filedialog.xmlFiles")}); //$NON-NLS-1$ //$NON-NLS-2$
+
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ dialog.setFilterPath(QuantumPlugin.getDefault().getPreferenceStore().getString("quantum.dialogs.importbookmark.path"));
+ String filename = dialog.open();
+ if (filename != null) {
+ QuantumPlugin.getDefault().getPreferenceStore().setValue("quantum.dialogs.importbookmark.path", filename);
+ File importFile = new File(filename);
+
+ FileInputStream source = null;
+ try {
+ source = new FileInputStream(importFile);
+ } catch (FileNotFoundException e1) {
+ e1.printStackTrace();
+ return;
+ }
+ try {
+ Document doc = XMLHelper.createFromInputStream(source);
+ Element root = doc.getDocumentElement();
+ BookmarkCollection.getInstance().importXML(root);
+
+ view.refresh();
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ } catch (SAXException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.view.LogProxy;
+import com.quantum.view.SQLLogView;
+import com.quantum.view.SQLQueryView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author root
+ *
+ */
+public class ImportQueryAction extends Action implements IViewActionDelegate {
+ SQLQueryView view;
+ FileDialog dialog;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (SQLQueryView) view;
+ dialog = new FileDialog(view.getSite().getShell(), SWT.OPEN);
+ dialog.setFilterExtensions(new String[]{"*.sql", "*.ddl", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ dialog.setFilterNames(new String[]{Messages.getString("filedialog.sqlFiles"), //$NON-NLS-1$
+ Messages.getString("filedialog.ddlFiles"), Messages.getString("filedialog.allfiles")}); //$NON-NLS-1$ //$NON-NLS-2$
+
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+
+ public void run() {
+ dialog.setFilterPath(QuantumPlugin.getDefault().getPreferenceStore().getString("quantum.dialogs.importquery.path"));
+ String filename = dialog.open();
+ if (filename != null) {
+ QuantumPlugin.getDefault().getPreferenceStore().setValue("quantum.dialogs.importquery.path", filename);
+
+ try {
+ File importFile = new File(filename);
+ FileReader fileReader = new FileReader(importFile);
+ BufferedReader reader = new BufferedReader(fileReader);
+ String line;
+ StringBuffer buffer = new StringBuffer();
+
+ while ((line = reader.readLine()) != null) {
+ buffer.append(line);
+ buffer.append('\n');
+ }
+ view.setQuery(buffer.toString());
+ reader.close();
+ } catch (IOException e) {
+ LogProxy.getInstance().addText(SQLLogView.ERROR, e.toString());
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.wizards.BookmarkWizard;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author root
+ *
+ */
+public class NewBookmarkAction extends Action {
+ private IViewPart view;
+
+ public NewBookmarkAction(IViewPart view) {
+ this.view = view;
+ setText(Messages.getString(getClass().getName() + ".text")); //$NON-NLS-1$
+ setToolTipText(Messages.getString(getClass().getName() + ".text")); //$NON-NLS-1$
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("bookmarks.gif")); //$NON-NLS-1$
+ }
+
+ public void run() {
+ BookmarkWizard wizard = new BookmarkWizard();
+ wizard.init();
+ WizardDialog dialog =
+ new WizardDialog(view.getSite().getShell(), wizard);
+ dialog.open();
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.Messages;
+import com.quantum.view.subset.SubsetNode;
+import com.quantum.view.subset.SubsetView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author root
+ *
+ */
+public class NewSubsetAction extends Action implements IViewActionDelegate {
+ IViewPart view;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = view;
+
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+ public void run() {
+ System.out.println(Messages.getString("NewSubsetAction.CreatingNewSubset")); //$NON-NLS-1$
+ InputDialog dialog = new InputDialog(view.getSite().getShell(),
+ Messages.getString("NewSubsetAction.NameOfNewSubset"), Messages.getString("NewSubsetAction.PleaseEnterName"), null, null); //$NON-NLS-1$ //$NON-NLS-2$
+ dialog.open();
+ String value = dialog.getValue();
+ if (value != null) {
+ SubsetNode subset = new SubsetNode(value);
+ ((SubsetView) view).addNewSubset(subset);
+ }
+
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.model.Bookmark;
+import com.quantum.sql.SQLResults;
+import com.quantum.view.ViewHelper;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.ui.IViewPart;
+
+public class NextSequenceAction extends BaseSequenceAction {
+
+ /**
+ * @param text
+ * @param view
+ */
+ public NextSequenceAction(IViewPart view) {
+ super(Messages.getString(NextSequenceAction.class.getName() + ".text"), view);
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("append.gif"));
+ }
+
+ public void run() {
+ EntityNode node = getEntityNode();
+ String name = null;
+ if (node.isSequence()) {
+ EntityNode sequence = (EntityNode) node;
+ Bookmark bookmark = sequence.getBookmark();
+ DatabaseAdapter adapter = AdapterFactory.getInstance().getAdapter(bookmark.getType());
+ if (adapter == null) return;
+ name = sequence.getName();
+ String query = adapter.getNextValue(name, sequence.getEntity().getSchema());
+
+ SQLResults results = ViewHelper.tryGetResults(view, getConnection(), query);
+ if (results != null && ! results.isError())
+ TableView.getInstance().loadQuery(bookmark, results);
+ }
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.Messages;
+import com.quantum.view.SQLQueryView;
+import com.quantum.view.bookmark.QueryNode;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * @author BC
+ */
+public class OpenQueryAction extends SelectionListenerAction {
+
+ /**
+ * @param text
+ */
+ public OpenQueryAction(IViewPart viewPart) {
+ super(Messages.getString(OpenQueryAction.class.getName() + ".text"));
+ }
+
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ enabled &= (selection.size() == 1 &&
+ selection.getFirstElement() instanceof QueryNode);
+ return enabled;
+ }
+ public void run() {
+ SQLQueryView queryView = SQLQueryView.getInstance();
+ if (queryView != null) {
+ queryView.setQuery(getQuery());
+ }
+ }
+ private String getQuery() {
+ if (isEnabled()) {
+ QueryNode node = (QueryNode) getSelectedNonResources().get(0);
+ return node.getQuery();
+ } else {
+ return null;
+ }
+ }
+}
--- /dev/null
+/*
+ * Created on 22-jul-2003
+ *
+ */
+package com.quantum.actions;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.model.Bookmark;
+import com.quantum.sql.SQLResults;
+import com.quantum.view.ViewHelper;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.ui.IViewPart;
+
+public class PrevSequenceAction extends BaseSequenceAction {
+ /**
+ * @param text
+ * @param view
+ */
+ public PrevSequenceAction(IViewPart view) {
+ super(Messages.getString(PrevSequenceAction.class.getName() + ".text"), view);
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("grid.gif"));
+ }
+
+ public void run() {
+ EntityNode node = getEntityNode();
+ if (((EntityNode) node).isSequence()) {
+ EntityNode sequence = (EntityNode) node;
+ Bookmark bookmark = sequence.getBookmark();
+ DatabaseAdapter adapter = AdapterFactory.getInstance().getAdapter(
+ bookmark.getType());
+ if (adapter == null) return;
+ String name = sequence.getName();
+ String query = adapter.getPrevValue(name, sequence.getEntity().getSchema());
+ SQLResults results = ViewHelper.tryGetResults(view, getConnection(), query);
+ if (results != null && ! results.isError())
+ TableView.getInstance().loadQuery(bookmark, results);
+ }
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.util.Iterator;
+import java.util.List;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.sql.SQLHelper;
+import com.quantum.view.bookmark.BookmarkView;
+import com.quantum.view.bookmark.TreeNode;
+
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * @author root
+ */
+public class RefreshBookmarkAction extends SelectionListenerAction {
+ SQLHelper helper = new SQLHelper();
+
+ BookmarkView view;
+ public RefreshBookmarkAction(IViewPart view) {
+ super(Messages.getString(RefreshBookmarkAction.class.getName() + ".text"));
+ this.view = (BookmarkView) view;
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("refresh.gif"));
+ }
+
+ public void run() {
+ List list = getSelectedNonResources();
+ for (Iterator i = list.iterator(); i.hasNext(); ) {
+ Object object = i.next();
+ if (object != null && object instanceof TreeNode) {
+ ((TreeNode) object).reload();
+ }
+ }
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author root
+ * Implements the "Refresh Table" action for the TableView view
+ */
+public class RefreshTableAction extends Action implements IViewActionDelegate {
+ TableView view;
+ /**
+ * @see org.eclipse.ui.IViewActionDelegate#init(IViewPart)
+ */
+ public void init(IViewPart view) {
+ this.view = (TableView) view;
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(IAction)
+ */
+ public void run(IAction action) {
+ run();
+ }
+ public void run() {
+ view.refreshCurrent();
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import com.quantum.Messages;
+import com.quantum.view.bookmark.EntityNode;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * <p>This action takes an EntityNode and adds a copy of it to the quicklist
+ * of a bookmark.</p>
+ *
+ * @author bcholmes
+ */
+public class RemoveFromQuickListAction extends SelectionListenerAction {
+ private IViewPart view;
+ private List entities = Collections.synchronizedList(new ArrayList());
+
+ public RemoveFromQuickListAction(IViewPart view) {
+ super(Messages.getString(RemoveFromQuickListAction.class.getName() + ".text"));
+ this.view = view;
+ }
+
+ public void run() {
+ for (Iterator i = this.entities.iterator(); i.hasNext(); ) {
+ EntityNode entityNode = (EntityNode) i.next();
+ entityNode.getBookmark().removeQuickListEntry(entityNode.getEntity());
+ }
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
+ */
+ public boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ this.entities.clear();
+ for (Iterator i = selection.iterator(); enabled && i.hasNext(); ) {
+ Object object = i.next();
+ if (object != null && object instanceof EntityNode) {
+ EntityNode node = (EntityNode) object;
+ enabled &= node.getBookmark().isInQuickList(node.getEntity());
+ this.entities.add(node);
+ } else {
+ enabled = false;
+ }
+ }
+
+ return enabled;
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Entity;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * @author root
+ * Implements action for "View Table"
+*/
+public class ViewTableAction extends SelectionListenerAction {
+ private IViewPart view;
+ private Entity entity;
+
+ public ViewTableAction(IViewPart view) {
+ super(Messages.getString(ViewTableAction.class.getName() + ".text"));
+ this.view = view;
+ setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("table.gif")); //$NON-NLS-1$
+ }
+
+ public void run() {
+ TableView.getInstance().loadTable(this.entity);
+ // TODO: reinstate this
+// } else if (view instanceof SubsetView){
+// SubsetView subsetView = (SubsetView) view;
+// node = (TreeNode) subsetView.getCurrent();
+// if (!(node instanceof ObjectNode)) return;
+// ObjectNode objectNode = (ObjectNode) node;
+//
+// String query = objectNode.getQuery();
+//
+// SQLResults results = ViewHelper.tryGetResults(view, objectNode.getConnection(), query);
+// if (results != null && ! results.isError())
+// TableView.getInstance().loadQuery(bookmark.getBookmark(), results);
+//
+ }
+
+ public boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ enabled &= (selection.size() == 1);
+
+ if (enabled) {
+ Object object = selection.getFirstElement();
+ if (object != null && object instanceof EntityNode) {
+ EntityNode entityNode = (EntityNode) object;
+ this.entity = entityNode.getEntity();
+ enabled &= (entityNode.isTable() || entityNode.isView());
+ }
+ }
+ return enabled;
+ }
+}
--- /dev/null
+package com.quantum.actions;
+
+import java.sql.Connection;
+import java.util.List;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+import com.quantum.sql.SQLResults;
+import com.quantum.util.connection.ConnectionUtil;
+import com.quantum.view.ViewHelper;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+public class ViewTableDetailsAction extends SelectionListenerAction {
+ private IViewPart view;
+ private ConnectionUtil connectionUtil = new ConnectionUtil();
+
+ public ViewTableDetailsAction(IViewPart view) {
+ super(Messages.getString(ViewTableDetailsAction.class, "text"));
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("table.gif")); //$NON-NLS-1$
+ this.view = view;
+ }
+
+ public void run() {
+ Entity entity = getEntity();
+ StringBuffer query = new StringBuffer();
+ query.append(Messages.getString("MetaDataKey")+Messages.getString("MetaDataKeySeparator")); //$NON-NLS-1$ //$NON-NLS-2$
+ query.append(entity.getQuotedTableName());
+ Connection connection = connectionUtil.getConnection(getBookmark(), getShell());
+ if (connection != null) {
+ SQLResults results = ViewHelper.tryGetResults(view, connection, query.toString());
+ if (results != null && ! results.isError())
+ TableView.getInstance().loadQuery(entity.getBookmark(), results);
+ }
+ }
+ public void selectionChanged(IAction action, ISelection selection) {
+ }
+ protected Bookmark getBookmark() {
+ return getEntity().getBookmark();
+ }
+ protected Shell getShell() {
+ return this.view.getViewSite().getShell();
+ }
+ protected Entity getEntity() {
+ List list = getSelectedNonResources();
+ return ((EntityNode) list.get(0)).getEntity();
+ }
+
+ /**
+ * @see org.eclipse.ui.actions.SelectionListenerAction#updateSelection(org.eclipse.jface.viewers.IStructuredSelection)
+ */
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ return enabled && selection.size() == 1;
+ }
+
+}
--- /dev/null
+package com.quantum.adapters;
+
+
+public class AdabasDAdapter extends DatabaseAdapter {
+ public String getShowTableQuery(String qualifier, boolean isDefault) {
+ return "SELECT OWNER, TABLENAME FROM TABLES WHERE OWNER = '" + qualifier.toUpperCase() + "'"; //$NON-NLS-1$
+ }
+ public String getShowViewQuery(String qualifier, boolean isDefault) {
+ return "SELECT OWNER, VIEWNAME FROM VIEWS WHERE OWNER = '" + qualifier.toUpperCase() + "'"; //$NON-NLS-1$
+ }
+}
--- /dev/null
+package com.quantum.adapters;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import com.quantum.Messages;
+
+/**
+ * @author root
+ * Basically this Factory is a Singleton that is used to return the proper adapter
+ */
+public class AdapterFactory {
+ public static final String GENERIC = "GENERIC"; //$NON-NLS-1$
+ public static final String ORACLE = "ORACLE"; //$NON-NLS-1$
+ public static final String POSTGRES = "POSTGRES"; //$NON-NLS-1$
+ public static final String MYSQL = "MYSQL"; //$NON-NLS-1$
+ public static final String DB2 = "DB2"; //$NON-NLS-1$
+ public static final String DB2AS400 = "DB2AS400"; //$NON-NLS-1$
+ public static final String ADABASD = "ADABASD"; //$NON-NLS-1$
+ public static final String INFORMIX = "INFORMIX"; //$NON-NLS-1$
+ public static final String REDBRICK = "REDBRICK"; //$NON-NLS-1$
+ public static final String SYBASE = "SYBASE"; //$NON-NLS-1$
+
+ private static AdapterFactory instance;
+
+ private ArrayList drivers;
+
+ private AdapterFactory() {
+ loadDrivers();
+ }
+ public static synchronized AdapterFactory getInstance() {
+ if (instance == null) {
+ instance = new AdapterFactory();
+ }
+ return instance;
+ }
+
+ /**
+ * Master list of supported drivers
+ */
+ private void loadDrivers() {
+ drivers = new ArrayList();
+
+ DriverInfo generic = new DriverInfo(GENERIC, Messages.getString("adapters.generic"), new GenericAdapter()); //$NON-NLS-1$
+ DriverInfo oracle = new DriverInfo(ORACLE, Messages.getString("adapters.oracle"), new OracleAdapter()); //$NON-NLS-1$
+ DriverInfo db2 = new DriverInfo(DB2, Messages.getString("adapters.db2"), new DB2Adapter()); //$NON-NLS-1$
+ DriverInfo db2as400 = new DriverInfo(DB2AS400, Messages.getString("adapters.db2as400"), new DB2AS400Adapter()); //$NON-NLS-1$
+ DriverInfo postgres = new DriverInfo(POSTGRES, Messages.getString("adapters.postgres"), new PostgresAdapter()); //$NON-NLS-1$
+ DriverInfo mysql = new DriverInfo(MYSQL, Messages.getString("adapters.mysql"), new GenericAdapter()); //$NON-NLS-1$
+ DriverInfo adabasd = new DriverInfo(ADABASD, Messages.getString("adapters.adabasd"), new AdabasDAdapter()); //$NON-NLS-1$
+ DriverInfo informix = new DriverInfo(INFORMIX, Messages.getString("adapters.informix"), new GenericAdapter()); //$NON-NLS-1$
+ DriverInfo redbrick = new DriverInfo(REDBRICK, Messages.getString("adapters.redbrick"), new RedBrickAdapter()); //$NON-NLS-1$
+ DriverInfo sybase = new DriverInfo(SYBASE, Messages.getString("adapters.sybase"), new GenericAdapter()); //$NON-NLS-1$
+
+ drivers.add(generic);
+ drivers.add(oracle);
+ drivers.add(db2);
+ drivers.add(db2as400);
+ drivers.add(postgres);
+ drivers.add(mysql);
+ drivers.add(adabasd);
+ drivers.add(informix);
+ drivers.add(redbrick);
+ drivers.add(sybase);
+ }
+
+ public synchronized DatabaseAdapter getAdapter(String type){
+ if (drivers == null) {
+ loadDrivers();
+ }
+ for (int i = 0; i < drivers.size(); i++) {
+ DriverInfo info = (DriverInfo) drivers.get(i);
+ if (type.equals(info.getDriverType())) {
+ return info.getAdapter();
+ }
+ }
+ // If its not a recognized driver, we return the generic one
+ for (int i = 0; i < drivers.size(); i++) {
+ DriverInfo info = (DriverInfo) drivers.get(i);
+ if (type.equals(GENERIC)) {
+ return info.getAdapter();
+ }
+ }
+ return null;
+ }
+
+ public synchronized DriverInfo[] getDriverList() {
+ List list = new ArrayList(this.drivers);
+ Collections.sort(list);
+ return (DriverInfo[]) list.toArray(new DriverInfo[list.size()]);
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.adapters;
+
+
+public class DB2AS400Adapter extends DatabaseAdapter {
+ public String getShowTableQuery(String qualifier, boolean isDefault) {
+ return "SELECT TABLE_NAME FROM QSYS2.SYSTABLES WHERE table_schema = '" +
+ qualifier.toUpperCase() +
+ "' AND TABLE_TYPE IN ('T', 'P') AND SYSTEM_TABLE= 'N'"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ public String getShowViewQuery(String qualifier, boolean isDefault) {
+ return "SELECT TABLE_NAME FROM QSYS2.SYSTABLES WHERE table_schema = '" +
+ qualifier.toUpperCase() +
+ "' AND TABLE_TYPE IN ('V', 'L') AND SYSTEM_TABLE= 'N'"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
--- /dev/null
+package com.quantum.adapters;
+
+import com.quantum.sql.SQLHelper;
+
+public class DB2Adapter extends DatabaseAdapter {
+ public String getShowTableQuery(String qualifier, boolean isDefault) {
+ return "SELECT TABNAME FROM syscat.tables WHERE tabschema = '" + qualifier.toUpperCase() + "' AND TYPE='T'"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ public String getShowViewQuery(String qualifier, boolean isDefault) {
+ return "SELECT TABNAME FROM syscat.tables WHERE tabschema = '" + qualifier.toUpperCase() + "' AND TYPE='V'"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ public String getShowSequenceQuery(String qualifier, boolean isDefault) {
+ return "SELECT SEQNAME FROM sysibm.syssequences WHERE seqschema = '" + qualifier.toUpperCase() + "'"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ public String getNextValue(String sequence, String owner) {
+ return "VALUES NEXTVAL FOR " + SQLHelper.getQualifiedName(owner, sequence); //$NON-NLS-1$
+ }
+ public String getPrevValue(String sequence, String owner) {
+ return "VALUES PREVVAL FOR " + SQLHelper.getQualifiedName(owner, sequence); //$NON-NLS-1$
+ }
+}
--- /dev/null
+package com.quantum.adapters;
+
+import com.quantum.sql.SQLHelper;
+import com.quantum.util.StringUtil;
+
+/**
+ * Abstract base class for all the adapter classes. Most functions can be redefined in
+ * the adapters for the different databases. If the functions is not redefined, the base
+ * implementation (usually a direct call to the JDBC driver) is used.
+ *
+ * @author root
+ */
+public abstract class DatabaseAdapter {
+
+ /**
+ * Returns the SQL Query to get a list of the tables for the current user (schema)
+ * @param info
+ * @return - A String with the SQL query
+ */
+ public String getShowTableQuery(String schema, boolean isDefault) {
+ return null;
+ }
+ /**
+ * Returns the SQL Query to get a list of the queries for the current user (schema)
+ * @param info
+ * @return - A String with the SQL query
+ */
+ public String getShowViewQuery(String schema, boolean isDefault) {
+ return null;
+ }
+ /**
+ * Returns the SQL Query to get a list of the sequences for the current user (schema)
+ * @param info
+ * @return - A String with the SQL query
+ */
+ public String getShowSequenceQuery(String schema, boolean isDefault) {
+ return null;
+ }
+
+ /** Returns the SQL Query to access all the columns of a table (SELECT)
+ * @param info
+ * @param table
+ * @return - A String with the SQL query
+ */
+ public String getTableQuery( String table) {
+ return "SELECT * FROM " + filterTableName(table); //$NON-NLS-1$
+ }
+
+ /**
+ * Gets the SQL query to get the next value of a sequence, (incrementing it).
+ * @param sequence - The name of the sequence
+ * @param owner - The owner (schema) of it
+ * @return - A string with the SQL query
+ */
+ public String getNextValue(String sequence, String owner) {
+ return null;
+ }
+ /**
+ * Gets the SQL query to get the actual value (previously used) of a sequence, (the sequence is not altered).
+ * @param sequence - The name of the sequence
+ * @param owner - The owner (schema) of it
+ * @return - A string with the SQL query
+ */
+ public String getPrevValue(String sequence, String owner) {
+ return null;
+ }
+ /**
+ * Returns a query to get the comments on the columns of a table.
+ * Should return a query to generate a recordset with one row where
+ * the first and only column is the comment
+ * @param tableName - The full name of the table qualified with schema if applicable
+ * @param columnName - The name of the column
+ */
+ public String getCommentsQuery(String tableName, String columnName) {
+ return null;
+ }
+
+ /**
+ * @param table
+ * @return : A query to get an empty ResultSet (null if failed) for that table or view.
+ * Subclassed if needed by the different database adapters
+ */
+ public String getEmptySetQuery(String table){
+ return "SELECT * FROM " + filterTableName(table) + " WHERE (1 = 0)"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Quotes a string according to the type of the column
+ * @param string to be quoted
+ * @param type according to java.sql.Types
+ * @return
+ */
+ public String quote(String string, int type, String typeString) {
+ if (isTextType(type, typeString)) {
+ return "'" + StringUtil.substituteString(string, "'", "''") + "'";
+ } else if (type == java.sql.Types.DATE || type == java.sql.Types.TIMESTAMP){
+ string = string.trim();
+ //Check if we have to strip the millisecods
+ String sub = string.substring(string.length() - 2, string.length() - 1);
+ if (string.length() > 1 && sub.equals(".")) //$NON-NLS-1$
+ string = string.substring(0, string.length() - 2); // strip the milliseconds
+
+ return "'" + string + "'"; //$NON-NLS-1$ //$NON-NLS-2$
+
+ }
+ return string;
+ }
+
+ /**
+ * Indicates whether or not a particular type should be quoted in
+ * SQL statements. Some databases support non-standard types such as
+ * TEXT that aren't normally recognized as quoted types.
+ *
+ * @param type according to java.sql.Types
+ * @param typeString if the type is "Other".
+ * @return
+ */
+ protected boolean isTextType(int type, String typeString) {
+ return SQLHelper.isText(type);
+ }
+
+
+ /**
+ * Makes an SQL insert string with the given table, names of columns and values
+ * @param string
+ * @param namesClause
+ * @param valuesClause
+ * @return
+ */
+ public String getInsert(String tableName, String namesClause, String valuesClause) {
+ String query = "INSERT INTO " + filterTableName(tableName);
+ if (namesClause != "") {
+ query += " (" + namesClause + ")";
+ query += " VALUES " + "(" + valuesClause; //$NON-NLS-1$
+ query += " )"; //$NON-NLS-1$
+ }
+ return query;
+ }
+ /**
+ * Changes the name of the table, usually to allow for lowercase situations.
+ * The parent implementation does nothing to the tableName, simply returns it.
+ * @param tableName
+ * @return
+ */
+ public String filterTableName(String tableName) {
+ return tableName;
+ }
+ /**
+ * Returns a query to get the number of registers from a table
+ * @param tableName
+ * @return
+ */
+ public String getCountQuery(String tableName) {
+ return "SELECT COUNT(*) FROM " + filterTableName(tableName);
+ }
+ /**
+ * @param string
+ * @param string2
+ * @param whereClause
+ * @param string3
+ */
+ public void getUpdate(String tableName, String string2, StringBuffer whereClause, String string3) {
+ // TODO Auto-generated method stub
+
+ }
+ /**
+ * Returns an SQL UPDATE statement
+ * @param string
+ * @param string2
+ * @param string3
+ */
+ public String getUpdate(String tableName, String setClause, String whereClause) {
+ String query = "UPDATE " + filterTableName(tableName); //$NON-NLS-1$
+ query += " SET " + setClause; //$NON-NLS-1$
+ if (!whereClause.equals("")) query += " WHERE " + whereClause; //$NON-NLS-1$
+ return query;
+ }
+ /**
+ * Returns an SQL DELETE statement
+ * @param string
+ * @param string2
+ * @return
+ */
+ public String getDelete(String tableName, String whereClause) {
+ String query = "DELETE FROM " + filterTableName(tableName); //$NON-NLS-1$
+ if (!whereClause.equals("")) {
+ query += " WHERE " + whereClause; //$NON-NLS-1$
+ }
+ return query;
+ }
+ /**
+ * @param userid - the userid used to connect to the database
+ * @return the default schema for the database
+ */
+ public String getDefaultSchema(String userid) {
+ return userid;
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.adapters;
+
+import java.util.Vector;
+
+public class DriverInfo implements Comparable {
+ private String driverType;
+ private String displayName;
+ private Vector driverNames = new Vector();
+ private DatabaseAdapter adapter;
+ public DriverInfo(String driverType, String displayName, DatabaseAdapter adapter) {
+ this.driverType = driverType;
+ this.displayName = displayName;
+ this.adapter = adapter;
+ }
+
+ public String getDriverType() {
+ return driverType;
+ }
+
+ public void setDriverType(String driverType) {
+ this.driverType = driverType;
+ }
+
+ public void addDriverName(String driverName) {
+ driverNames.addElement(driverName);
+ }
+
+ public String[] getDriverNames() {
+ String retVal[] = new String[driverNames.size()];
+ for (int i = 0; i < driverNames.size(); i++) {
+ retVal[i] = (String) driverNames.elementAt(i);
+ }
+ return retVal;
+ }
+
+ public DatabaseAdapter getAdapter() {
+ return adapter;
+ }
+
+ public void setAdapter(DatabaseAdapter adapter) {
+ this.adapter = adapter;
+ }
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public void setDisplayName(String displayName) {
+ this.displayName = displayName;
+ }
+
+ public int compareTo(Object o) {
+ DriverInfo that = (DriverInfo) o;
+ return this.getDisplayName().compareTo(that.getDisplayName());
+ }
+
+}
--- /dev/null
+package com.quantum.adapters;
+
+public class FeatureNotSupported extends Error {
+ public FeatureNotSupported(String error) {
+ super(error);
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.adapters;
+
+
+
+
+public class GenericAdapter extends DatabaseAdapter {
+
+ public String getShowTableQuery(String qualifier, boolean isDefault) {
+ return null;
+ }
+ public String getShowViewQuery(String qualifier, boolean isDefault) {
+ return null;
+ }
+
+ public String getShowSequenceQuery(String qualifier, boolean isDefault) {
+ return null;
+ }
+
+
+}
--- /dev/null
+package com.quantum.adapters;
+
+
+
+public class MySQLAdapter extends DatabaseAdapter {
+ public String getShowTableQuery(String qualifier, boolean isDefault) {
+ return "SHOW TABLES"; //$NON-NLS-1$
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.adapters;
+
+import com.quantum.Messages;
+
+public class NoSuchAdapterException extends Exception {
+ public NoSuchAdapterException(String driverName) {
+ super(Messages.getString("Error.NoDatabase") + driverName + Messages.getString("NoSuchAdapterException.<-_2")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.adapters;
+
+import com.quantum.Messages;
+import com.quantum.sql.SQLHelper;
+import com.quantum.util.QuantumUtil;
+
+
+
+public class OracleAdapter extends DatabaseAdapter {
+ public String getShowSequenceQuery(String qualifier, boolean isDefault) {
+ return "SELECT SEQUENCE_OWNER, SEQUENCE_NAME FROM ALL_SEQUENCES WHERE SEQUENCE_OWNER = '" + qualifier + "'"; //$NON-NLS-1$
+ }
+ public String getPrevValue(String sequence, String owner) {
+ return "SELECT LAST_NUMBER FROM ALL_SEQUENCES WHERE SEQUENCE_OWNER = '" + owner + "' AND SEQUENCE_NAME = '" + sequence + "'"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ public String getNextValue(String sequence, String owner) {
+ return "SELECT " + SQLHelper.getQualifiedName(owner, sequence) + ".NEXTVAL FROM DUAL";
+ }
+ public String getCommentsQuery(String tableName, String column) {
+ String query = "SELECT COMMENTS FROM ALL_COL_COMMENTS WHERE TABLE_NAME = '";
+ query += QuantumUtil.getTableName(tableName) + "' AND COLUMN_NAME = '" + column + "'" ;
+ if (!(QuantumUtil.getSchemaName(tableName).equals("")))
+ query += " AND OWNER = '" + QuantumUtil.getSchemaName(tableName) + "'";
+ return query;
+ }
+ /**
+ * Quotes a string according to the type of the column
+ * @param string to be quoted
+ * @param type according to java.sql.Types
+ * @return
+ */
+ public String quote(String string, int type, String typeString) {
+ if (type == java.sql.Types.DATE || type == java.sql.Types.TIMESTAMP) {
+ string = string.trim();
+ String sub = string.substring(string.length()-2, string.length()-1);
+ if (string.length() > 1 && sub.equals(Messages.getString("OracleAdapter.._3"))) //$NON-NLS-1$
+ string = string.substring(0,string.length()-2);
+ return "TO_DATE('" + string + "','yyyy-mm-dd hh24:mi:ss')"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ // use the default (upper type)
+ return super.quote(string, type, typeString);
+ }
+
+ /* (non-Javadoc)
+ * @see com.quantum.adapters.DatabaseAdapter#filterTableName(java.lang.String)
+ */
+ public String filterTableName(String tableName) {
+ // If there is no mixed case, better not quote, it's prettier on display
+ if (tableName.equals(tableName.toUpperCase())) return tableName;
+ // We quote the table name (and only the table name) because it has mixed case
+ if (QuantumUtil.getSchemaName(tableName).equals(""))
+ return "\"" + tableName +"\""; //$NON-NLS-1$
+ else
+ return QuantumUtil.getSchemaName(tableName) + ".\"" +
+ QuantumUtil.getTableName(tableName) + "\"";
+}
+
+ /**
+ * The default schema for Oracle is the upper-case userid.
+ * @see com.quantum.adapters.DatabaseAdapter#getDefaultSchema(java.lang.String)
+ */
+ public String getDefaultSchema(String userid) {
+ return super.getDefaultSchema(userid).toUpperCase();
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.adapters;
+
+import com.quantum.sql.SQLHelper;
+import com.quantum.util.QuantumUtil;
+import com.quantum.util.sql.TypesHelper;
+
+
+public class PostgresAdapter extends DatabaseAdapter {
+ public String getShowTableQuery(String qualifier, boolean isDefault) {
+ return "SELECT SCHEMANAME, TABLENAME FROM PG_TABLES WHERE SCHEMANAME = '"
+ + qualifier + "'";
+ }
+ public String getShowViewQuery(String qualifier, boolean isDefault) {
+ return "SELECT SCHEMANAME, VIEWNAME FROM PG_VIEWS WHERE SCHEMANAME = '"
+ + qualifier + "'";
+ }
+ public String getShowSequenceQuery(String qualifier, boolean isDefault) {
+ return "SELECT SCHEMANAME, relname FROM pg_class WHERE relkind = 'S'" +
+ "AND SCHEMANAME = '" + qualifier + "'";
+ }
+ public String getNextValue(String sequence, String owner) {
+ return "SELECT NEXTVAL('" + SQLHelper.getQualifiedName(owner, sequence) + "')";
+ }
+ public String getPrevValue(String sequence, String owner) {
+ return "SELECT * FROM " + SQLHelper.getQualifiedName(owner, sequence);
+ }
+
+ /**
+ * Quotes a string according to the type of the column
+ * @param string to be quoted
+ * @param type according to java.sql.Types
+ * @return
+ */
+ public String quote(String string, int type, String typeString) {
+ // Booleans in PostgreSQL are queried "t" or "f", but require "true" or "false" when inputed.
+ if (type == TypesHelper.BIT || type == TypesHelper.BOOLEAN ) // Postgresql seems to identify booleans as BITs
+ {
+ if (string.indexOf('t') >= 0 || string.indexOf('T') >= 0 )
+ return "true";
+ else if (string.indexOf('f') >= 0 || string.indexOf('F') >= 0 )
+ return "false";
+ else
+ return string;
+ }
+ // use the default (upper type)
+ return super.quote(string, type, typeString);
+ }
+
+ /**
+ * @see com.quantum.adapters.DatabaseAdapter#filterTableName(java.lang.String)
+ */
+ public String filterTableName(String tableName) {
+ // If there is no mixed case, better not quote, it's prettier on display
+ if (tableName.equals(tableName.toUpperCase())) return tableName;
+ // We quote the table name (and only the table name) because it has mixed case
+ if (QuantumUtil.getSchemaName(tableName).equals("")) {
+ return "\"" + tableName +"\""; //$NON-NLS-1$
+ } else {
+ return QuantumUtil.getSchemaName(tableName) + ".\"" +
+ QuantumUtil.getTableName(tableName) + "\"";
+ }
+ }
+ /**
+ * @see com.quantum.adapters.DatabaseAdapter#getDefaultSchema(java.lang.String)
+ */
+ public String getDefaultSchema(String userid) {
+ return "public";
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.adapters;
+
+
+/**
+ * @author bcholmes
+ */
+public class RedBrickAdapter extends DatabaseAdapter {
+
+ public String getShowTableQuery(String qualifier, boolean isDefault) {
+ return "select name from rbw_tables where type = 'TABLE'";
+ }
+
+ public String getShowViewQuery(String qualifier, boolean isDefault) {
+ return "select name from rbw_tables where type = 'VIEW'";
+ }
+ /**
+ * @see com.quantum.adapters.DatabaseAdapter#getDefaultSchema(java.lang.String)
+ */
+ public String getDefaultSchema(String userid) {
+ return null;
+ }
+
+}
--- /dev/null
+package com.quantum.editors;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.widgets.Display;
+
+public class ColorManager {
+
+ protected Map fColorTable = new HashMap(10);
+
+ public void dispose() {
+ Iterator e= fColorTable.values().iterator();
+ while (e.hasNext())
+ ((Color) e.next()).dispose();
+ }
+ public Color getColor(RGB rgb) {
+ Color color= (Color) fColorTable.get(rgb);
+ if (color == null) {
+ color= new Color(Display.getCurrent(), rgb);
+ fColorTable.put(rgb, color);
+ }
+ return color;
+ }
+}
--- /dev/null
+package com.quantum.editors;
+
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.DocumentEvent;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITypedRegion;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.text.TextAttribute;
+import org.eclipse.jface.text.TextPresentation;
+import org.eclipse.jface.text.presentation.IPresentationDamager;
+import org.eclipse.jface.text.presentation.IPresentationRepairer;
+import org.eclipse.jface.util.Assert;
+import org.eclipse.swt.custom.StyleRange;
+
+public class NonRuleBasedDamagerRepairer
+ implements IPresentationDamager, IPresentationRepairer {
+
+ /** The document this object works on */
+ protected IDocument fDocument;
+ /** The default text attribute if non is returned as data by the current token */
+ protected TextAttribute fDefaultTextAttribute;
+
+ /**
+ * Constructor for NonRuleBasedDamagerRepairer.
+ */
+ public NonRuleBasedDamagerRepairer(TextAttribute defaultTextAttribute) {
+ Assert.isNotNull(defaultTextAttribute);
+
+ fDefaultTextAttribute = defaultTextAttribute;
+ }
+
+ /**
+ * @see IPresentationRepairer#setDocument(IDocument)
+ */
+ public void setDocument(IDocument document) {
+ fDocument = document;
+ }
+
+ public void setTextAttribute(TextAttribute attr) {
+ fDefaultTextAttribute = attr;
+ }
+
+ /**
+ * Returns the end offset of the line that contains the specified offset or
+ * if the offset is inside a line delimiter, the end offset of the next line.
+ *
+ * @param offset the offset whose line end offset must be computed
+ * @return the line end offset for the given offset
+ * @exception BadLocationException if offset is invalid in the current document
+ */
+ protected int endOfLineOf(int offset) throws BadLocationException {
+
+ IRegion info = fDocument.getLineInformationOfOffset(offset);
+ if (offset <= info.getOffset() + info.getLength())
+ return info.getOffset() + info.getLength();
+
+ int line = fDocument.getLineOfOffset(offset);
+ try {
+ info = fDocument.getLineInformation(line + 1);
+ return info.getOffset() + info.getLength();
+ } catch (BadLocationException x) {
+ return fDocument.getLength();
+ }
+ }
+
+ /**
+ * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, boolean)
+ */
+ public IRegion getDamageRegion(
+ ITypedRegion partition,
+ DocumentEvent event,
+ boolean documentPartitioningChanged) {
+ if (!documentPartitioningChanged) {
+ try {
+
+ IRegion info = fDocument.getLineInformationOfOffset(event.getOffset());
+ int start = Math.max(partition.getOffset(), info.getOffset());
+
+ int end =
+ event.getOffset()
+ + (event.getText() == null ? event.getLength() : event.getText().length());
+
+ if (info.getOffset() <= end && end <= info.getOffset() + info.getLength()) {
+ // optimize the case of the same line
+ end = info.getOffset() + info.getLength();
+ } else
+ end = endOfLineOf(end);
+
+ end = Math.min(partition.getOffset() + partition.getLength(), end);
+ return new Region(start, end - start);
+
+ } catch (BadLocationException x) {
+ }
+ }
+
+ return partition;
+ }
+
+ /**
+ * @see IPresentationRepairer#createPresentation(TextPresentation, ITypedRegion)
+ */
+ public void createPresentation(
+ TextPresentation presentation,
+ ITypedRegion region) {
+ addRange(
+ presentation,
+ region.getOffset(),
+ region.getLength(),
+ fDefaultTextAttribute);
+ }
+
+ /**
+ * Adds style information to the given text presentation.
+ *
+ * @param presentation the text presentation to be extended
+ * @param offset the offset of the range to be styled
+ * @param length the length of the range to be styled
+ * @param attr the attribute describing the style of the range to be styled
+ */
+ protected void addRange(
+ TextPresentation presentation,
+ int offset,
+ int length,
+ TextAttribute attr) {
+ if (attr != null)
+ presentation.addStyleRange(
+ new StyleRange(
+ offset,
+ length,
+ attr.getForeground(),
+ attr.getBackground(),
+ attr.getStyle()));
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.editors;
+
+import org.eclipse.swt.graphics.RGB;
+
+public class SQLColorConstants {
+ public static RGB BACKGROUND = new RGB(255, 0, 255);
+ public static RGB COMMENT = new RGB(88, 148, 64);
+ public static RGB IDENTIFIER = new RGB(0, 0, 0);
+ public static RGB KEYWORD = new RGB(126, 0, 75);
+ public static RGB STRING = new RGB(0, 0, 255);
+ public static RGB NUMERIC = new RGB(255, 0, 0);
+ public static RGB DEFAULT = new RGB(0, 0, 0);
+}
--- /dev/null
+package com.quantum.editors;
+
+import java.util.HashMap;
+
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferenceConverter;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.TextAttribute;
+import org.eclipse.jface.text.presentation.IPresentationReconciler;
+import org.eclipse.jface.text.presentation.PresentationReconciler;
+import org.eclipse.jface.text.source.ISourceViewer;
+import org.eclipse.jface.text.source.SourceViewerConfiguration;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.RGB;
+
+public class SQLConfiguration extends SourceViewerConfiguration {
+ private PresentationReconciler reconciler = new PresentationReconciler();
+ private ColorManager colorManager;
+ private HashMap cache = new HashMap();
+ private boolean textBold = false;
+ private boolean keywordBold = true;
+ private boolean stringBold = false;
+ private boolean commentBold = false;
+ private boolean numericBold = false;
+ public SQLConfiguration(ColorManager colorManager) {
+ this.colorManager = colorManager;
+ }
+ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
+ return new String[] {
+ IDocument.DEFAULT_CONTENT_TYPE,
+ SQLPartitionScanner.SQL_COMMENT,
+ SQLPartitionScanner.SQL_KEYWORD,
+ SQLPartitionScanner.SQL_IDENTIFIER};
+ }
+
+ public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
+ initializeColors();
+ return reconciler;
+ }
+ public void loadPrefs() {
+ IPreferenceStore store = QuantumPlugin.getDefault().getPreferenceStore();
+ textBold = store.getBoolean("quantum.text.bold"); //$NON-NLS-1$
+ keywordBold = store.getBoolean("quantum.keyword.bold"); //$NON-NLS-1$
+ stringBold = store.getBoolean("quantum.string.bold"); //$NON-NLS-1$
+ commentBold = store.getBoolean("quantum.comment.bold"); //$NON-NLS-1$
+ numericBold = store.getBoolean("quantum.numeric.bold"); //$NON-NLS-1$
+ SQLColorConstants.BACKGROUND = PreferenceConverter.getColor(store, "quantum.background.color"); //$NON-NLS-1$
+ SQLColorConstants.DEFAULT = PreferenceConverter.getColor(store, "quantum.text.color"); //$NON-NLS-1$
+ SQLColorConstants.IDENTIFIER = PreferenceConverter.getColor(store, "quantum.text.color"); //$NON-NLS-1$
+ SQLColorConstants.KEYWORD = PreferenceConverter.getColor(store, "quantum.keyword.color"); //$NON-NLS-1$
+ SQLColorConstants.STRING = PreferenceConverter.getColor(store, "quantum.string.color"); //$NON-NLS-1$
+ SQLColorConstants.COMMENT = PreferenceConverter.getColor(store, "quantum.comment.color"); //$NON-NLS-1$
+ SQLColorConstants.NUMERIC = PreferenceConverter.getColor(store, "quantum.numeric.color"); //$NON-NLS-1$
+ }
+ public void initializeColors() {
+ setDamageRepairer(getAttr(SQLColorConstants.KEYWORD, keywordBold), SQLPartitionScanner.SQL_KEYWORD);
+ setDamageRepairer(getAttr(SQLColorConstants.COMMENT, commentBold), SQLPartitionScanner.SQL_COMMENT);
+ setDamageRepairer(getAttr(SQLColorConstants.STRING, stringBold), SQLPartitionScanner.SQL_STRING);
+ setDamageRepairer(getAttr(SQLColorConstants.DEFAULT, textBold), IDocument.DEFAULT_CONTENT_TYPE);
+ setDamageRepairer(getAttr(SQLColorConstants.DEFAULT, textBold), SQLPartitionScanner.SQL_SYMBOL);
+ setDamageRepairer(getAttr(SQLColorConstants.DEFAULT, textBold), SQLPartitionScanner.SQL_IDENTIFIER);
+ setDamageRepairer(getAttr(SQLColorConstants.DEFAULT, textBold), SQLPartitionScanner.SQL_SEPARATOR);
+ setDamageRepairer(getAttr(SQLColorConstants.NUMERIC, numericBold), SQLPartitionScanner.SQL_NUMERIC);
+ }
+ public TextAttribute getAttr(RGB color, boolean bold) {
+ colorManager.getColor(SQLColorConstants.BACKGROUND);
+ Color foreground = colorManager.getColor(color);
+ TextAttribute attr = new TextAttribute(foreground);
+ if (bold) {
+ return new TextAttribute(foreground, attr.getBackground(), SWT.BOLD);
+ }
+ return attr;
+ }
+ public void setDamageRepairer(TextAttribute attr, String token) {
+ NonRuleBasedDamagerRepairer ndr = (NonRuleBasedDamagerRepairer) cache.get(token);
+ if (ndr == null) {
+ ndr =
+ new NonRuleBasedDamagerRepairer(attr);
+ reconciler.setDamager(ndr, token);
+ reconciler.setRepairer(ndr, token);
+ cache.put(token, ndr);
+ } else {
+ ndr.setTextAttribute(attr);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.editors;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IDocumentPartitioner;
+import org.eclipse.jface.text.rules.DefaultPartitioner;
+import org.eclipse.ui.editors.text.FileDocumentProvider;
+
+public class SQLDocumentProvider extends FileDocumentProvider {
+
+ public SQLDocumentProvider() {
+ super();
+ }
+
+ protected IDocument createDocument(Object element) throws CoreException {
+ IDocument document = super.createDocument(element);
+ if (document != null) {
+ IDocumentPartitioner partitioner =
+ new DefaultPartitioner(
+ new SQLPartitionScanner(),
+ new String[] {
+ IDocument.DEFAULT_CONTENT_TYPE,
+ SQLPartitionScanner.SQL_KEYWORD,
+ SQLPartitionScanner.SQL_COMMENT,
+ SQLPartitionScanner.SQL_IDENTIFIER,
+ SQLPartitionScanner.SQL_STRING,
+ SQLPartitionScanner.SQL_SEPARATOR,
+ SQLPartitionScanner.SQL_SYMBOL,
+ SQLPartitionScanner.SQL_NUMERIC });
+ partitioner.connect(document);
+ document.setDocumentPartitioner(partitioner);
+ }
+ return document;
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.editors;
+
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.PreferenceConverter;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.editors.text.TextEditor;
+
+public class SQLEditor extends TextEditor {
+ SQLConfiguration config;
+ private ColorManager colorManager;
+ /**
+ * An editor capable of editing SQL scripts
+ */
+ public SQLEditor() {
+ super();
+ colorManager = new ColorManager();
+ config = new SQLConfiguration(colorManager);
+ config.loadPrefs();
+
+ setPreferenceStore(QuantumPlugin.getDefault().getPreferenceStore());
+ IPropertyChangeListener preferenceListener = new IPropertyChangeListener() {
+ public void propertyChange(PropertyChangeEvent event) {
+ config.loadPrefs();
+ config.initializeColors();
+ getSourceViewer().invalidateTextPresentation();
+ StyledText widget = getSourceViewer().getTextWidget();
+ FontData font = PreferenceConverter.getFontData(getPreferenceStore(), "quantum.font"); //$NON-NLS-1$
+ widget.setFont(new Font(Display.getCurrent(), font));
+ Color background = colorManager.getColor(SQLColorConstants.BACKGROUND);
+ widget.setBackground(background);
+ }
+ };
+ getPreferenceStore().
+ addPropertyChangeListener(preferenceListener);
+
+ setSourceViewerConfiguration(config);
+ setDocumentProvider(new SQLDocumentProvider());
+ }
+ public void dispose() {
+ colorManager.dispose();
+ super.dispose();
+ }
+ public void createPartControl(Composite arg0) {
+ super.createPartControl(arg0);
+ StyledText widget = getSourceViewer().getTextWidget();
+ FontData font = PreferenceConverter.getFontData(getPreferenceStore(), "quantum.font"); //$NON-NLS-1$
+ widget.setFont(new Font(Display.getCurrent(), font));
+ Color background = colorManager.getColor(SQLColorConstants.BACKGROUND);
+ widget.setBackground(background);
+ }
+}
--- /dev/null
+package com.quantum.editors;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.rules.EndOfLineRule;
+import org.eclipse.jface.text.rules.ICharacterScanner;
+import org.eclipse.jface.text.rules.IPredicateRule;
+import org.eclipse.jface.text.rules.IRule;
+import org.eclipse.jface.text.rules.IToken;
+import org.eclipse.jface.text.rules.IWhitespaceDetector;
+import org.eclipse.jface.text.rules.MultiLineRule;
+import org.eclipse.jface.text.rules.RuleBasedPartitionScanner;
+import org.eclipse.jface.text.rules.SingleLineRule;
+import org.eclipse.jface.text.rules.Token;
+import org.eclipse.jface.text.rules.WhitespaceRule;
+
+public class SQLPartitionScanner extends RuleBasedPartitionScanner {
+ public final static String SQL_COMMENT = "__sql_comment"; //$NON-NLS-1$
+ public final static String SQL_IDENTIFIER = "__sql_word"; //$NON-NLS-1$
+ public final static String SQL_STRING = "__sql_string"; //$NON-NLS-1$
+ public final static String SQL_KEYWORD = "__sql_keyword"; //$NON-NLS-1$
+ public final static String SQL_SYMBOL = "__sql_symbol"; //$NON-NLS-1$
+ public final static String SQL_SEPARATOR = "__sql_separator"; //$NON-NLS-1$
+ public final static String SQL_NUMERIC = "__sql_numeric"; //$NON-NLS-1$
+
+ private final static String[] KEYWORDS = {
+ "ALTER", //$NON-NLS-1$
+ "AND", //$NON-NLS-1$
+ "BY", //$NON-NLS-1$
+ "COLUMN", //$NON-NLS-1$
+ "CREATE", //$NON-NLS-1$
+ "DELETE", //$NON-NLS-1$
+ "DROP", //$NON-NLS-1$
+ "FROM", //$NON-NLS-1$
+ "GROUP", //$NON-NLS-1$
+ "INSERT", //$NON-NLS-1$
+ "INTO", //$NON-NLS-1$
+ "NOT", //$NON-NLS-1$
+ "NULL", //$NON-NLS-1$
+ "OR", //$NON-NLS-1$
+ "ORDER", //$NON-NLS-1$
+ "SELECT", //$NON-NLS-1$
+ "SEQUENCE", //$NON-NLS-1$
+ "SET", //$NON-NLS-1$
+ "TABLE", //$NON-NLS-1$
+ "UNION", //$NON-NLS-1$
+ "UNIQUE", //$NON-NLS-1$
+ "UPDATE", //$NON-NLS-1$
+ "USING", //$NON-NLS-1$
+ "VALUES", //$NON-NLS-1$
+ "VIEW", //$NON-NLS-1$
+ "WHEN", //$NON-NLS-1$
+ "WHERE" //$NON-NLS-1$
+ };
+
+ public SQLPartitionScanner() {
+
+ List rules = new ArrayList();
+
+ IToken comment = new Token(SQL_COMMENT);
+ IToken string = new Token(SQL_STRING);
+ IToken identifier = new Token(SQL_IDENTIFIER);
+ IToken keyword = new Token(SQL_KEYWORD);
+ IToken separator = new Token(SQL_SEPARATOR);
+ IToken symbol = new Token(SQL_SYMBOL);
+ IToken whitespace = new Token(IDocument.DEFAULT_CONTENT_TYPE);
+ IToken numeric = new Token(SQL_NUMERIC);
+
+ rules.add(new PredicateRuleAdapter(new WhitespaceRule(new WhitespaceDetector()), whitespace));
+ rules.add(new MultiLineRule("/*", "*/", comment)); //$NON-NLS-1$ //$NON-NLS-2$
+ rules.add(new EndOfLineRule("--", comment)); //$NON-NLS-1$
+ rules.add(new SingleLineRule("'", "'", string)); //$NON-NLS-1$ //$NON-NLS-2$
+ rules.add(new PredicateRuleAdapter(new SQLNumberRule(numeric), numeric));
+ SQLWordRule wordRule = new SQLWordRule(identifier);
+ for (int i = 0; i < KEYWORDS.length; i++) {
+ wordRule.addKeyword(KEYWORDS[i], keyword);
+ }
+ rules.add(new PredicateRuleAdapter(wordRule, keyword));
+ rules.add(new PredicateRuleAdapter(wordRule, identifier));
+ rules.add(new PredicateRuleAdapter(new SQLSeparatorRule(separator), separator));
+ rules.add(new PredicateRuleAdapter(new SymbolRule(symbol), symbol));
+
+ IPredicateRule[] result= new IPredicateRule[rules.size()];
+ rules.toArray(result);
+ setPredicateRules(result);
+ }
+}
+
+class PredicateRuleAdapter implements IPredicateRule {
+ IRule rule;
+ IToken token;
+ public PredicateRuleAdapter(IRule rule, IToken token) {
+ this.rule = rule;
+ this.token = token;
+ }
+
+ public IToken evaluate(ICharacterScanner scanner, boolean resume) {
+ return rule.evaluate(scanner);
+ }
+
+ public IToken getSuccessToken() {
+ return token;
+ }
+
+ public IToken evaluate(ICharacterScanner scanner) {
+ return rule.evaluate(scanner);
+ }
+
+}
+
+class SQLSeparatorRule implements IRule {
+ IToken token;
+ public SQLSeparatorRule(IToken token) {
+ this.token = token;
+ }
+ public IToken evaluate(ICharacterScanner scanner) {
+ char c = (char) scanner.read();
+ if (c == ';') {
+ return token;
+ }
+ scanner.unread();
+ return Token.UNDEFINED;
+ }
+
+}
+
+class SymbolRule implements IRule {
+ IToken token;
+ public SymbolRule(IToken token) {
+ this.token = token;
+ }
+ public IToken evaluate(ICharacterScanner scanner) {
+ int val = scanner.read();
+ if (val != ICharacterScanner.EOF) {
+ char c = (char) val;
+ if (!Character.isWhitespace(c) && !Character.isLetterOrDigit(c) && c != '_') {
+ return token;
+ }
+ }
+ scanner.unread();
+ return Token.UNDEFINED;
+ }
+
+}
+
+class WhitespaceDetector implements IWhitespaceDetector {
+
+ public boolean isWhitespace(char c) {
+ return Character.isWhitespace(c);
+ }
+}
+
+class SQLNumberRule implements IRule {
+ private IToken token;
+
+ public SQLNumberRule(IToken token) {
+ this.token = token;
+ }
+
+ public IToken evaluate(ICharacterScanner scanner) {
+ char c = (char) scanner.read();
+ if (Character.isDigit(c)) {
+ // postive numbers and zero
+ do {
+ c= (char) scanner.read();
+ } while (Character.isDigit(c) || c == '.');
+ scanner.unread();
+ return token;
+ } else if (c == '-') {
+ // negative numbers
+ c = (char) scanner.read();
+ if (Character.isDigit(c)) {
+ do {
+ c= (char) scanner.read();
+ } while (Character.isDigit(c) || c == '.');
+ scanner.unread();
+ return token;
+ } else {
+ scanner.unread();
+ scanner.unread();
+ return Token.UNDEFINED;
+ }
+ } else {
+ scanner.unread();
+ return Token.UNDEFINED;
+ }
+ }
+}
+
+class SQLWordRule implements IRule {
+ private IToken token;
+ private HashMap keywords = new HashMap();
+
+ public SQLWordRule(IToken token) {
+ this.token = token;
+ }
+
+ public void addKeyword(String word, IToken token) {
+ keywords.put(word.toUpperCase(), token);
+ }
+
+ public IToken evaluate(ICharacterScanner scanner) {
+ char c = (char) scanner.read();
+ if (Character.isLetter(c) || c == '_') {
+ StringBuffer value = new StringBuffer();
+ do {
+ value.append(c);
+ c= (char) scanner.read();
+ } while (Character.isLetterOrDigit(c) || c == '_');
+ scanner.unread();
+ IToken retVal = (IToken) keywords.get(value.toString().toUpperCase());
+ if (retVal != null) {
+ return retVal;
+ } else {
+ return token;
+ }
+ } else {
+ scanner.unread();
+ return Token.UNDEFINED;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Created on 17/02/2004
+ *
+ */
+package com.quantum.extensions;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.Iterator;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.xml.ModelToXMLConverter;
+import com.quantum.sql.TableRow;
+import com.quantum.sql.metadata.MetaDataXMLInterface;
+import com.quantum.util.xml.XMLHelper;
+import com.quantum.view.bookmark.BookmarkView;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.bookmark.TreeNode;
+import com.quantum.view.tableview.TableView;
+
+/**
+ * @author panic
+ *
+ * Defines an Action Class to implement extension Actions.
+ * An external plug-in that wants to extend quantum will
+ * generate one ExtensionAction object for each action it
+ * wants to perform.
+ */
+public class ExtensionAction extends SelectionListenerAction {
+ private IViewPart view;
+ private IQuantumExtension extension;
+ private TableRow tableRow;
+
+ public ExtensionAction(IViewPart view, String label, String toolTip, IQuantumExtension extension) {
+ super(label);
+ this.view = view;
+ this.extension = extension;
+
+ setText(label);
+ setToolTipText(toolTip); //$NON-NLS-1$
+ tableRow = null;
+ }
+
+ public void run() {
+ if (extension instanceof IMetadataExtension && view instanceof BookmarkView)
+ runMetadataExtension();
+ else if (extension instanceof IDataExtension && view instanceof TableView)
+ runDataExtension();
+ }
+
+ /**
+ *
+ */
+ private void runDataExtension() {
+ IDataExtension dataExtension = (IDataExtension) extension;
+ if (tableRow == null) return;
+ Document doc;
+ try {
+ doc = XMLHelper.createEmptyDocument();
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ return;
+ }
+ Element root = (Element) doc.appendChild(doc.createElement(Messages.getString("ExportXMLAction.Metadata"))); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(root, Messages.getString("ExportXMLAction.Author"), //$NON-NLS-1$
+ Messages.getString("ExportXMLAction.Quantum")); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(root, Messages.getString("ExportXMLAction.Version"), //$NON-NLS-1$
+ Messages.getString("ExportXMLAction.XMLVersionNumber")); //$NON-NLS-1$
+ ModelToXMLConverter.getInstance().convert(root, tableRow.getEntity() );
+ MetaDataXMLInterface.stringMatrixToXML(tableRow.getRowTableData(), doc, root, "DataRow"); //$NON-NLS-1$
+
+ dataExtension.run(doc);
+ }
+
+ private void runMetadataExtension() {
+ IMetadataExtension metadataExtension = (IMetadataExtension) extension;
+ BookmarkView bookmarkView = (BookmarkView) view;
+ StructuredSelection selection = bookmarkView.getSelection();
+ if (selection == null) return;
+ Document doc;
+ try {
+ doc = XMLHelper.createEmptyDocument();
+ } catch (ParserConfigurationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return;
+ }
+ Element root = (Element) doc.appendChild(doc.createElement(Messages.getString("ExportXMLAction.Metadata"))); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(root, Messages.getString("ExportXMLAction.Author"), //$NON-NLS-1$
+ Messages.getString("ExportXMLAction.Quantum")); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(root, Messages.getString("ExportXMLAction.Version"), //$NON-NLS-1$
+ Messages.getString("ExportXMLAction.XMLVersionNumber")); //$NON-NLS-1$
+ Iterator iter = selection.iterator();
+ while (iter.hasNext()) {
+ TreeNode current = (TreeNode) iter.next();
+ EntityNode entityNode = (EntityNode) current;
+ ModelToXMLConverter.getInstance().convert(root, entityNode.getEntity() );
+ }
+
+ StringWriter text = new StringWriter();
+ try {
+ XMLHelper.createDOMSerializer(text).serialize(doc);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ String textXml = new String(text.getBuffer());
+ QuantumPlugin.getDefault().getSysClip().setContents(
+ new Object[] { textXml },
+ new Transfer[] { TextTransfer.getInstance()});
+
+ metadataExtension.run(doc);
+ }
+
+ /**
+ * @param row
+ */
+ public void addRowData(TableRow row) {
+ tableRow = row;
+ }
+
+}
--- /dev/null
+/*
+ * Created on 21/03/2004
+ *
+ */
+package com.quantum.extensions;
+
+import org.w3c.dom.Document;
+
+/**
+ * @author panic
+ *
+ */
+public interface IDataExtension extends IQuantumExtension {
+ /**
+ * Callback method for data export
+ *
+ * @param doc. An org.w3c.dom.Document with the XML data on the selected items
+ */
+ public void run(Document doc);
+
+}
--- /dev/null
+/*
+ * Created on 15/02/2004
+ *
+ */
+package com.quantum.extensions;
+
+import org.w3c.dom.Document;
+
+/**
+ * @author panic
+ *
+ */
+public interface IMetadataExtension extends IQuantumExtension{
+ /**
+ * Callback method for metadata export
+ *
+ * @param doc. An org.w3c.dom.Document with the XML data on the selected items
+ */
+ public void run(Document doc);
+
+}
--- /dev/null
+/*
+ * Created on 17/02/2004
+ *
+ */
+package com.quantum.extensions;
+
+/**
+ * @author panic
+ * A commom parent for the Quantum Extensions
+ */
+public interface IQuantumExtension {
+
+}
--- /dev/null
+
+/*
+ * Created on 16-feb-2004
+ *
+ */
+package com.quantum.extensions;
+import java.util.Vector;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IPluginRegistry;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.WorkbenchException;
+import org.w3c.dom.Document;
+
+import com.quantum.view.bookmark.BookmarkView;
+import com.quantum.view.tableview.TableView;
+
+/**
+ * Extension processing logic for the <code>functions</code> extension-point.
+ * Extract specific information about each function. Create callback
+ * function object when required.
+ *
+ * @author panic
+ *
+ */
+public class ProcessServiceMembers {
+
+ /**
+ * The fully-qualified name of the functions extension-point for this plug-in.
+ */
+ private static final String EXTENSION_POINT_METADATA =
+ "com.quantum.Quantum.metadata";
+ private static final String EXTENSION_POINT_DATA =
+ "com.quantum.Quantum.data";
+
+ /**
+ * Name of the XML attribute designating a metadata actor label.
+ */
+ private static final String FUNCTION_NAME_ATTRIBUTE = "label";
+
+ /**
+ * Name of the XML attribute designating the fully-qualified name
+ * of the implementation class of a function.
+ */
+ private static final String CLASS_ATTRIBUTE = "class";
+
+ /**
+ * Perform initial extension processing for the members of the
+ * <code>functions</code> extension-point. Make calls to the user interface
+ * module to add the functions of an extension to the UI functions grid.
+ * For each function, a virtual proxy callback object is created and handed
+ * to the user interface module. The proxy class is a nested top-level
+ * class and is therefore known at compile time. The actual (real) callback
+ * objects configured into extensions are instantiated and initialized in
+ * a lazy fashion by the proxy callback objects.
+ *
+ * @param grid The UI functions grid exposing the functions configured
+ * into <code>functions</code> extensions.
+ *
+ */
+ public static void process(IViewPart view, Vector extensionActions) throws WorkbenchException {
+
+ extensionActions.clear();
+
+ IPluginRegistry registry = Platform.getPluginRegistry();
+ String extPointId;
+ // We have two different extension points, we choose the needed one based
+ // on the view that calls this function.
+ // Our two extension points have the same attributes, so the only change is the name
+ // If the implementation differed more, we should probably make two different functions
+ if (view instanceof BookmarkView)
+ extPointId = EXTENSION_POINT_METADATA;
+ else if (view instanceof TableView)
+ extPointId = EXTENSION_POINT_DATA;
+ else
+ return;
+
+ IExtensionPoint extensionPoint =
+ registry.getExtensionPoint(extPointId);
+ if (extensionPoint == null) {
+ throw new WorkbenchException(
+ "unable to resolve extension-point: " + extPointId);
+ }
+ IConfigurationElement[] members =
+ extensionPoint.getConfigurationElements();
+
+ // For each service:
+ for (int m = 0; m < members.length; m++) {
+ IConfigurationElement member = members[m];
+ // Get the label of the extender plugin and the ID of the extension.
+ IExtension extension = member.getDeclaringExtension();
+ String pluginLabel =
+ extension.getDeclaringPluginDescriptor().getLabel();
+ if (pluginLabel == null) {
+ pluginLabel = "[unnamed plugin]";
+ }
+ // Get the name of the operation implemented by the service.
+ // The operation name is a service attribute in the extension's XML specification.
+ String functionName = member.getAttribute(FUNCTION_NAME_ATTRIBUTE);
+ if (functionName == null) {
+ functionName = "[unnamed function]";
+ }
+ String label = pluginLabel + "/" + functionName;
+ // Add a row to support this operation to the UI grid.
+ IQuantumExtension proxy = null;
+ if (view instanceof BookmarkView)
+ proxy = (IMetadataExtension) new MetadataFunctionProxy(member);
+ else if (view instanceof TableView)
+ proxy = (IDataExtension) new DataFunctionProxy(member);
+ //grid.addFunction(proxy, functionName, label);
+ extensionActions.add(new ExtensionAction(view, label, label, proxy));
+ }
+ }
+
+ /**
+ * Virtual proxy class for function invokation.
+ * Members of this class support lazy processing by fronting the real
+ * implementations of arithmetic functions configured into extensions.
+ */
+ private static class MetadataFunctionProxy implements IMetadataExtension {
+ // The "real" implementation of the function.
+ private IMetadataExtension delegate = null;
+ // The configured state of the extension element representing this arithmetic function.
+ private IConfigurationElement element;
+ // Whether this function has been invoked before.
+ // Used for lazy evaluation of the service.
+ private boolean invoked = false;
+
+ /**
+ * Construct a virtual proxy to stand in place of an extension function.
+ * The constructor simply keeps track of an arithmetic function's configured state
+ * without at this time instantiating the implementation of the function.
+ *
+ * @param element The configuration of this arithmetic function.
+ */
+ public MetadataFunctionProxy(IConfigurationElement element) {
+ this.element = element;
+ }
+
+ /**
+ * Compute the function value.
+ * The proxy computation first instantiates the implementation
+ * of the function, if this is the first time the function is called,
+ * and then delegates to that implementation. The instantiation and
+ * initialization of the delegate implementation uses the standard
+ * callback object instantiation and initialization methods of Eclipse.
+ *
+ * @see com.bolour.sample.eclipse.service.ui.IFunction#compute(long)
+ */
+ public final void run(Document doc) {
+ try {
+ getDelegate().run(doc);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Instantiate and initialize the implementation of the function if
+ * this is the first time the proxy has been called.
+ *
+ * @return The implementation delegate (same as the instance variable <code>delegate</code>.
+ * @throws Exception If the callback object is misconfigured.
+ */
+ private final IMetadataExtension getDelegate() throws Exception {
+ if (invoked) {
+ return delegate;
+ }
+ invoked = true;
+ try {
+ Object callback =
+ element.createExecutableExtension(CLASS_ATTRIBUTE);
+ if (!(callback instanceof IMetadataExtension)) {
+ String message =
+ "callback class '"
+ + callback.getClass().getName()
+ + "' is not an IFunction";
+ System.err.println(message);
+ throw new ClassCastException(message);
+ }
+ delegate = (IMetadataExtension) callback;
+ } catch (CoreException ex) {
+ System.err.println(ex.getMessage());
+ ex.printStackTrace();
+ throw ex;
+ } catch (Error err) {
+ System.err.println(err.getMessage());
+ err.printStackTrace();
+ throw err;
+ }
+ return delegate;
+ }
+ }
+ /**
+ * Virtual proxy class for function invokation.
+ * Members of this class support lazy processing by fronting the real
+ * implementations of arithmetic functions configured into extensions.
+ */
+ private static class DataFunctionProxy implements IDataExtension {
+ // The "real" implementation of the function.
+ private IDataExtension delegate = null;
+ // The configured state of the extension element representing this arithmetic function.
+ private IConfigurationElement element;
+ // Whether this function has been invoked before.
+ // Used for lazy evaluation of the service.
+ private boolean invoked = false;
+
+ /**
+ * Construct a virtual proxy to stand in place of an extension function.
+ * The constructor simply keeps track of an arithmetic function's configured state
+ * without at this time instantiating the implementation of the function.
+ *
+ * @param element The configuration of this arithmetic function.
+ */
+ public DataFunctionProxy(IConfigurationElement element) {
+ this.element = element;
+ }
+
+ /**
+ * Compute the function value.
+ * The proxy computation first instantiates the implementation
+ * of the function, if this is the first time the function is called,
+ * and then delegates to that implementation. The instantiation and
+ * initialization of the delegate implementation uses the standard
+ * callback object instantiation and initialization methods of Eclipse.
+ *
+ * @see com.bolour.sample.eclipse.service.ui.IFunction#compute(long)
+ */
+ public final void run(Document doc) {
+ try {
+ getDelegate().run(doc);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Instantiate and initialize the implementation of the function if
+ * this is the first time the proxy has been called.
+ *
+ * @return The implementation delegate (same as the instance variable <code>delegate</code>.
+ * @throws Exception If the callback object is misconfigured.
+ */
+ private final IDataExtension getDelegate() throws Exception {
+ if (invoked) {
+ return delegate;
+ }
+ invoked = true;
+ try {
+ Object callback =
+ element.createExecutableExtension(CLASS_ATTRIBUTE);
+ if (!(callback instanceof IDataExtension)) {
+ String message =
+ "callback class '"
+ + callback.getClass().getName()
+ + "' is not an IFunction";
+ System.err.println(message);
+ throw new ClassCastException(message);
+ }
+ delegate = (IDataExtension) callback;
+ } catch (CoreException ex) {
+ System.err.println(ex.getMessage());
+ ex.printStackTrace();
+ throw ex;
+ } catch (Error err) {
+ System.err.println(err.getMessage());
+ err.printStackTrace();
+ throw err;
+ }
+ return delegate;
+ }
+ }
+
+}
+
--- /dev/null
+package com.quantum.model;
+
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.quantum.IQuantumConstants;
+import com.quantum.QuantumPlugin;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.sql.ConnectionEstablisher;
+import com.quantum.sql.MultiSQLServer;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+
+/**
+ * Class Bookmark holds the "static" information of a bookmark, that is the data that
+ * is saved and loaded from the external file and describes a bookmark. This info will
+ * be filled up by the end user.
+ *
+ * @author root
+ */
+public class Bookmark {
+
+ private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
+ private String name = ""; //$NON-NLS-1$
+ private String username = ""; //$NON-NLS-1$
+ private String password = ""; //$NON-NLS-1$
+ private String connect = ""; //$NON-NLS-1$
+ private String driver = ""; //$NON-NLS-1$
+ private String type = ""; //$NON-NLS-1$
+ private String driverFile = ""; //$NON-NLS-1$
+
+ /**
+ * A quick list is a list of favourite tables that a person might want to view
+ * without having to look at the entire list of tables.
+ */
+ private Map quickList = new Hashtable();
+ private Set schemas = new HashSet();
+ private Connection connection = null;
+ private ConnectionEstablisher connectionEstablisher;
+ private boolean changed = true;
+ private List queries = Collections.synchronizedList(new ArrayList());
+ private boolean promptForPassword = false;
+ private boolean autoCommit = true;
+ private String autoCommitPreference = IQuantumConstants.autoCommitTrue;
+
+ public Bookmark() {
+ this(MultiSQLServer.getInstance());
+ }
+
+ public Bookmark(ConnectionEstablisher connectionEstablisher) {
+ this.connectionEstablisher = connectionEstablisher;
+ }
+
+ public Bookmark(Bookmark data) {
+ this();
+ setName(data.getName());
+ setUsername(data.getUsername());
+ setPassword(data.getPassword());
+ setConnect(data.getConnect());
+ setDriver(data.getDriver());
+ setType(data.getType());
+ setDriverFile(data.getDriverFile());
+ setPromptForPassword(data.getPromptForPassword());
+ setAutoCommit(data.isAutoCommit());
+ setAutoCommitPreference(data.getAutoCommitPreference());
+
+ this.schemas.addAll(data.schemas);
+ this.quickList = new Hashtable(data.quickList);
+ }
+
+ /**
+ * Returns the JDBC URL.
+ * @return String
+ */
+ public String getConnect() {
+ return connect;
+ }
+
+ /**
+ * Returns the driver.
+ * @return String
+ */
+ public String getDriver() {
+ return driver;
+ }
+
+ /**
+ * Returns the driverFile.
+ * @return String
+ */
+ public String getDriverFile() {
+ return driverFile;
+ }
+
+ /**
+ * Returns the password.
+ * @return String
+ */
+ public String getPassword() {
+ return password;
+ }
+
+ /**
+ * Returns the username.
+ * @return String
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /**
+ * Sets the connect.
+ * @param connect The connect to set
+ */
+ public void setConnect(String connect) {
+ if (connect == null) {
+ connect = ""; //$NON-NLS-1$
+ }
+ this.connect = connect;
+ }
+
+ /**
+ * Sets the driver.
+ * @param driver The driver to set
+ */
+ public void setDriver(String driver) {
+ if (driver == null) {
+ driver = ""; //$NON-NLS-1$
+ }
+ this.driver = driver;
+ }
+
+ /**
+ * Sets the driverFile.
+ * @param driverFile The driverFile to set
+ */
+ public void setDriverFile(String driverFile) {
+ if (driverFile == null) {
+ driverFile = ""; //$NON-NLS-1$
+ }
+ this.driverFile = driverFile;
+ }
+
+ /**
+ * Sets the password.
+ * @param password The password to set
+ */
+ public void setPassword(String password) {
+ if (password == null) {
+ password = ""; //$NON-NLS-1$
+ }
+ this.password = password;
+ }
+
+ /**
+ * Sets the username.
+ * @param username The username to set
+ */
+ public void setUsername(String username) {
+ if (username == null) {
+ username = ""; //$NON-NLS-1$
+ }
+ this.username = username;
+ }
+
+ /**
+ * Returns the name.
+ * @return String
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Sets the name.
+ * @param name The name to set
+ */
+ public void setName(String name) {
+ if (name == null) {
+ name = ""; //$NON-NLS-1$
+ }
+ if (!name.equals(this.name)) {
+
+ String oldName = this.name;
+ this.name = name;
+ this.propertyChangeSupport.firePropertyChange("name", oldName, this.name);
+ this.changed = true;
+ }
+ }
+
+ public boolean isEmpty() {
+ if (name.equals("") && //$NON-NLS-1$
+ username.equals("") && //$NON-NLS-1$
+ password.equals("") && //$NON-NLS-1$
+ connect.equals("") && //$NON-NLS-1$
+ driver.equals("") && //$NON-NLS-1$
+ type.equals("") && //$NON-NLS-1$
+ driverFile.equals("")) { //$NON-NLS-1$
+ return true;
+ }
+ return false;
+ }
+ public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("["); //$NON-NLS-1$
+ buffer.append("name="); //$NON-NLS-1$
+ buffer.append(name);
+ buffer.append(", "); //$NON-NLS-1$
+ buffer.append("username="); //$NON-NLS-1$
+ buffer.append(username);
+ buffer.append(", "); //$NON-NLS-1$
+ buffer.append("password=****"); //$NON-NLS-1$
+ buffer.append(", "); //$NON-NLS-1$
+ buffer.append("connect="); //$NON-NLS-1$
+ buffer.append(connect);
+ buffer.append(", "); //$NON-NLS-1$
+ buffer.append("driver="); //$NON-NLS-1$
+ buffer.append(driver);
+ buffer.append(", "); //$NON-NLS-1$
+ buffer.append("type="); //$NON-NLS-1$
+ buffer.append(type);
+ buffer.append(", "); //$NON-NLS-1$
+ buffer.append("driverFile="); //$NON-NLS-1$
+ buffer.append(driverFile);
+ buffer.append("]"); //$NON-NLS-1$
+ return buffer.toString();
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public Connection connect(PasswordFinder passwordFinder) throws ConnectionException {
+ boolean isConnected = isConnected();
+ if (this.connection == null) {
+ this.connection = this.connectionEstablisher.connect(this, passwordFinder);
+ }
+
+ if (isConnected() != isConnected) {
+ this.propertyChangeSupport.firePropertyChange(
+ "connected", isConnected, isConnected());
+ }
+ return this.connection;
+ }
+
+ /**
+ * Returns the connection object.
+ * @return the Connection object associated with the current JDBC source.
+ *
+ */
+ public Connection getConnection() throws NotConnectedException {
+ if (this.connection == null) {
+ throw new NotConnectedException();
+ }
+ return this.connection;
+ }
+
+ /**
+ * @return true if the BookmarkNode is connected to a JDBC source
+ */
+ public boolean isConnected() {
+ return (connection != null);
+ }
+
+ /**
+ * Sets the connection member. From that moment on the BookmarkNode is "connected" (open)
+ * @param connection : a valid connection to a JDBC source
+ */
+ public void setConnection(Connection connection) {
+ this.connection = connection;
+ }
+
+ public void disconnect() throws ConnectionException {
+ boolean isConnected = isConnected();
+ try {
+ if (this.connection != null) {
+ this.connectionEstablisher.disconnect(this.connection);
+ }
+ } finally {
+ this.connection = null;
+ if (isConnected() != isConnected) {
+ this.propertyChangeSupport.firePropertyChange(
+ "connected", isConnected, isConnected());
+ }
+ }
+ }
+ public void addSchema(String schema) {
+ if (schema != null && schema.trim().length() > 0) {
+ addSchema(new Schema(schema));
+ }
+ }
+
+ public void addSchema(Schema qualifier) {
+ if (qualifier != null) {
+ this.schemas.add(qualifier);
+ this.changed = true;
+ this.propertyChangeSupport.firePropertyChange("schemas", null, null);
+ }
+ }
+
+ public void setSchemas(Schema[] schemas) {
+ this.schemas.clear();
+ for (int i = 0, length = (schemas == null) ? 0 : schemas.length;
+ i < length;
+ i++) {
+ this.schemas.add(schemas[i]);
+
+ }
+ this.changed = true;
+ this.propertyChangeSupport.firePropertyChange("schemas", null, null);
+ }
+
+ /**
+ * @return a list of all the schemas that have been set up.
+ */
+ public Schema[] getSchemas() {
+ Set set = new HashSet();
+ set.addAll(this.schemas);
+ if (set.isEmpty()) {
+ set.add(new Schema(getAdapter().getDefaultSchema(this.username),
+ this.username, true));
+ }
+ List list = new ArrayList(set);
+ Collections.sort(list);
+ return (Schema[]) list.toArray(new Schema[list.size()]);
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof Bookmark)) return false;
+ String name = ((Bookmark)obj).getName();
+ if (name.equals(this.getName())) return true;
+ return false;
+ }
+
+ /**
+ * @param listener
+ */
+ public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
+ this.propertyChangeSupport.addPropertyChangeListener(listener);
+ }
+
+ /**
+ * @param listener
+ */
+ public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
+ this.propertyChangeSupport.removePropertyChangeListener(listener);
+ }
+
+ public void addQuickListEntry(String type, String schemaName, String name) {
+ Entity entity = EntityFactory.getInstance().create(this, schemaName, name, type);
+ this.quickList.put(entity.getCondQualifiedName(), entity);
+ this.propertyChangeSupport.firePropertyChange("quickList", null, null);
+ this.changed = true;
+ }
+
+ public void addQuickListEntry(Entity entity) {
+ addQuickListEntry(entity.getType(), entity.getSchema(), entity.getName());
+ }
+
+ public void removeQuickListEntry(Entity entity) {
+ if (entity != null && this.quickList.containsKey(entity.getCondQualifiedName())) {
+ this.quickList.remove(entity.getCondQualifiedName());
+ this.propertyChangeSupport.firePropertyChange("quickList", null, null);
+ this.changed = true;
+ }
+ }
+
+ public Entity[] getQuickListEntries() {
+ return (Entity[]) this.quickList.values().toArray(new Entity[this.quickList.size()]);
+ }
+
+ public boolean hasQuickList() {
+ return !this.quickList.isEmpty();
+ }
+ /**
+ * @return
+ */
+ public boolean isChanged() {
+ return changed;
+ }
+
+ /**
+ * @param b
+ */
+ public void setChanged(boolean b) {
+ changed = b;
+ }
+
+ public Database getDatabase() throws NotConnectedException {
+ if (!isConnected()) {
+ throw new NotConnectedException();
+ }
+ return new Database(this);
+ }
+
+ public DatabaseAdapter getAdapter() {
+ return AdapterFactory.getInstance().getAdapter(getType());
+ }
+
+ public Entity[] getEntitiesForSchema(Schema schema, String type) throws SQLException {
+ try {
+ Entity[] entities = getDatabase().getEntities(this, schema, type);
+ return entities;
+ } catch (NotConnectedException e) {
+ return new Entity[0];
+ }
+ }
+
+ public Entity getEntity(Schema schema, String name) throws SQLException {
+ Entity result = null;
+ if (schema != null && name != null) {
+ Entity[] entities = getEntitiesForSchema(schema, null);
+ for (int i = 0, length = (entities == null) ? 0 : entities.length;
+ result == null && i < length;
+ i++) {
+ if (schema.equals(entities[i].getSchema()) &&
+ name.equals(entities[i].getName())) {
+ result = entities[i];
+ }
+ }
+ }
+ return result;
+ }
+
+ public boolean isInQuickList(Entity entity) {
+ return this.quickList.containsKey(entity.getCondQualifiedName());
+ }
+
+ /**
+ *
+ * @param queryString
+ */
+ public void addQuery(String queryString) {
+ if (this.queries.contains(queryString)) {
+ this.queries.remove(queryString);
+ }
+ this.queries.add(queryString);
+
+ int size = getQueryHistorySize();
+
+ while (this.queries.size() > size) {
+ this.queries.remove(0);
+ }
+ this.propertyChangeSupport.firePropertyChange("queries", null, null);
+ this.changed = true;
+ }
+
+ public String[] getQueries() {
+ return (String[]) this.queries.toArray(new String[this.queries.size()]);
+ }
+
+ private int getQueryHistorySize() {
+ IPreferenceStore store =
+ QuantumPlugin.getDefault().getPreferenceStore();
+ return store.getInt(getClass().getName() + ".queryHistorySize"); //$NON-NLS-1$
+ }
+ /**
+ * @return
+ */
+ public boolean getPromptForPassword() {
+ return promptForPassword;
+ }
+
+ /**
+ * @param b
+ */
+ public void setPromptForPassword(boolean b) {
+ promptForPassword = b;
+ }
+
+ /**
+ * @return
+ */
+ public boolean isAutoCommit() {
+ return autoCommit;
+ }
+
+ /**
+ * @return
+ */
+ public String getAutoCommitPreference() {
+ return autoCommitPreference;
+ }
+
+ /**
+ * @param b
+ */
+ public void setAutoCommit(boolean b) {
+ autoCommit = b;
+ }
+
+ /**
+ * @param string
+ */
+ public void setAutoCommitPreference(String string) {
+ autoCommitPreference = string;
+ }
+
+ // Returns true or false indicating whether this bookmark must be set to AutoCommit on connection or not
+ public boolean getDefaultAutoCommit(){
+ if (autoCommitPreference.equals(IQuantumConstants.autoCommitTrue)) return true;
+ else if (autoCommitPreference.equals(IQuantumConstants.autoCommitFalse)) return false;
+ else if (autoCommitPreference.equals(IQuantumConstants.autoCommitSaved)) return autoCommit;
+
+ return true;
+ }
+
+}
--- /dev/null
+package com.quantum.model;
+
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
+
+import com.quantum.IQuantumConstants;
+import com.quantum.Messages;
+import com.quantum.model.xml.ModelToXMLConverter;
+import com.quantum.sql.metadata.MetaDataXMLInterface;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * The collection of database bookmarks that the Quantum plug-in knows about.
+ * This collection is loaded by the QuantumPlugin class before any Quantum plugin
+ * extension is invoked.
+ *
+ * @author BC
+ */
+public class BookmarkCollection {
+
+ private static BookmarkCollection instance = new BookmarkCollection();
+ private List bookmarks = new Vector();
+ private boolean changed = false;
+ private PropertyChangeSupport support = new PropertyChangeSupport(this);
+
+ private BookmarkCollection() {
+ }
+
+ /**
+ * Singleton accessor
+ */
+ public static BookmarkCollection getInstance() {
+ return BookmarkCollection.instance;
+ }
+
+ /**
+ * Imports the bookmars from a properties file. This load method is
+ * provided for backwards compatability only; we no longer persist
+ * bookmarks as properties files.
+ * @param file
+ */
+ public void load(File file) throws IOException {
+ Properties props = new Properties();
+ FileInputStream in = new FileInputStream(file);
+ props.load(in);
+ in.close();
+ fromProperties(true, props);
+ }
+
+ private void fromProperties(boolean overwrite, Properties props) {
+ List newBookmarks = new Vector();
+ int i = 0;
+ while (true) {
+ Bookmark bookmark = new Bookmark();
+ String name = props.getProperty(i + ".name"); //$NON-NLS-1$
+ if (name == null) {
+ break;
+ }
+ bookmark.setName(name);
+ bookmark.setUsername(props.getProperty(i + ".username")); //$NON-NLS-1$
+ bookmark.setPassword(props.getProperty(i + ".password")); //$NON-NLS-1$
+ bookmark.setConnect(props.getProperty(i + ".connect")); //$NON-NLS-1$
+ bookmark.setDriver(props.getProperty(i + ".driver")); //$NON-NLS-1$
+ String schema = props.getProperty(i + ".schema"); //$NON-NLS-1$
+ if (schema != null) {
+ bookmark.addSchema(schema);
+ }
+ String type = props.getProperty(i + ".type"); //$NON-NLS-1$
+ if (type != null) {
+ bookmark.setType(type);
+ } else {
+ bookmark.setType(""); //$NON-NLS-1$
+ }
+ String driverFile = props.getProperty(i + ".driverLocation"); //$NON-NLS-1$
+ if (driverFile != null) {
+ bookmark.setDriverFile(driverFile);
+ } else {
+ bookmark.setDriverFile(""); //$NON-NLS-1$
+ }
+ System.out.println(bookmark.toString());
+ if (!bookmark.isEmpty()) {
+ newBookmarks.add(bookmark);
+ }
+ i++;
+ }
+ if (overwrite) {
+ this.bookmarks = newBookmarks;
+ } else {
+ this.bookmarks.addAll(newBookmarks);
+ }
+ }
+ /**
+ * Finds a Bookmark with the specified name.
+ *
+ * @param name
+ * @return the bookmark with the specified name, or null if no bookmark can be found
+ */
+ public Bookmark find(String name){
+ Bookmark result = null;
+ if (name != null) {
+ for (Iterator i = this.bookmarks.iterator(); result == null && i.hasNext(); ) {
+ Bookmark temp = (Bookmark) i.next();
+ if (name.equals(temp.getName())) {
+ result = temp;
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Exports a Bookmark data to an XMLDocument Element
+ * The complementary function is importXML()
+ * @param root The Element to fill up with the bookmark info
+ */
+ public void exportXML(Element root) {
+ System.out.println("Bookmarks: Saving to Element"); //$NON-NLS-1$
+ Element bookmarkRoot = MetaDataXMLInterface.createElementText(root,"bookmarks", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ for (int i = 0; i < bookmarks.size(); i++) {
+ Bookmark b = (Bookmark) bookmarks.get(i);
+ ModelToXMLConverter.getInstance().convert(bookmarkRoot, b);
+ }
+ }
+
+ /**
+ * Imports a Bookmark data from an XMLDocument Element
+ * The complementary function is exportXML()
+ * @param root The Element from which to load
+ */
+ public void importXML(Element root) {
+ this.changed = true;
+ System.out.println("Bookmarks: Loading from Element"); //$NON-NLS-1$
+ Vector newBookmarks = new Vector();
+ NodeList nodes = root.getElementsByTagName("bookmark"); //$NON-NLS-1$
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Bookmark bookmark = new Bookmark();
+ Element column = (Element) nodes.item(i);
+
+ String name = MetaDataXMLInterface.getElementText(column,"name"); //$NON-NLS-1$
+ if (name == null) break;
+ bookmark.setName(name);
+
+ MetaDataXMLInterface.getElementText(column,"name"); //$NON-NLS-1$
+ bookmark.setUsername(MetaDataXMLInterface.getElementText(column,"username")); //$NON-NLS-1$
+ bookmark.setPassword(MetaDataXMLInterface.getElementText(column,"password")); //$NON-NLS-1$
+ bookmark.setPromptForPassword(Boolean.TRUE.toString().equalsIgnoreCase(
+ MetaDataXMLInterface.getElementText(column,"prompt"))); //$NON-NLS-1$
+ bookmark.setConnect(MetaDataXMLInterface.getElementText(column,"connect")); //$NON-NLS-1$
+ bookmark.setAutoCommit(Boolean.TRUE.toString().equalsIgnoreCase(
+ MetaDataXMLInterface.getElementText(column,"autoCommit", "True"))); //$NON-NLS-1$
+ bookmark.setAutoCommitPreference(MetaDataXMLInterface.getElementText(column,"autoCommitPreference", IQuantumConstants.autoCommitTrue)); //$NON-NLS-1$
+ bookmark.setDriver(MetaDataXMLInterface.getElementText(column,"driver")); //$NON-NLS-1$
+ bookmark.addSchema(MetaDataXMLInterface.getElementText(column,"schema")); //$NON-NLS-1$
+ bookmark.setType(MetaDataXMLInterface.getElementText(column,"type")); //$NON-NLS-1$
+ bookmark.setDriverFile(MetaDataXMLInterface.getElementText(column,"driverLocation")); //$NON-NLS-1$
+ NodeList children = column.getElementsByTagName(Messages.getString("ExportXMLAction.OtherSchemas"));
+ if (children.getLength() > 0) {
+ importSchemas((Element) children.item(0), bookmark);
+ }
+ System.out.println(bookmark.toString());
+ if (!bookmark.isEmpty()) {
+ newBookmarks.addElement(bookmark);
+ }
+ importQuickList(bookmark, column);
+ importQueryList(bookmark, column);
+ }
+ this.bookmarks.addAll(newBookmarks);
+ this.support.firePropertyChange("bookmarks", null, null);
+ }
+
+ private void importSchemas(Element otherSchemas, Bookmark bookmark) {
+ Vector vector = MetaDataXMLInterface.getVectorText(otherSchemas, Messages.getString("ExportXMLAction.SchemaName"));
+ List list = new ArrayList();
+ for (Iterator i = vector.iterator(); i.hasNext();) {
+ String schemaName = (String) i.next();
+ list.add(new Schema(schemaName));
+ }
+ bookmark.setSchemas((Schema[]) list.toArray(new Schema[list.size()]));
+ }
+
+ private void importQuickList(Bookmark bookmark, Element bookmarkElement) {
+ NodeList quickList = bookmarkElement.getElementsByTagName("quickList");
+ for (int j = 0,
+ length = (quickList == null) ? 0 : quickList.getLength();
+ j < length;
+ j++) {
+
+ Element element = (Element) quickList.item(j);
+ NodeList childNodes = element.getChildNodes();
+
+ for (int k = 0,
+ length2 = (childNodes == null) ? 0 : childNodes.getLength();
+ k < length2;
+ k++) {
+ if (Node.ELEMENT_NODE == childNodes.item(k).getNodeType()) {
+ Element entity = (Element) childNodes.item(k);
+ bookmark.addQuickListEntry(entity.getTagName(),
+ entity.getAttribute("schema"), entity.getAttribute("name"));
+ }
+ }
+ }
+ }
+
+ private void importQueryList(Bookmark bookmark, Element bookmarkElement) {
+ NodeList queryList = bookmarkElement.getElementsByTagName("queryList");
+ for (int i = 0,
+ length = (queryList == null) ? 0 : queryList.getLength();
+ i < length;
+ i++) {
+
+ Element element = (Element) queryList.item(i);
+ NodeList childNodes = element.getElementsByTagName("query");
+
+ for (int k = 0,
+ length2 = (childNodes == null) ? 0 : childNodes.getLength();
+ k < length2;
+ k++) {
+
+ Element query = (Element) childNodes.item(k);
+ bookmark.addQuery(MetaDataXMLInterface.getElementText(query,"queryString"));
+
+ }
+ }
+ }
+
+ public void addBookmark(Bookmark b) {
+ this.changed = true;
+ if (!bookmarks.contains(b)) {
+ Bookmark[] original = getBookmarks();
+ bookmarks.add(b);
+ this.support.firePropertyChange("bookmarks", original, getBookmarks());
+ }
+ }
+ public void removeBookmark(Bookmark b) {
+ this.changed = true;
+ if (bookmarks.contains(b)) {
+ Bookmark[] original = getBookmarks();
+ bookmarks.remove(b);
+ this.support.firePropertyChange("bookmarks", original, getBookmarks());
+ }
+ }
+
+ public Bookmark[] getBookmarks() {
+ return (Bookmark[]) this.bookmarks.toArray(new Bookmark[this.bookmarks.size()]);
+ }
+ /**
+ * @return
+ */
+ public boolean isAnythingChanged() {
+ boolean anythingChanged = this.changed;
+ for (Iterator i = this.bookmarks.iterator(); !anythingChanged && i.hasNext();) {
+ Bookmark bookmark = (Bookmark) i.next();
+ anythingChanged |= bookmark.isChanged();
+ }
+ return anythingChanged;
+ }
+
+ public boolean isChanged() {
+ return this.changed;
+ }
+
+ /**
+ * @param b
+ */
+ public void setChanged(boolean changed) {
+ this.changed = changed;
+ }
+
+ /**
+ * @param listener
+ */
+ public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
+ this.support.addPropertyChangeListener(listener);
+ }
+
+ /**
+ * @param listener
+ */
+ public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
+ this.support.removePropertyChangeListener(listener);
+ }
+
+ /**
+ * @param string
+ * @return
+ */
+ public String getCopyName(String name) {
+
+ String copyName = Messages.getString("BookmarkView.CopyOf") + name;
+ int i = 1;
+ while (find(copyName) != null)
+ {
+ copyName = Messages.getString("BookmarkView.CopyOf") + name + "(" + String.valueOf(i) + ")";
+ i++;
+ }
+
+ return copyName;
+ }
+
+
+}
--- /dev/null
+/*
+ * Created on 22-jul-2003
+ *
+ */
+package com.quantum.model;
+
+
+/**
+ * User interface components that can provide a connection to the database they
+ * relate to implement this interface. Such components must know how to obtain a
+ * password, as required.
+ *
+ * @author panic
+ */
+public interface BookmarkHolder {
+ public Bookmark getBookmark();
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ *
+ * @author bcholmes
+ */
+public interface Column {
+ public int getSize();
+ public int getPrimaryKeyOrder();
+ public boolean isPrimaryKey();
+ public String getName();
+ public int getNumberOfFractionalDigits();
+ public String getTypeName();
+ public boolean isReal();
+ public boolean isNullable();
+ public boolean isNumeric();
+ public int getType();
+ public Entity getParentEntity();
+ public String getQualifiedTableName();
+ public String getRemarks();
+}
--- /dev/null
+package com.quantum.model;
+
+import com.quantum.sql.SQLHelper;
+
+/**
+ * @author BC
+ */
+class ColumnImpl implements Column, Comparable {
+
+ private int size;
+ private boolean nullable;
+ private int primaryKeyOrder;
+ private String name;
+ private Entity entity;
+ private int numberOfFractionalDigits;
+ private String typeName;
+ private int type;
+ private int position;
+ private String remarks;
+
+ ColumnImpl(Entity entity, String name, String typeName, int type,
+ int size, int numberOfFractionalDigits, boolean nullable, int position,
+ String remarks) {
+
+ this.entity = entity;
+ this.name = name;
+ this.typeName = typeName;
+ this.type = type;
+ this.size = size;
+ this.numberOfFractionalDigits = numberOfFractionalDigits;
+ this.nullable = nullable;
+ this.position = position;
+ this.remarks = remarks;
+ }
+
+ /**
+ * @see com.quantum.model.Column#getPrimaryKeyOrder()
+ */
+ public int getPrimaryKeyOrder() {
+ return this.primaryKeyOrder;
+ }
+
+ /**
+ * @see com.quantum.model.Column#isPrimaryKey()
+ */
+ public boolean isPrimaryKey() {
+ return getPrimaryKeyOrder() > 0;
+ }
+
+ /**
+ * @see com.quantum.model.Column#getName()
+ */
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * @see com.quantum.model.Column#getTypeName()
+ */
+ public String getTypeName() {
+ return this.typeName;
+ }
+
+ /**
+ * @see com.quantum.model.Column#isReal()
+ */
+ public boolean isReal() {
+ return false;
+ }
+
+ /**
+ * @see com.quantum.model.Column#isNullable()
+ */
+ public boolean isNullable() {
+ return this.nullable;
+ }
+
+ /**
+ * @see com.quantum.model.Column#isNumeric()
+ */
+ public boolean isNumeric() {
+ return SQLHelper.isNumeric(this.type);
+ }
+
+ /**
+ * @see com.quantum.model.Column#getType()
+ */
+ public int getType() {
+ return this.type;
+ }
+
+ /**
+ * @see com.quantum.model.Column#getParentEntity()
+ */
+ public Entity getParentEntity() {
+ return this.entity;
+ }
+
+ /**
+ * @see com.quantum.model.Column#getQualifiedTableName()
+ */
+ public String getQualifiedTableName() {
+ return this.entity.getCondQualifiedName();
+ }
+ /**
+ * @param i
+ */
+ void setPrimaryKeyOrder(int i) {
+ this.primaryKeyOrder = i;
+ }
+
+ /**
+ * @see java.lang.Comparable#compareTo(java.lang.Object)
+ */
+ public int compareTo(Object o) {
+ ColumnImpl that = (ColumnImpl) o;
+ if (this.isPrimaryKey() && that.isPrimaryKey()) {
+ return this.primaryKeyOrder - that.primaryKeyOrder;
+ } else if (this.isPrimaryKey()) {
+ return -1;
+ } else if (that.isPrimaryKey()) {
+ return 1;
+ } else {
+ return this.position - that.position;
+ }
+ }
+ /**
+ * @return
+ */
+ public int getSize() {
+ return size;
+ }
+
+ /**
+ * @return
+ */
+ public int getNumberOfFractionalDigits() {
+ return numberOfFractionalDigits;
+ }
+
+ /**
+ * @return
+ */
+ public String getRemarks() {
+ return this.remarks == null ? "" : this.remarks;
+ }
+
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public class ConnectionException extends Exception {
+
+ private Throwable cause = null;
+
+ /**
+ *
+ */
+ public ConnectionException() {
+ super();
+ }
+
+ /**
+ * @param message
+ */
+ public ConnectionException(String message) {
+ super(message);
+ }
+
+ /**
+ * @param message
+ * @param cause
+ */
+ public ConnectionException(String message, Throwable cause) {
+ super(message);
+ this.cause = cause;
+ }
+
+ /**
+ * @param cause
+ */
+ public ConnectionException(Throwable cause) {
+ super(cause.getMessage());
+ this.cause = cause;
+ }
+
+ public Throwable getCause() {
+ return this.cause;
+ }
+
+ public String toString() {
+ String base = super.toString();
+ if (this.cause != null) {
+ base += System.getProperty("line.separator")
+ + "Root cause:"
+ + System.getProperty("line.separator")
+ + this.cause.toString();
+ }
+ return base;
+ }
+
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public interface Constraint {
+ public Entity getEntity();
+}
--- /dev/null
+package com.quantum.model;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import com.quantum.IQuantumConstants;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.sql.MultiSQLServer;
+import com.quantum.sql.SQLResults;
+
+/**
+ * @author BC
+ */
+public class Database {
+
+ private DatabaseAdapter databaseAdapter;
+ private Bookmark bookmark;
+
+ public Database(Bookmark bookmark) {
+ this.bookmark = bookmark;
+ this.databaseAdapter = bookmark.getAdapter();
+ }
+
+ private static final String[] ALL_TYPES = {
+ IQuantumConstants.Table,
+ IQuantumConstants.View,
+ IQuantumConstants.Sequence };
+
+ private static final List STANDARD_TABLE_TYPES =
+ Collections.synchronizedList(new ArrayList());
+
+ static {
+ for (int i = 0, length = (ALL_TYPES == null) ? 0 : ALL_TYPES.length;
+ i < length;
+ i++) {
+ STANDARD_TABLE_TYPES.add(ALL_TYPES[i]);
+ }
+ }
+
+ public String[] getEntityTypes()
+ throws NotConnectedException, SQLException {
+ return getEntityTypes(this.bookmark.getConnection(), this.bookmark.getSchemas()[0]);
+ }
+
+
+ /**
+ * <p>This method returns a list of entity types supported by the database
+ * adapter. This list will always be limited to Tables, Views and
+ * Sequences.</p>
+ *
+ * <p>Not all databases support all types. MySQL only supports
+ * Tables. Informix supports Tables and Views. Oracle and DB2 support
+ * Tables, Views and Sequences.</p>
+ *
+ * @param connection
+ * @param schema -
+ * This parameter is somewhat bogus. It is used to determine if the
+ * adapter defines an SQL statement for finding entities of a
+ * particular types.
+ * @return
+ * @throws SQLException
+ */
+ public String[] getEntityTypes(Connection connection, Schema schema)
+ throws SQLException {
+
+ Set set = new HashSet();
+ if (this.databaseAdapter.getShowTableQuery(schema.getName(), false) != null) {
+ set.add(IQuantumConstants.Table);
+ } else if (this.databaseAdapter.getShowViewQuery(schema.getName(), false) != null) {
+ set.add(IQuantumConstants.View);
+ } else if (this.databaseAdapter.getShowSequenceQuery(schema.getName(), false) != null) {
+ set.add(IQuantumConstants.Sequence);
+ }
+
+ DatabaseMetaData metaData = connection.getMetaData();
+ ResultSet resultSet = metaData.getTableTypes();
+ while (resultSet.next()) {
+ String type = resultSet.getString("TABLE_TYPE");
+ if (type != null) {
+ type = type.trim();
+ }
+ if (STANDARD_TABLE_TYPES.contains(type)) {
+ set.add(type);
+ }
+ }
+
+ return (String[]) set.toArray(new String[set.size()]);
+ }
+
+ public String getInformation() throws SQLException {
+ try {
+ Connection connection = this.bookmark.getConnection();
+ DatabaseMetaData metaData = connection.getMetaData();
+
+ return metaData == null ? null : metaData.getDatabaseProductName() + " "
+ + metaData.getDatabaseProductVersion();
+ } catch (NotConnectedException e) {
+ // TODO: think about this...
+ return "";
+ }
+ }
+
+ /**
+ * Get a list of entities (tables, views, sequences) for a particular
+ * bookmark. This function is usually not redefined because it gives
+ * an external interface. You will usually redefine the getShowTableQuery(),
+ * getShowViewQuery(), etc.
+ *
+ * @param bookmark -
+ * the bookmark that describes the database that is being accessed.
+ * @param passwordFinder -
+ * a utility class that knows how to obtain a password, if required
+ * @param schema -
+ * the schema from which to extract
+ * @param type -
+ * the type ("VIEW", "TABLE", etc.) of entities to extract or null
+ * if all entity types should be extracted
+ * @return
+ * an array of entity objects representing the tables, views and sequences.
+ * @throws SQLException
+ */
+ public Entity[] getEntities(Bookmark bookmark, Schema schema, String type)
+ throws SQLException, NotConnectedException {
+ Connection connection = bookmark.getConnection();
+ Entity[] result = getEntities(bookmark, connection, schema, type);
+ return (result == null) ? new Entity[0] : result;
+ }
+
+ protected Entity[] getEntities(Bookmark bookmark, Connection connection, Schema schema, String type)
+ throws SQLException {
+
+ List list = new ArrayList();
+ String[] types = (type == null) ? ALL_TYPES : new String[] { type };
+
+ for (int i = 0; i < types.length; i++) {
+ list.addAll(getEntitiesList(bookmark, connection, types[i], schema));
+ }
+
+ return (Entity[]) list.toArray(new Entity[list.size()]);
+ }
+
+ protected List getEntitiesList(Bookmark bookmark, Connection connection, String type, Schema schema)
+ throws SQLException {
+
+ String sql = getSQL(bookmark, type, schema);
+ List list = new ArrayList();
+ SQLResults results = null;
+ if (sql != null) {
+ results = MultiSQLServer.getInstance().execute(connection, sql);
+ for (int i = 1, size = (results == null) ? 0 : results.getRowCount(); i <= size; i++) {
+ String schemaName = results.getColumnCount() == 1
+ ? schema.getName() : results.getElement(1, i).toString();
+ String tableName = results.getColumnCount() == 1
+ ? results.getElement(1, i).toString()
+ : results.getElement(2, i).toString();
+ if (tableName != null && tableName.length() > 0) {
+ Entity entity = EntityFactory.getInstance().create(
+ bookmark, schemaName, tableName, type);
+ if (entity != null) {
+ list.add(entity);
+ }
+ }
+ }
+ }
+ // If we have some results, we go back
+ if (results != null) return list;
+ // Else, we try the JDBC driver
+ DatabaseMetaData metaData = connection.getMetaData();
+ // getTables needs a null schema to get all the schemas. So we don't pass a "" schema, but a null one
+ ResultSet set = null;
+ if (metaData.supportsSchemasInTableDefinitions())
+ set = metaData.getTables(null, (schema != null) ? schema.getName() : null, "%", new String[] { type });
+ else
+ set = metaData.getTables(null, null, "%", new String[] { type });
+
+ while (set.next()) {
+ String tempSchema = set.getString("TABLE_SCHEM");
+ tempSchema = (tempSchema == null) ? "" : tempSchema.trim();
+ String tableName = set.getString("TABLE_NAME");
+ tableName = (tableName == null) ? "" : tableName.trim();
+
+ if (tableName != null && tableName.length() > 0) {
+ Entity entity = EntityFactory.getInstance().create(bookmark, tempSchema, tableName, type);
+ if (entity != null) {
+ list.add(entity);
+ }
+ }
+ }
+ set.close();
+ return list;
+ }
+
+
+ private String getSQL(Bookmark bookmark, String type, Schema schema) {
+ if (Entity.TABLE_TYPE.equals(type)) {
+ return this.databaseAdapter.getShowTableQuery(schema.getName(), schema.isDefault());
+ } else if (Entity.VIEW_TYPE.equals(type)) {
+ return this.databaseAdapter.getShowViewQuery(schema.getName(), schema.isDefault());
+ } else if (Entity.SEQUENCE_TYPE.equals(type)) {
+ return this.databaseAdapter.getShowSequenceQuery(schema.getName(), schema.isDefault());
+ } else {
+ return null;
+ }
+ }
+
+
+}
--- /dev/null
+package com.quantum.model;
+
+import com.quantum.IQuantumConstants;
+
+/**
+ * @author BC
+ */
+public interface Entity extends BookmarkHolder {
+
+ public static final String TABLE_TYPE = IQuantumConstants.Table;
+ public static final String VIEW_TYPE = IQuantumConstants.View;
+ public static final String SEQUENCE_TYPE = IQuantumConstants.Sequence;
+
+ public String getName();
+ public String getSchema();
+ public String getType();
+ public Column[] getColumns();
+ public Index[] getIndexes();
+ public Column getColumn(String columnName);
+ /**
+ * Returns a String with the qualified name of the Entity.
+ * That is, "schema.name". The difference with getQualifiedName()
+ * is that the schema may be absent if it's not defined in the bookmark
+ */
+ public String getCondQualifiedName();
+
+ /**
+ * @return - TRUE if the entity exists in the database<br />
+ * - FALSE if the entity does not exist in the database<br />
+ * - null if it's not known whether or not the
+ * entity exists in the database.
+ */
+ public Boolean exists();
+ /**
+ * Some databases support mixed-case table names. Queries issued
+ * against these tables must be quoted.
+ * @return
+ */
+ public String getQuotedTableName();
+}
--- /dev/null
+package com.quantum.model;
+
+
+/**
+ *
+ *
+ * @author BC
+ */
+public class EntityFactory {
+
+ private static EntityFactory instance = new EntityFactory();
+
+ private EntityFactory() {
+ }
+
+ public static EntityFactory getInstance() {
+ return EntityFactory.instance;
+ }
+
+ public Entity create(Bookmark bookmark, String schema, String name, String type) {
+ if (type != null) {
+ type = type.toUpperCase().trim();
+ }
+
+ if (Entity.TABLE_TYPE.equals(type)) {
+ return new TableImpl(bookmark, schema, name);
+ } else if (Entity.VIEW_TYPE.equals(type)) {
+ return new ViewImpl(bookmark, schema, name);
+ } else if (Entity.SEQUENCE_TYPE.equals(type)) {
+ return new SequenceImpl(bookmark, schema, name);
+ } else {
+ return null;
+// throw new IllegalArgumentException("Unknown type: " + type);
+ }
+ }
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public interface EntityHolder {
+ public Entity getEntity();
+}
--- /dev/null
+ package com.quantum.model;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+
+/**
+ * This class models a table or view.
+ *
+ * @author bcholmes
+ */
+abstract class EntityImpl implements Entity {
+ private String schema;
+ private String name;
+ private String type;
+ private Bookmark bookmark;
+ private Boolean exists = Boolean.TRUE;
+
+ public EntityImpl(Bookmark bookmark, String schema, String name, String type) {
+ this.schema = schema;
+ this.name = name;
+ this.type = type;
+ this.bookmark = bookmark;
+ }
+ public Bookmark getBookmark() {
+ return this.bookmark;
+ }
+ public String getName() {
+ return this.name;
+ }
+ public String getSchema() {
+ return this.schema;
+ }
+ public String getType() {
+ return this.type;
+ }
+ public String getCondQualifiedName() {
+ return (this.schema == null || this.schema.length() == 0) ?
+ this.name : this.schema + "." + this.name;
+ }
+ public Column getColumn(String columnName) {
+ Column column = null;
+ Column[] columns = getColumns();
+ for (int i = 0, length = (columns == null) ? 0 : columns.length;
+ column == null && i < length;
+ i++) {
+ if (columnName != null && columnName.equals(columns[i].getName())) {
+ column = columns[i];
+ }
+ }
+ return column;
+ }
+ public Column[] getColumns() {
+
+ Column[] columns = new Column[0];
+ try {
+ // TODO: Some DBs (like DB2) don't support metadata
+ Map temp = new HashMap();
+ Connection connection = this.bookmark.getConnection();
+ DatabaseMetaData metaData = connection.getMetaData();
+ ResultSet resultSet = metaData.getColumns(null, getSchema(), getName(), null);
+
+ while (resultSet.next()) {
+ ColumnImpl column = new ColumnImpl(
+ this,
+ resultSet.getString("COLUMN_NAME"),
+ resultSet.getString("TYPE_NAME"),
+ resultSet.getInt("DATA_TYPE"),
+ resultSet.getInt("COLUMN_SIZE"),
+ resultSet.getInt("DECIMAL_DIGITS"),
+ "YES".equalsIgnoreCase(resultSet.getString("IS_NULLABLE")),
+ resultSet.getInt("ORDINAL_POSITION"),
+ getComments(resultSet.getString("REMARKS"),getCondQualifiedName(), resultSet.getString("COLUMN_NAME"))
+ );
+ temp.put(column.getName(), column);
+ }
+ resultSet.close();
+
+ resultSet = metaData.getPrimaryKeys(null, getSchema(), getName());
+ while (resultSet.next()) {
+ String name = resultSet.getString("COLUMN_NAME");
+ short keySequence = resultSet.getShort("KEY_SEQ");
+ ColumnImpl column = (ColumnImpl) temp.get(name);
+ if (column != null) {
+ column.setPrimaryKeyOrder(keySequence);
+ }
+ }
+ resultSet.close();
+
+ List columnList = Collections.synchronizedList(
+ new ArrayList(temp.values()));
+ Collections.sort(columnList);
+ columns = (Column[]) columnList.toArray(new Column[columnList.size()]);
+
+ } catch (NotConnectedException e) {
+ } catch (SQLException e) {
+ }
+ return columns;
+ }
+
+ /**
+ * Some JDBC drivers (Oracle for example) won't return the comments
+ * We recheck with a custom query, if it's defined
+ * @param iniComment The already got comment
+ * @param tableName The fully qualified table name
+ * @param columnName The column name
+ */
+ private String getComments( String iniComment, String tableName, String columnName) {
+ if (iniComment != null && iniComment.length() > 0)
+ return iniComment;
+ String comment = "";
+ try {
+ Connection con = this.bookmark.getConnection();
+ Statement stmt = con.createStatement();
+ DatabaseAdapter adapter = AdapterFactory.getInstance().getAdapter(this.bookmark.getType());
+ if (adapter != null && stmt != null && adapter.getCommentsQuery(tableName, columnName) != null) {
+
+ stmt.execute(adapter.getCommentsQuery(tableName, columnName));
+ ResultSet set = stmt.getResultSet();
+ if (set.next())
+ comment = set.getString(1);
+ }
+ } catch (NotConnectedException e) {
+ } catch (SQLException e) {
+ }
+
+ return comment;
+ }
+ public Index[] getIndexes() {
+
+ List indexList = new ArrayList();
+ Map temp = new HashMap();
+ try {
+ Connection connection = this.bookmark.getConnection();
+ DatabaseMetaData metaData = connection.getMetaData();
+ ResultSet resultSet = metaData.getIndexInfo(null, getSchema(), getName(), false, false);
+
+ while (resultSet.next()) {
+ String indexName = resultSet.getString("INDEX_NAME");
+ IndexImpl index = (IndexImpl) temp.get(indexName);
+ if (index == null) {
+ index = new IndexImpl(this, indexName);
+ temp.put(indexName, index);
+ }
+ String columnName = resultSet.getString("COLUMN_NAME");
+ String ascending = resultSet.getString("ASC_OR_DESC");
+ index.addColumn(columnName, ascending == null
+ ? null : (ascending.toUpperCase().startsWith("A")
+ ? Boolean.TRUE : Boolean.FALSE));
+ }
+ resultSet.close();
+ indexList.addAll(temp.values());
+
+ } catch (NotConnectedException e) {
+ } catch (SQLException e) {
+ }
+ return (Index[]) indexList.toArray(new Index[indexList.size()]);
+ }
+
+ public Boolean exists() {
+ return this.exists;
+ }
+
+
+ /**
+ * @see com.quantum.model.Entity#getQuotedTableName()
+ */
+ public String getQuotedTableName() {
+ return getBookmark().getAdapter().filterTableName(getCondQualifiedName());
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public interface ForeignKey extends Constraint {
+ public String getName();
+ public Entity getForeignEntity();
+ public String getForeignEntityName();
+ public String getForeignEntitySchema();
+ public int getNumberOfColumns();
+ public String getLocalColumnName(int index);
+ public String getForeignColumnName(int index);
+ public int getDeleteRule();
+}
--- /dev/null
+/*
+ * Created on 22-jul-2003
+ *
+ */
+package com.quantum.model;
+
+import com.quantum.sql.metadata.ObjectMetaData;
+
+/**
+ * Interface for objects that offer metadata support
+ * @author panic
+ *
+ */
+public interface HasMetaData {
+ public ObjectMetaData getMetaData() throws NotConnectedException;
+ /**
+ * Returns a String with the qualified name of the Entity.
+ * That is, "schema.name". The difference with getConQualifiedName()
+ * is that the schema is always present if the database supports schemas.
+ * @return
+ */
+ public String getQualifiedName();
+
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public interface Index {
+ public String getName();
+ public int getNumberOfColumns();
+ public String getColumnName(int ordinalPosition);
+ public Entity getParentEntity();
+ public boolean isAscending(int ordinalPosition);
+ public boolean isDescending(int ordinalPosition);
+}
--- /dev/null
+package com.quantum.model;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author BC
+ */
+/*package*/ class IndexImpl implements Index {
+
+ private String name;
+ private List columnNames = Collections.synchronizedList(new ArrayList());
+ private Entity entity;
+ private List ascending = Collections.synchronizedList(new ArrayList());
+
+ IndexImpl(Entity entity, String name) {
+
+ this.name = name;
+ this.entity = entity;
+ }
+
+ void addColumn(String columnName, Boolean ascending) {
+ this.columnNames.add(columnName);
+ this.ascending.add(ascending);
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * @see com.quantum.model.Index#getNumberOfColumns()
+ */
+ public int getNumberOfColumns() {
+ return this.columnNames.size();
+ }
+
+ /**
+ * @see com.quantum.model.Index#getColumnName(int)
+ */
+ public String getColumnName(int ordinalPosition) {
+ return (String) this.columnNames.get(ordinalPosition);
+ }
+
+ /**
+ * @see com.quantum.model.Index#getParentEntity()
+ */
+ public Entity getParentEntity() {
+ return this.entity;
+ }
+
+ /**
+ * @see com.quantum.model.Index#isAscending()
+ */
+ public boolean isAscending(int ordinalPosition) {
+ Boolean ascending = (Boolean) this.ascending.get(ordinalPosition);
+ return Boolean.TRUE.equals(ascending);
+ }
+
+ /**
+ * @see com.quantum.model.Index#isDescending()
+ */
+ public boolean isDescending(int ordinalPosition) {
+ Boolean ascending = (Boolean) this.ascending.get(ordinalPosition);
+ return Boolean.FALSE.equals(ascending);
+ }
+
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public class NotConnectedException extends ConnectionException {
+
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * When a bookmark doesn't have a saved password, an
+ * implementation of a password finder class can be called
+ * to obtain one.
+ *
+ * @author BC
+ */
+public interface PasswordFinder {
+
+ public String getPassword();
+ public boolean isPasswordMeantToBeSaved();
+
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public class Schema implements Comparable {
+
+ private String name;
+ private String displayName;
+ private boolean isDefault;
+
+
+ public Schema() {
+ }
+
+ public Schema(String name, String displayName, boolean isDefault) {
+ this.name = name;
+ this.displayName = displayName;
+ this.isDefault = isDefault;
+ }
+
+ public Schema(String name) {
+ this(name, name, false);
+ }
+
+ /**
+ * @return
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @param string
+ */
+ public void setName(String string) {
+ name = string;
+ }
+
+ /**
+ * @see java.lang.Comparable#compareTo(java.lang.Object)
+ */
+ public int compareTo(Object o) {
+ Schema that = (Schema) o;
+ if (that.isDefault() == this.isDefault()) {
+ return this.getDisplayName().compareTo(that.getDisplayName());
+ } else {
+ return that.isDefault() ? 1 : -1;
+ }
+ }
+ public boolean equals(Object obj) {
+ if (getClass() != obj.getClass()) {
+ return false;
+ } else {
+ Schema that = (Schema) obj;
+ if (this.name == null && !(that.name == null)) {
+ return false;
+ } else if (this.name != null && !this.name.equals(that.name)) {
+ return false;
+ } else if (this.displayName == null && !(that.displayName == null)) {
+ return false;
+ } else if (this.displayName == null && !this.displayName.equals(that.displayName)) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+ }
+ public int hashCode() {
+ int hashCode = super.hashCode();
+ if (this.name != null) {
+ hashCode ^= this.name.hashCode();
+ }
+ if (this.displayName != null) {
+ hashCode ^= this.displayName.hashCode();
+ }
+
+ return hashCode;
+ }
+
+ /**
+ * @return
+ */
+ public boolean isDefault() {
+ return isDefault;
+ }
+
+ /**
+ * @param b
+ */
+ public void setDefault(boolean isDefault) {
+ this.isDefault = isDefault;
+ }
+
+ /**
+ * @return
+ */
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ /**
+ * @param string
+ */
+ public void setDisplayName(String string) {
+ displayName = string;
+ }
+
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public interface SchemaHolder {
+ public Schema getSchema();
+}
--- /dev/null
+package com.quantum.model;
+
+/**
+ * @author BC
+ */
+public interface Sequence extends Entity {
+
+}
--- /dev/null
+package com.quantum.model;
+
+class SequenceImpl extends EntityImpl implements Sequence {
+ public SequenceImpl(Bookmark bookmark, String schema, String name) {
+ super(bookmark, schema, name, SEQUENCE_TYPE);
+ }
+ public Column[] getColumns() {
+ return new Column[0];
+ }
+ public Column getColumn(String columnName) {
+ return null;
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.model;
+
+import java.sql.SQLException;
+
+/**
+ * @author BC
+ */
+public interface Table extends Entity {
+ public Integer getSize();
+ public void deleteAllRows() throws SQLException, ConnectionException;
+}
--- /dev/null
+package com.quantum.model;
+
+import java.sql.SQLException;
+
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.sql.MultiSQLServer;
+import com.quantum.sql.SQLHelper;
+
+
+class TableImpl extends EntityImpl implements Table {
+ public TableImpl(Bookmark bookmark, String schema, String name) {
+ super(bookmark, schema, name, TABLE_TYPE);
+ }
+
+ public Integer getSize() {
+ Integer size = null;
+ try {
+ size = new Integer(SQLHelper.getSize(
+ getBookmark().getConnection(), getCondQualifiedName(),
+ AdapterFactory.getInstance().getAdapter(getBookmark().getType())));
+ } catch (SQLException e) {
+ } catch (ConnectionException e) {
+ }
+ return size;
+ }
+
+ public void deleteAllRows() throws SQLException, ConnectionException {
+ String sql = "DELETE FROM " + getCondQualifiedName();
+ MultiSQLServer.getInstance().execute(getBookmark().getConnection(), sql);
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.model;
+
+
+/**
+ * @author BC
+ */
+public interface View extends Entity {
+
+ public Integer getSize();
+
+}
--- /dev/null
+package com.quantum.model;
+
+import java.sql.SQLException;
+
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.sql.SQLHelper;
+
+
+class ViewImpl extends EntityImpl implements View {
+ public ViewImpl(Bookmark bookmark, String schema, String name) {
+ super(bookmark, schema, name, VIEW_TYPE);
+ }
+
+ public Integer getSize() {
+ Integer size = null;
+ try {
+ size = new Integer(SQLHelper.getSize(
+ getBookmark().getConnection(), getCondQualifiedName(),
+ AdapterFactory.getInstance().getAdapter(getBookmark().getType())));
+ } catch (SQLException e) {
+ } catch (ConnectionException e) {
+ }
+ return size;
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.model.xml;
+
+import com.quantum.Messages;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Column;
+import com.quantum.model.Entity;
+import com.quantum.model.Schema;
+import com.quantum.sql.metadata.MetaDataXMLInterface;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Text;
+
+/**
+ * @author BC
+ */
+public class ModelToXMLConverter {
+
+ private static final ModelToXMLConverter instance = new ModelToXMLConverter();
+
+ private ModelToXMLConverter() {
+ }
+
+ public static ModelToXMLConverter getInstance() {
+ return ModelToXMLConverter.instance;
+ }
+
+ public void createRoot(Document document) {
+ document.appendChild(document.createElement("SAVED_DATA"));
+ }
+
+ public void convert(Element bookmarkRoot, Bookmark b) {
+ Document document = bookmarkRoot.getOwnerDocument();
+ Element bookmark = MetaDataXMLInterface.createElementText(bookmarkRoot,"bookmark", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ MetaDataXMLInterface.createElementText(bookmark,"name", b.getName()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"username", b.getUsername()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"password", b.getPassword()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"prompt", b.getPromptForPassword() ? "true" : "false"); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"connect", b.getConnect()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"autoCommit", b.isAutoCommit() ? "true" : "false"); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"autoCommitPreference", b.getAutoCommitPreference()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"driver", b.getDriver()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"type", b.getType()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(bookmark,"driverLocation", b.getDriverFile()); //$NON-NLS-1$
+ Element otherSchemas = (Element) bookmark.appendChild(document.createElement(Messages.getString("ExportXMLAction.OtherSchemas"))); //$NON-NLS-1$
+ Schema[] schemas = b.getSchemas();
+ for (int i = 0, length = (schemas == null) ? 0 : schemas.length;
+ i < length;
+ i++) {
+ if (!schemas[i].isDefault()) {
+ MetaDataXMLInterface.createElementText(
+ otherSchemas,Messages.getString("ExportXMLAction.SchemaName"), schemas[i].getName()); //$NON-NLS-1$
+ }
+ }
+ Entity[] quickList = b.getQuickListEntries();
+ Element quickListEntity = document.createElement("quickList");
+ for (int j = 0, length = (quickList == null) ? 0 : quickList.length;
+ j < length;
+ j++) {
+ ModelToXMLConverter.getInstance().convert(quickListEntity, quickList[j]);
+ }
+ bookmark.appendChild(quickListEntity);
+ convertQueryList(b, bookmark);
+ }
+
+
+ public void convert(Element parent, Entity entity) {
+ convert(parent, entity, true);
+ }
+ public void convert(Element parent, Entity entity, boolean recurse) {
+ Document document = parent.getOwnerDocument();
+ Element element = document.createElement(getEntityDOMNodeName(entity));
+ element.setAttribute("name", entity.getName());
+ if (entity.getSchema() != null) {
+ element.setAttribute("schema", entity.getSchema());
+ }
+ if (recurse) {
+ convert(element, entity.getColumns());
+ }
+ parent.appendChild(element);
+ }
+
+ public void convert(Element element, Column[] columns) {
+ for (int i = 0, length = (columns == null) ? 0 : columns.length;
+ i < length;
+ i++) {
+ convert(element, columns[i]);
+ }
+ }
+
+ public void convert(Element parent, Column column) {
+ Document document = parent.getOwnerDocument();
+ Element element = document.createElement("column");
+ element.setAttribute("name", column.getName());
+ element.setAttribute("type", column.getTypeName());
+ element.setAttribute("primaryKey", column.isPrimaryKey() ? "true" : "false");
+ element.setAttribute("nullable", column.isNullable() ? "true" : "false");
+ if (column.isNumeric()) {
+ if (column.getSize() > 0) {
+ element.setAttribute("size", String.valueOf(column.getSize()));
+ }
+ if (column.getNumberOfFractionalDigits() > 0) {
+ element.setAttribute("numberOfFractionalDigits", String.valueOf(column.getNumberOfFractionalDigits()));
+ }
+ } else {
+ if (column.getSize() > 0) {
+ element.setAttribute("size", String.valueOf(column.getSize()));
+ }
+ }
+ if (column.getRemarks().length() > 0)
+ MetaDataXMLInterface.createElementText(element, "remarks", column.getRemarks());
+ parent.appendChild(element);
+ }
+
+
+ public String getEntityDOMNodeName(Entity entity) {
+ if (Entity.TABLE_TYPE.equals(entity.getType())) {
+ return "table";
+ } else if (Entity.VIEW_TYPE.equals(entity.getType())) {
+ return "view";
+ } else if (Entity.SEQUENCE_TYPE.equals(entity.getType())) {
+ return "sequence";
+ } else {
+ return "unknown";
+ }
+ }
+
+ public void convertQueryList(
+ Bookmark bookmark,
+ Element parent) {
+
+ Document document = parent.getOwnerDocument();
+ String[] queryList = bookmark.getQueries();
+ Element queryListEntity = document.createElement("queryList");
+ for (int j = 0, length = (queryList == null) ? 0 : queryList.length;
+ j < length;
+ j++) {
+ Element query = document.createElement("query");
+
+ // will have more possibilities later
+ Element queryString = document.createElement("queryString");
+ Text queryText = document.createTextNode(queryList[j]);
+ queryString.appendChild(queryText);
+ query.appendChild(queryString);
+ queryListEntity.appendChild(query);
+ }
+ parent.appendChild(queryListEntity);
+ }
+
+}
--- /dev/null
+package com.quantum.model.xml;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.sql.SQLException;
+import java.sql.Types;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.Column;
+import com.quantum.model.Entity;
+import com.quantum.model.Schema;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * @author BC
+ */
+public class TorqueConverter {
+ public void createRoot(Document document) {
+ Element root = document.createElement("database");
+ document.appendChild(root);
+ }
+ public void convert(Element root, Bookmark bookmark, Schema schema) {
+ try {
+ Entity[] tables = bookmark.getEntitiesForSchema(
+ schema, Entity.TABLE_TYPE);
+
+ for (int i = 0, length = (tables == null) ? 0 : tables.length;
+ i < length;
+ i++) {
+ convert(root, tables[i]);
+ }
+ } catch (SQLException e) {
+ }
+ }
+
+ public void convert(Element root, Entity entity) {
+ Element table = root.getOwnerDocument().createElement("table");
+ table.setAttribute("name", entity.getName());
+
+ Column[] columns = entity.getColumns();
+ for (int i = 0, length = (columns == null) ? 0 : columns.length;
+ i < length;
+ i++) {
+ convert(table, columns[i]);
+ }
+
+ root.appendChild(table);
+ }
+
+ public void convert(Element root, Column column) {
+ Element element = root.getOwnerDocument().createElement("column");
+ element.setAttribute("name", column.getName());
+ if (column.isPrimaryKey()) {
+ element.setAttribute("primaryKey", "true");
+ }
+ element.setAttribute("required", column.isNullable() ? "false" : "true");
+ if (column.isNumeric() && column.getNumberOfFractionalDigits() > 0) {
+ element.setAttribute("size", String.valueOf(column.getSize()) +
+ "," + String.valueOf(column.getNumberOfFractionalDigits()));
+ } else if (column.getSize() >= 0) {
+ element.setAttribute("size", String.valueOf(column.getSize()));
+ }
+ element.setAttribute("type", getStandardType(column.getType()));
+
+ root.appendChild(element);
+ }
+
+ private String getStandardType(int type) {
+ String result = null;
+ try {
+ Field[] fields = Types.class.getFields();
+ for (int i = 0, length = (fields == null) ? 0 : fields.length;
+ result == null & i < length;
+ i++) {
+ if (fields[i].getDeclaringClass() == Integer.TYPE &&
+ Modifier.isStatic(fields[i].getModifiers()) &&
+ Modifier.isPublic(fields[i].getModifiers()) &&
+ type == fields[i].getLong(null)) {
+
+ result = fields[i].getName();
+ }
+ }
+ } catch (IllegalAccessException e) {
+ // shouldn't happen
+ }
+ return result;
+ }
+}
--- /dev/null
+package com.quantum.perspective;
+
+import org.eclipse.ui.IFolderLayout;
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+
+/**
+ * @author root
+ */
+public class DBPerspective implements IPerspectiveFactory {
+ public void createInitialLayout(IPageLayout layout) {
+ layout.setEditorAreaVisible(false);
+ IFolderLayout side =
+ layout.createFolder(
+ "side", //$NON-NLS-1$
+ IPageLayout.LEFT,
+ 0.33F,
+ layout.getEditorArea());
+ side.addView("com.quantum.view.bookmarkview"); //$NON-NLS-1$
+ layout.addView("com.quantum.view.sqlqueryview", IPageLayout.BOTTOM, 0.33F, layout.getEditorArea()); //$NON-NLS-1$
+ IFolderLayout bottomRight =
+ layout.createFolder(
+ "bottomRight", //$NON-NLS-1$
+ IPageLayout.BOTTOM,
+ 0.33F,
+ "com.quantum.view.sqlqueryview");
+ bottomRight.addView("com.quantum.view.tableview.TableView"); //$NON-NLS-1$
+ bottomRight.addView("com.quantum.view.logview"); //$NON-NLS-1$
+ }
+}
--- /dev/null
+package com.quantum.preferences;
+
+
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.FieldEditorPreferencePage;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.StringFieldEditor;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class CopyPreferences
+ extends FieldEditorPreferencePage
+ implements IWorkbenchPreferencePage {
+
+ public CopyPreferences() {
+ super(FieldEditorPreferencePage.GRID);
+
+ // Set the preference store for the preference page.
+ IPreferenceStore store =
+ QuantumPlugin.getDefault().getPreferenceStore();
+ setPreferenceStore(store);
+ }
+
+ public void init(IWorkbench workbench) {
+ this.workbench = workbench;
+ }
+
+ IWorkbench workbench;
+
+ protected void createFieldEditors() {
+ StringFieldEditor copyColumnSeparator = new StringFieldEditor("copyColumnSeparator", "&Normal Copy Separator:", getFieldEditorParent());
+ this.
+ addField(copyColumnSeparator);
+ }
+
+}
--- /dev/null
+package com.quantum.preferences;
+
+
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.FieldEditorPreferencePage;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.StringFieldEditor;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class CustomCopyPreferences
+ extends FieldEditorPreferencePage
+ implements IWorkbenchPreferencePage {
+
+ public CustomCopyPreferences() {
+ super(FieldEditorPreferencePage.GRID);
+
+ // Set the preference store for the preference page.
+ IPreferenceStore store =
+ QuantumPlugin.getDefault().getPreferenceStore();
+ setPreferenceStore(store);
+ }
+
+ public void init(IWorkbench workbench) {
+ this.workbench = workbench;
+ }
+
+ IWorkbench workbench;
+
+ protected void createFieldEditors() {
+ StringFieldEditor customCopyName = new StringFieldEditor("customCopyName1", "&Name:", getFieldEditorParent());
+ addField(customCopyName);
+ StringFieldEditor customCopyTableItem = new StringFieldEditor("customCopyTableItem1", "&Table Item:", getFieldEditorParent());
+ addField(customCopyTableItem);
+ StringFieldEditor customCopyTableSeparator = new StringFieldEditor("customCopyTableSeparator1", "&Table Separator:", getFieldEditorParent());
+ addField(customCopyTableSeparator);
+ StringFieldEditor customCopyColumnItem = new StringFieldEditor("customCopyColumnItem1", "&Column Item:", getFieldEditorParent());
+ addField(customCopyColumnItem);
+ StringFieldEditor customCopyColumnSeparator = new StringFieldEditor("customCopyColumnSeparator1", "&Column Separator:", getFieldEditorParent());
+ addField(customCopyColumnSeparator);
+ StringFieldEditor customCopyTemplate = new StringFieldEditor("customCopyTemplate1", "&Template:", getFieldEditorParent());
+ addField(customCopyTemplate);
+ }
+
+}
--- /dev/null
+package com.quantum.preferences;
+
+
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.FieldEditorPreferencePage;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.StringFieldEditor;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class CustomCopyPreferences2
+ extends FieldEditorPreferencePage
+ implements IWorkbenchPreferencePage {
+
+ public CustomCopyPreferences2() {
+ super(FieldEditorPreferencePage.GRID);
+
+ // Set the preference store for the preference page.
+ IPreferenceStore store =
+ QuantumPlugin.getDefault().getPreferenceStore();
+ setPreferenceStore(store);
+ }
+
+ public void init(IWorkbench workbench) {
+ this.workbench = workbench;
+ }
+
+ IWorkbench workbench;
+
+ protected void createFieldEditors() {
+ StringFieldEditor customCopyName = new StringFieldEditor("customCopyName2", "&Name:", getFieldEditorParent());
+ addField(customCopyName);
+ StringFieldEditor customCopyTableItem = new StringFieldEditor("customCopyTableItem2", "&Table Item:", getFieldEditorParent());
+ addField(customCopyTableItem);
+ StringFieldEditor customCopyTableSeparator = new StringFieldEditor("customCopyTableSeparator2", "&Table Separator:", getFieldEditorParent());
+ addField(customCopyTableSeparator);
+ StringFieldEditor customCopyColumnItem = new StringFieldEditor("customCopyColumnItem2", "&Column Item:", getFieldEditorParent());
+ addField(customCopyColumnItem);
+ StringFieldEditor customCopyColumnSeparator = new StringFieldEditor("customCopyColumnSeparator2", "&Column Separator:", getFieldEditorParent());
+ addField(customCopyColumnSeparator);
+ StringFieldEditor customCopyTemplate = new StringFieldEditor("customCopyTemplate2", "&Template:", getFieldEditorParent());
+ addField(customCopyTemplate);
+ }
+
+}
--- /dev/null
+package com.quantum.preferences;
+
+
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.FieldEditorPreferencePage;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.StringFieldEditor;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class CustomCopyPreferences3
+ extends FieldEditorPreferencePage
+ implements IWorkbenchPreferencePage {
+
+ public CustomCopyPreferences3() {
+ super(FieldEditorPreferencePage.GRID);
+
+ // Set the preference store for the preference page.
+ IPreferenceStore store =
+ QuantumPlugin.getDefault().getPreferenceStore();
+ setPreferenceStore(store);
+ }
+
+ public void init(IWorkbench workbench) {
+ this.workbench = workbench;
+ }
+
+ IWorkbench workbench;
+
+ protected void createFieldEditors() {
+ StringFieldEditor customCopyName = new StringFieldEditor("customCopyName3", "&Name:", getFieldEditorParent());
+ addField(customCopyName);
+ StringFieldEditor customCopyTableItem = new StringFieldEditor("customCopyTableItem3", "&Table Item:", getFieldEditorParent());
+ addField(customCopyTableItem);
+ StringFieldEditor customCopyTableSeparator = new StringFieldEditor("customCopyTableSeparator3", "&Table Separator:", getFieldEditorParent());
+ addField(customCopyTableSeparator);
+ StringFieldEditor customCopyColumnItem = new StringFieldEditor("customCopyColumnItem3", "&Column Item:", getFieldEditorParent());
+ addField(customCopyColumnItem);
+ StringFieldEditor customCopyColumnSeparator = new StringFieldEditor("customCopyColumnSeparator3", "&Column Separator:", getFieldEditorParent());
+ addField(customCopyColumnSeparator);
+ StringFieldEditor customCopyTemplate = new StringFieldEditor("customCopyTemplate3", "&Template:", getFieldEditorParent());
+ addField(customCopyTemplate);
+ }
+
+}
--- /dev/null
+package com.quantum.preferences;
+
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.FieldEditorPreferencePage;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.IntegerFieldEditor;
+import org.eclipse.jface.preference.StringFieldEditor;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+/**
+ * PreferencePage for the global options on QuantumDB
+ * @author panic
+ *
+ */
+public class GlobalPreferences
+extends FieldEditorPreferencePage
+implements IWorkbenchPreferencePage {
+
+ public GlobalPreferences() {
+ super(FieldEditorPreferencePage.GRID);
+
+ // Set the preference store for the preference page.
+ IPreferenceStore store =
+ QuantumPlugin.getDefault().getPreferenceStore();
+ setPreferenceStore(store);
+ }
+
+ public void init(IWorkbench workbench) {
+ this.workbench = workbench;
+ }
+
+ IWorkbench workbench;
+
+ protected void createFieldEditors() {
+ IntegerFieldEditor queryHistorySize = new IntegerFieldEditor(
+ "com.quantum.model.Bookmark.queryHistorySize",
+ Messages.getString(getClass().getName() + "."
+ + "com.quantum.model.Bookmark.queryHistorySize"),
+ getFieldEditorParent());
+ queryHistorySize.setValidRange(0, Integer.MAX_VALUE);
+ this.addField(queryHistorySize);
+ StringFieldEditor askPasswordString = new StringFieldEditor("askPasswordString", "&Ask for password string:", getFieldEditorParent());
+ this.addField(askPasswordString);
+ }
+}
--- /dev/null
+package com.quantum.preferences;
+
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.editors.ColorManager;
+import com.quantum.editors.SQLColorConstants;
+import com.quantum.util.versioning.VersioningHelper;
+
+import org.eclipse.jface.preference.ColorFieldEditor;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferenceConverter;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.FontDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class SQLEditorPreferences extends PreferencePage
+ implements IWorkbenchPreferencePage {
+ FontDialog fontDialog;
+ ColorFieldEditor backgroundColorEditor;
+
+ ColorFieldEditor textColorEditor;
+ boolean textFlag;
+ ColorFieldEditor keywordColorEditor;
+ boolean keywordFlag;
+ ColorFieldEditor stringColorEditor;
+ boolean stringFlag;
+ ColorFieldEditor numericColorEditor;
+ boolean numericFlag;
+ ColorFieldEditor commentColorEditor;
+ boolean commentFlag;
+
+ Button boldText;
+ Button boldKeyword;
+ Button boldString;
+ Button boldNumeric;
+ Button boldComment;
+
+ IWorkbench workbench;
+ FontData fontData;
+ Label fontDisplay;
+ public void init(IWorkbench workbench) {
+ //Initialize the preference store
+ this.workbench = workbench;
+ setPreferenceStore(QuantumPlugin.getDefault().getPreferenceStore());
+ initializeColorDefaults(getPreferenceStore());
+ }
+
+ private void initializeColorDefaults(IPreferenceStore store) {
+ RGB BACKGROUND = new RGB(255, 255, 255);
+ RGB COMMENT = new RGB(88, 148, 64);
+ RGB KEYWORD = new RGB(126, 0, 75);
+ RGB STRING = new RGB(0, 0, 255);
+ RGB NUMERIC = new RGB(255, 0, 0);
+ RGB DEFAULT = new RGB(0, 0, 0);
+ PreferenceConverter.setDefault(store,
+ "quantum.background.color", BACKGROUND); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.text.color", DEFAULT); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.keyword.color", KEYWORD); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.comment.color", COMMENT); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.string.color", STRING); //$NON-NLS-1$
+ PreferenceConverter.setDefault(store,
+ "quantum.numeric.color", NUMERIC); //$NON-NLS-1$
+ }
+
+ protected void performDefaults() {
+ fontData = null;
+ updateFontDisplay();
+ textFlag = false;
+ keywordFlag = true;
+ stringFlag = false;
+ numericFlag = false;
+ commentFlag = false;
+ updateFlags();
+ backgroundColorEditor.loadDefault();
+ textColorEditor.loadDefault();
+ keywordColorEditor.loadDefault();
+ stringColorEditor.loadDefault();
+ commentColorEditor.loadDefault();
+ numericColorEditor.loadDefault();
+ }
+ /**
+ * Save the preferences to the preference store.
+ */
+ public boolean performOk() {
+ PreferenceConverter.setValue(getPreferenceStore(), "quantum.font", fontData); //$NON-NLS-1$
+ getPreferenceStore().setValue("quantum.text.bold", textFlag); //$NON-NLS-1$
+ getPreferenceStore().setValue("quantum.keyword.bold", keywordFlag); //$NON-NLS-1$
+ getPreferenceStore().setValue("quantum.string.bold", stringFlag); //$NON-NLS-1$
+ getPreferenceStore().setValue("quantum.comment.bold", commentFlag); //$NON-NLS-1$
+ getPreferenceStore().setValue("quantum.numeric.bold", numericFlag); //$NON-NLS-1$
+ backgroundColorEditor.store();
+ textColorEditor.store();
+ keywordColorEditor.store();
+ stringColorEditor.store();
+ commentColorEditor.store();
+ numericColorEditor.store();
+ return super.performOk();
+ }
+ protected Control createContents(Composite parent) {
+ Composite main = new Composite(parent, SWT.NULL);
+
+ GridLayout innerLayout = new GridLayout();
+ innerLayout.numColumns = 4;
+ main.setLayout(innerLayout);
+
+ fontData = PreferenceConverter.getFontData(getPreferenceStore(), "quantum.font"); //$NON-NLS-1$
+ textFlag = getPreferenceStore().getBoolean("quantum.text.bold"); //$NON-NLS-1$
+ keywordFlag = getPreferenceStore().getBoolean("quantum.keyword.bold"); //$NON-NLS-1$
+ stringFlag = getPreferenceStore().getBoolean("quantum.string.bold"); //$NON-NLS-1$
+ commentFlag = getPreferenceStore().getBoolean("quantum.comment.bold"); //$NON-NLS-1$
+ numericFlag = getPreferenceStore().getBoolean("quantum.numeric.bold"); //$NON-NLS-1$
+
+ fontDialog = new FontDialog(workbench.getActiveWorkbenchWindow().getShell());
+ Button fontButton = new Button(main, SWT.PUSH);
+ fontButton.setText(Messages.getString("PreferencesPage.PickFont")); //$NON-NLS-1$
+ fontButton.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ if (fontData != null) {
+ VersioningHelper.setFont(fontDialog, new FontData[] { fontData} );
+ }
+ FontData data = fontDialog.open();
+ if (data != null) {
+ fontData = data;
+ updateFontDisplay();
+ }
+ }
+ });
+ Button defaultButton = new Button(main, SWT.PUSH);
+ defaultButton.setText(Messages.getString("PreferencesPage.DefaultFont")); //$NON-NLS-1$
+ defaultButton.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ fontData = null;
+ updateFontDisplay();
+ }
+ });
+
+ fontDisplay = new Label(main, SWT.NULL);
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+ data.grabExcessHorizontalSpace = true;
+ fontDisplay.setLayoutData(data);
+ updateFontDisplay();
+
+ ColorManager manager = new ColorManager();
+
+ Composite comp = new Composite(main, SWT.NULL);
+ GridData layoutData = new GridData();
+ layoutData.horizontalSpan = 2;
+ comp.setLayoutData(layoutData);
+
+ manager.getColor(SQLColorConstants.DEFAULT);
+ backgroundColorEditor =
+ new ColorFieldEditor(
+ "quantum.background.color", //$NON-NLS-1$
+ Messages.getString("PreferencesPage.BackgroundColor"), //$NON-NLS-1$
+ comp);
+
+ Composite temp = new Composite(main, SWT.NULL);
+ temp.setSize(0, 0);
+
+ comp = new Composite(main, SWT.NULL);
+ layoutData = new GridData();
+ layoutData.horizontalSpan = 2;
+ comp.setLayoutData(layoutData);
+
+ textColorEditor =
+ new ColorFieldEditor(
+ "quantum.text.color", //$NON-NLS-1$
+ Messages.getString("PreferencesPage.DefaultTextColor"), //$NON-NLS-1$
+ comp);
+
+ boldText = new Button(main, SWT.CHECK);
+ boldText.setSelection(textFlag);
+ boldText.setText(Messages.getString("PreferencesPage.Bold")); //$NON-NLS-1$
+ boldText.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ textFlag = boldText.getSelection();
+ }
+ });
+
+ comp = new Composite(main, SWT.NULL);
+ layoutData = new GridData();
+ layoutData.horizontalSpan = 2;
+ comp.setLayoutData(layoutData);
+
+ keywordColorEditor =
+ new ColorFieldEditor(
+ Messages.getString("PreferencesPage.quantum.keyword.color_26"), //$NON-NLS-1$
+ Messages.getString("PreferencesPage.KeywordTextColor"), //$NON-NLS-1$
+ comp);
+
+ boldKeyword = new Button(main, SWT.CHECK);
+ boldKeyword.setSelection(keywordFlag);
+ boldKeyword.setText(Messages.getString("PreferencesPage.Bold")); //$NON-NLS-1$
+ boldKeyword.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ keywordFlag = boldKeyword.getSelection();
+ }
+ });
+
+ comp = new Composite(main, SWT.NULL);
+ layoutData = new GridData();
+ layoutData.horizontalSpan = 2;
+ comp.setLayoutData(layoutData);
+
+ commentColorEditor =
+ new ColorFieldEditor(
+ "quantum.comment.color", //$NON-NLS-1$
+ Messages.getString("PreferencesPage.CommentTextColor"), //$NON-NLS-1$
+ comp);
+
+ boldComment = new Button(main, SWT.CHECK);
+ boldComment.setSelection(commentFlag);
+ boldComment.setText(Messages.getString("PreferencesPage.Bold")); //$NON-NLS-1$
+ boldComment.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ commentFlag = boldComment.getSelection();
+ }
+ });
+
+ comp = new Composite(main, SWT.NULL);
+ layoutData = new GridData();
+ layoutData.horizontalSpan = 2;
+ comp.setLayoutData(layoutData);
+
+ stringColorEditor =
+ new ColorFieldEditor(
+ "quantum.string.color", //$NON-NLS-1$
+ Messages.getString("PreferencesPage.StringTextColor"), //$NON-NLS-1$
+ comp);
+
+ boldString = new Button(main, SWT.CHECK);
+ boldString.setSelection(stringFlag);
+ boldString.setText(Messages.getString("PreferencesPage.Bold")); //$NON-NLS-1$
+ boldString.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ stringFlag = boldString.getSelection();
+ }
+ });
+
+ comp = new Composite(main, SWT.NULL);
+ layoutData = new GridData();
+ layoutData.horizontalSpan = 2;
+ comp.setLayoutData(layoutData);
+
+ numericColorEditor =
+ new ColorFieldEditor(
+ "quantum.numeric.color", //$NON-NLS-1$
+ Messages.getString("PreferencesPage.NumericTextColor"), //$NON-NLS-1$
+ comp);
+
+ boldNumeric = new Button(main, SWT.CHECK);
+ boldNumeric.setSelection(numericFlag);
+ boldNumeric.setText(Messages.getString("PreferencesPage.Bold")); //$NON-NLS-1$
+ boldNumeric.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ numericFlag = boldNumeric.getSelection();
+ }
+ });
+
+ backgroundColorEditor.setPreferencePage(this);
+ backgroundColorEditor.setPreferenceStore(getPreferenceStore());
+ backgroundColorEditor.load();
+
+ textColorEditor.setPreferencePage(this);
+ textColorEditor.setPreferenceStore(getPreferenceStore());
+ textColorEditor.load();
+
+ keywordColorEditor.setPreferencePage(this);
+ keywordColorEditor.setPreferenceStore(getPreferenceStore());
+ keywordColorEditor.load();
+
+ commentColorEditor.setPreferencePage(this);
+ commentColorEditor.setPreferenceStore(getPreferenceStore());
+ commentColorEditor.load();
+
+ stringColorEditor.setPreferencePage(this);
+ stringColorEditor.setPreferenceStore(getPreferenceStore());
+ stringColorEditor.load();
+
+ numericColorEditor.setPreferencePage(this);
+ numericColorEditor.setPreferenceStore(getPreferenceStore());
+ numericColorEditor.load();
+
+ return main;
+ }
+ public void updateFontDisplay() {
+ if (fontData == null) {
+ fontDisplay.setText(Messages.getString("PreferencesPage.Font_Default")); //$NON-NLS-1$
+ } else {
+ String style = Messages.getString("PreferencesPage.regular"); //$NON-NLS-1$
+ if (fontData.getStyle() == SWT.BOLD) {
+ style = Messages.getString("PreferencesPage.bold"); //$NON-NLS-1$
+ } else if (fontData.getStyle() == SWT.ITALIC) {
+ style = Messages.getString("PreferencesPage.italic"); //$NON-NLS-1$
+ } else if (fontData.getStyle() == (SWT.BOLD | SWT.ITALIC)) {
+ style = Messages.getString("PreferencesPage.boldItalic"); //$NON-NLS-1$
+ }
+ fontDisplay.setText(Messages.getString("PreferencesPage.FontPrompt") + fontData.getName() + '-' + style + '-' + fontData.getHeight()); //$NON-NLS-1$
+ }
+ }
+ public void updateFlags() {
+ boldText.setSelection(textFlag);
+ boldKeyword.setSelection(keywordFlag);
+ boldString.setSelection(stringFlag);
+ boldNumeric.setSelection(numericFlag);
+ boldComment.setSelection(commentFlag);
+ }
+}
--- /dev/null
+package com.quantum.properties;
+
+import com.quantum.IQuantumConstants;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DriverInfo;
+import com.quantum.model.Bookmark;
+import com.quantum.view.bookmark.TreeNode;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.TabFolder;
+import org.eclipse.swt.widgets.TabItem;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.dialogs.PropertyPage;
+
+public class BookmarkPropertyPage extends PropertyPage {
+
+ private Text password;
+ private Text userid;
+ private Button prompt;
+
+ private Text jdbcURL;
+ private Text driverName;
+ private Text driverPath;
+
+ private Combo type;
+ private Combo autoCommit;
+ private DriverInfo[] adapters = AdapterFactory.getInstance().getDriverList();
+
+ protected Control createContents(Composite parent) {
+
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.grabExcessHorizontalSpace = true;
+ composite.setLayoutData(data);
+
+ Label nameLabel = new Label(composite, SWT.NONE);
+ nameLabel.setText("Name:");
+
+ Label name = new Label(composite, SWT.NONE);
+
+ Bookmark bookmark = getBookmark();
+ String description = bookmark.getName();
+ name.setText(description);
+
+ TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
+ layout = new GridLayout();
+ tabFolder.setLayout(layout);
+ data = new GridData(GridData.FILL_BOTH);
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessVerticalSpace = true;
+ data.verticalAlignment = GridData.FILL;
+ data.horizontalSpan = 2;
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ tabFolder.setLayoutData(data);
+
+ createUserTab(tabFolder);
+ createDriverTab(tabFolder);
+ createOptionsTab(tabFolder);
+
+ performDefaults();
+ return composite;
+ }
+
+ private Bookmark getBookmark() {
+ Bookmark bookmark =
+ ((TreeNode) getElement()).getBookmark();
+ return bookmark;
+ }
+
+ private void createDriverTab(TabFolder tabFolder) {
+ TabItem driverTab = new TabItem(tabFolder, SWT.NONE);
+ driverTab.setText("JDBC Driver");
+
+ Composite composite = new Composite(tabFolder, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ data.grabExcessHorizontalSpace = true;
+ composite.setLayoutData(data);
+
+ Label label = new Label(composite, SWT.NONE);
+ label.setText("Connection URL:");
+
+ this.jdbcURL = new Text(composite, SWT.BORDER);
+ data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessHorizontalSpace = true;
+ this.jdbcURL.setLayoutData(data);
+
+ label = new Label(composite, SWT.NONE);
+ label.setText("Driver Name:");
+
+ this.driverName = new Text(composite, SWT.BORDER);
+ data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ this.driverName.setLayoutData(data);
+
+ label = new Label(composite, SWT.NONE);
+ label.setText("Driver Location:");
+
+ this.driverPath = new Text(composite, SWT.BORDER);
+ data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ this.driverPath.setLayoutData(data);
+
+ label = new Label(composite, SWT.NULL);
+ label.setText("Type:");
+ this.type = new Combo(composite, SWT.SIMPLE | SWT.DROP_DOWN | SWT.READ_ONLY);
+ String adapterNames[] = new String[adapters.length];
+ for (int i = 0; i < adapters.length; i++) {
+ adapterNames[i] = adapters[i].getDisplayName();
+ }
+ this.type.setItems(adapterNames);
+
+ data = new GridData();
+ data.horizontalAlignment = GridData.FILL;
+ this.type.setLayoutData(data);
+
+ driverTab.setControl(composite);
+ }
+
+ private void createUserTab(TabFolder tabFolder) {
+ TabItem userTab = new TabItem(tabFolder, SWT.NONE);
+ userTab.setText("User");
+
+ Composite composite = new Composite(tabFolder, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ data.grabExcessHorizontalSpace = true;
+ composite.setLayoutData(data);
+
+ Label useridLabel = new Label(composite, SWT.NONE);
+ useridLabel.setText("Userid:");
+
+ this.userid = new Text(composite, SWT.BORDER);
+ data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessHorizontalSpace = true;
+ this.userid.setLayoutData(data);
+
+ Label passworLabel = new Label(composite, SWT.NONE);
+ passworLabel.setText("Password:");
+
+ this.password = new Text(composite, SWT.BORDER);
+ this.password.setEchoChar('*');
+ data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ this.password.setLayoutData(data);
+
+ this.prompt = new Button(composite, SWT.CHECK);
+ this.prompt.setText("Prompt for password");
+ data = new GridData(GridData.FILL);
+ data.horizontalSpan = 2;
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ this.prompt.setLayoutData(data);
+
+ this.prompt.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ password.setEditable(!((Button) event.getSource()).getSelection());
+ }
+ });
+
+ userTab.setControl(composite);
+ }
+
+ /**
+ * @param tabFolder
+ */
+ private void createOptionsTab(TabFolder tabFolder) {
+ TabItem optionsTab = new TabItem(tabFolder, SWT.NONE);
+ optionsTab.setText("Options");
+
+ Composite composite = new Composite(tabFolder, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ data.grabExcessHorizontalSpace = true;
+ composite.setLayoutData(data);
+
+ Label label;
+
+ label = new Label(composite, SWT.NULL);
+ label.setText("On connection, Auto-Commit should be:");
+ this.autoCommit = new Combo(composite, SWT.SIMPLE | SWT.DROP_DOWN | SWT.READ_ONLY);
+ String autoCommitTypes[] = new String[] {
+ IQuantumConstants.autoCommitTrue,
+ IQuantumConstants.autoCommitFalse,
+ IQuantumConstants.autoCommitSaved
+ };
+ this.autoCommit.setItems(autoCommitTypes);
+
+ data = new GridData();
+ data.horizontalAlignment = GridData.FILL;
+ this.autoCommit.setLayoutData(data);
+
+ optionsTab.setControl(composite);
+
+ }
+
+
+
+ /**
+ * @see org.eclipse.jface.preference.PreferencePage#performApply()
+ */
+ public boolean performOk() {
+ Bookmark bookmark = getBookmark();
+ bookmark.setUsername(this.userid.getText());
+ bookmark.setPromptForPassword(this.prompt.getSelection());
+ if (this.prompt.getSelection()) {
+ bookmark.setPassword("");
+ } else {
+ bookmark.setPassword(this.password.getText());
+ }
+
+ int index = this.type.getSelectionIndex();
+ bookmark.setType(this.adapters[index].getDriverType());
+ bookmark.setConnect(this.jdbcURL.getText());
+ bookmark.setDriver(this.driverName.getText());
+ bookmark.setDriverFile(this.driverPath.getText());
+ if (this.autoCommit.getSelectionIndex() >= 0)
+ bookmark.setAutoCommitPreference(this.autoCommit.getItem(this.autoCommit.getSelectionIndex()));
+ return super.performOk();
+ }
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
+ */
+ protected void performDefaults() {
+ super.performDefaults();
+ Bookmark bookmark = getBookmark();
+
+ this.prompt.setSelection(bookmark.getPromptForPassword());
+ this.password.setEditable(!bookmark.getPromptForPassword());
+ this.password.setText(bookmark.getPassword());
+ this.userid.setText(bookmark.getUsername());
+
+ this.type.select(0);
+ boolean done = false;
+ for (int i = 0,
+ length = (adapters == null) ? 0 : adapters.length;
+ !done && i < length;
+ i++) {
+ if (bookmark.getType() != null &&
+ bookmark.getType().equals(adapters[i].getDriverType())) {
+ this.type.select(i);
+ done = true;
+ }
+ }
+ if (bookmark.getAutoCommitPreference().equals(IQuantumConstants.autoCommitTrue))
+ this.autoCommit.select(0);
+ else if (bookmark.getAutoCommitPreference().equals(IQuantumConstants.autoCommitFalse))
+ this.autoCommit.select(1);
+ else if (bookmark.getAutoCommitPreference().equals(IQuantumConstants.autoCommitSaved))
+ this.autoCommit.select(2);
+
+ this.driverName.setText(bookmark.getDriver());
+ this.jdbcURL.setText(bookmark.getConnect());
+ this.driverPath.setText(bookmark.getDriverFile());
+ }
+}
--- /dev/null
+package com.quantum.properties;
+
+import java.sql.SQLException;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.NotConnectedException;
+import com.quantum.view.bookmark.TreeNode;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.dialogs.PropertyPage;
+
+public class DatabaseInformationPropertyPage extends PropertyPage {
+
+ public DatabaseInformationPropertyPage() {
+ super();
+ }
+
+ protected Control createContents(Composite parent) {
+
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.grabExcessHorizontalSpace = true;
+ composite.setLayoutData(data);
+
+ Label productLabel = new Label(composite, SWT.NONE);
+ productLabel.setText("Product:");
+
+ Label productDescriptionLabel = new Label(composite, SWT.NONE);
+
+ Bookmark bookmark =
+ ((TreeNode) getElement()).getBookmark();
+ String description = null;
+ try {
+ description = bookmark.getDatabase().getInformation();
+ } catch (NotConnectedException e) {
+ } catch (SQLException e) {
+ }
+ if (description == null) {
+ description = "<unknown>";
+ }
+ productDescriptionLabel.setText(description);
+ return composite;
+ }
+
+ protected void performDefaults() {
+ }
+
+ public boolean performOk() {
+ return true;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.properties;
+
+import com.quantum.model.Column;
+import com.quantum.model.Entity;
+import com.quantum.model.Index;
+import com.quantum.view.bookmark.EntityNode;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.TabFolder;
+import org.eclipse.swt.widgets.TabItem;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.ui.dialogs.PropertyPage;
+
+public class EntityPropertyPage extends PropertyPage {
+
+ protected Control createContents(Composite parent) {
+
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.grabExcessHorizontalSpace = true;
+ composite.setLayoutData(data);
+
+ Label label = new Label(composite, SWT.NONE);
+ label.setText("Name:");
+
+ Entity entity = getEntity();
+
+ Label name = new Label(composite, SWT.NONE);
+ name.setText(entity.getName());
+
+ label = new Label(composite, SWT.NONE);
+ label.setText("Schema:");
+
+ Label schema = new Label(composite, SWT.NONE);
+ schema.setText(entity.getSchema());
+
+ if (!Entity.SEQUENCE_TYPE.equals(getEntity().getType())) {
+ TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
+ layout = new GridLayout();
+ tabFolder.setLayout(layout);
+ data = new GridData(GridData.FILL_BOTH);
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessVerticalSpace = true;
+ data.verticalAlignment = GridData.FILL;
+ data.horizontalSpan = 2;
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ tabFolder.setLayoutData(data);
+
+ createColumnsTab(tabFolder);
+ createIndexesTab(tabFolder);
+ }
+
+ return composite;
+ }
+
+ private Entity getEntity() {
+ Entity entity =
+ ((EntityNode) getElement()).getEntity();
+ return entity;
+ }
+
+ private void createColumnsTab(TabFolder tabFolder) {
+ TabItem columnsTab = new TabItem(tabFolder, SWT.NONE);
+ columnsTab.setText("Columns");
+
+ Table table = new Table(tabFolder, SWT.FULL_SELECTION | SWT.MULTI);
+ table.setLinesVisible(true);
+ table.setHeaderVisible(true);
+
+ GridLayout layout = new GridLayout();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+ table.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL_HORIZONTAL;
+ data.verticalAlignment = GridData.FILL_VERTICAL;
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessVerticalSpace = true;
+ table.setLayoutData(data);
+
+ String[] columnNames = { "Name", "Type", "Size", "Digits",
+ "Primary Key", "Nullable", "Remarks" };
+
+ for (int i = 0, length = columnNames.length; i < length; i++) {
+ TableColumn column = new TableColumn(table, SWT.NONE);
+ column.setText(columnNames[i]);
+ }
+ for (int i = 0, length = columnNames.length; i < length; i++) {
+ table.getColumn(i).pack();
+ }
+
+ Column[] columns = getEntity().getColumns();
+ for (int i = 0, length = columns.length; i < length; i++) {
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(new String[] {
+ columns[i].getName(),
+ columns[i].getTypeName(),
+ String.valueOf(columns[i].getSize()),
+ columns[i].getNumberOfFractionalDigits() == 0 ? "" :
+ String.valueOf(columns[i].getNumberOfFractionalDigits()),
+ columns[i].isPrimaryKey() ? "Yes" : "No",
+ columns[i].isNullable() ? "Yes" : "No",
+ columns[i].getRemarks() });
+ }
+
+ for (int i = 0, length = columnNames.length; i < length; i++) {
+ table.getColumn(i).pack();
+ }
+
+ data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL_HORIZONTAL;
+ data.verticalAlignment = GridData.FILL_VERTICAL;
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessVerticalSpace = true;
+ table.setLayoutData(data);
+
+ columnsTab.setControl(table);
+ }
+
+ private void createIndexesTab(TabFolder tabFolder) {
+ TabItem indexesTab = new TabItem(tabFolder, SWT.NONE);
+ indexesTab.setText("Indexes");
+
+ Table table = new Table(tabFolder, SWT.FULL_SELECTION | SWT.MULTI);
+ table.setLinesVisible(true);
+ table.setHeaderVisible(true);
+
+ GridLayout layout = new GridLayout();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+ table.setLayout(layout);
+ GridData data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL_HORIZONTAL;
+ data.verticalAlignment = GridData.FILL_VERTICAL;
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessVerticalSpace = true;
+ table.setLayoutData(data);
+
+ String[] columnNames = { "Name", "Column", "Ascending" };
+
+ for (int i = 0, length = columnNames.length; i < length; i++) {
+ TableColumn column = new TableColumn(table, SWT.NONE);
+ column.setText(columnNames[i]);
+ }
+ for (int i = 0, length = columnNames.length; i < length; i++) {
+ table.getColumn(i).pack();
+ }
+
+ Index[] indexes = getEntity().getIndexes();
+ for (int i = 0, length = indexes.length; i < length; i++) {
+ for (int j = 0, numberOfColumns = indexes[i].getNumberOfColumns();
+ j < numberOfColumns; j++) {
+
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(new String[] {
+ j == 0 ? indexes[i].getName() : "",
+ indexes[i].getColumnName(j),
+ indexes[i].isAscending(j) ? "Yes"
+ : (indexes[i].isDescending(j)) ? "No" : "" });
+ }
+ }
+
+ for (int i = 0, length = columnNames.length; i < length; i++) {
+ table.getColumn(i).pack();
+ }
+
+ data = new GridData(GridData.FILL);
+ data.horizontalAlignment = GridData.FILL_HORIZONTAL;
+ data.verticalAlignment = GridData.FILL_VERTICAL;
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessVerticalSpace = true;
+ table.setLayoutData(data);
+
+ indexesTab.setControl(table);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.properties;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkHolder;
+import com.quantum.model.ConnectionException;
+import com.quantum.model.Schema;
+import com.quantum.sql.SQLHelper;
+import com.quantum.ui.dialog.ExceptionDisplayDialog;
+import com.quantum.util.connection.ConnectionUtil;
+import com.quantum.view.bookmark.AddSchemaDialog;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.dialogs.PropertyPage;
+
+public class SchemaPropertyPage extends PropertyPage {
+
+ class ContentProviderImpl implements IStructuredContentProvider {
+ public Object[] getElements(Object inputElement) {
+ List list = new ArrayList((Collection) inputElement);
+ Collections.sort(list);
+ return list.toArray();
+ }
+
+ public void dispose() {
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
+
+ class LabelProviderImpl implements ITableLabelProvider {
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ if (columnIndex == 0) {
+ return QuantumPlugin.getImage("schema.gif");
+ } else {
+ return null;
+ }
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ if (columnIndex == 0) {
+ return ((Schema) element).getDisplayName();
+ } else {
+ return null;
+ }
+ }
+
+ public void addListener(ILabelProviderListener listener) {
+ }
+
+ public void dispose() {
+ }
+
+ public boolean isLabelProperty(Object element, String property) {
+ return "displayName".equals(property);
+ }
+
+ public void removeListener(ILabelProviderListener listener) {
+ }
+ }
+
+ private Set schemas = Collections.synchronizedSet(new HashSet());
+ private TableViewer schemaTable;
+ private Button addButton;
+ private Button removeButton;
+
+ private ConnectionUtil connectionUtil = new ConnectionUtil();
+
+ protected Control createContents(Composite parent) {
+
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ GridData data = new GridData();
+ composite.setLayoutData(data);
+
+ this.schemaTable = new TableViewer(composite,
+ SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER);
+
+ layout = new GridLayout();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+
+ this.schemaTable.getTable().setLayout(layout);
+ data = new GridData();
+ data.heightHint = 200;
+ data.widthHint = 200;
+// data.verticalSpan = 2;
+ this.schemaTable.getTable().setLayoutData(data);
+ this.schemaTable.setLabelProvider(new LabelProviderImpl());
+ this.schemaTable.setContentProvider(new ContentProviderImpl());
+ this.schemaTable.setInput(this.schemas);
+
+ createButtonArea(composite);
+
+ performDefaults();
+ return composite;
+ }
+
+ private void createButtonArea(Composite composite) {
+ GridLayout layout;
+ GridData data;
+ Composite buttonArea = new Composite(composite, SWT.NONE);
+ layout = new GridLayout();
+ layout.numColumns = 1;
+ buttonArea.setLayout(layout);
+ data = new GridData();
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ buttonArea.setLayoutData(data);
+
+ this.addButton = new Button(buttonArea, SWT.NULL);
+ this.addButton.setText("Add");
+ data = new GridData();
+ data.horizontalAlignment = GridData.FILL_HORIZONTAL;
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ data.widthHint = 60;
+ this.addButton.setLayoutData(data);
+ this.addButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ addSchema();
+ }
+ });
+
+ this.removeButton = new Button(buttonArea, SWT.NULL);
+ this.removeButton.setText("Remove");
+ this.removeButton.setEnabled(false);
+ data = new GridData();
+ data.horizontalAlignment = GridData.FILL_HORIZONTAL;
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ data.widthHint = 60;
+ this.removeButton.setLayoutData(data);
+ this.removeButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ removeSchema(SchemaPropertyPage.this.schemaTable.getSelection());
+ }
+ });
+
+ this.schemaTable.addSelectionChangedListener(new ISelectionChangedListener() {
+ public void selectionChanged(SelectionChangedEvent event) {
+ SchemaPropertyPage.this.removeButton.setEnabled(
+ !event.getSelection().isEmpty());
+ }
+ });
+ }
+
+ private void addSchema() {
+ Bookmark bookmark = getBookmark();
+ boolean isAlreadyConnected = bookmark.isConnected();
+
+ if (!isAlreadyConnected) {
+ boolean confirmed = MessageDialog.openConfirm(getShell(), "Connect Required",
+ "We must connect to the database to retrieve schemas.");
+ if (confirmed) {
+ this.connectionUtil.connect(bookmark, getShell());
+ }
+ }
+
+ try {
+ if (bookmark.isConnected()) {
+ Vector schemas = SQLHelper.getSchemas(bookmark.getConnection());
+ AddSchemaDialog dialog = new AddSchemaDialog(getShell(), schemas);
+ dialog.open();
+ if (dialog.getSelectedSchemas() != null) {
+ Collection temp = dialog.getSelectedSchemas();
+ for (Iterator i = temp.iterator(); i.hasNext();) {
+ String name = (String) i.next();
+ this.schemas.add(new Schema(name));
+ }
+ refreshTable();
+ }
+
+ if (!isAlreadyConnected) {
+ bookmark.disconnect();
+ }
+ }
+ } catch (ConnectionException e) {
+ ExceptionDisplayDialog.openError(getShell(), null, null, e);
+ }
+ }
+
+ private void removeSchema(ISelection selection) {
+ IStructuredSelection structuredSelection = (IStructuredSelection) selection;
+ for (Iterator i = structuredSelection.iterator(); i.hasNext();) {
+ Schema element = (Schema) i.next();
+ this.schemas.remove(element);
+ }
+ refreshTable();
+ }
+
+ private Bookmark getBookmark() {
+ Bookmark bookmark =
+ ((BookmarkHolder) getElement()).getBookmark();
+ return bookmark;
+ }
+
+ /**
+ * @see org.eclipse.jface.preference.PreferencePage#performApply()
+ */
+ public boolean performOk() {
+ getBookmark().setSchemas((Schema[]) this.schemas.toArray(
+ new Schema[this.schemas.size()]));
+ return true;
+ }
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
+ */
+ protected void performDefaults() {
+ super.performDefaults();
+ Bookmark bookmark = getBookmark();
+
+ this.schemas.clear();
+ Schema[] schemas = bookmark.getSchemas();
+ for (int i = 0, length = (schemas == null) ? 0 : schemas.length;
+ i < length;
+ i++) {
+ if (!schemas[i].isDefault()) {
+ this.schemas.add(schemas[i]);
+ }
+ }
+ refreshTable();
+ }
+
+ private void refreshTable() {
+ this.schemaTable.refresh();
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.sql;
+
+import java.sql.Connection;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.ConnectionException;
+import com.quantum.model.PasswordFinder;
+
+/**
+ * @author BC
+ */
+public interface ConnectionEstablisher {
+
+ public Connection connect(Bookmark bookmark, PasswordFinder passwordFinder)
+ throws ConnectionException;
+ public void disconnect(Connection connection)
+ throws ConnectionException;
+
+}
--- /dev/null
+package com.quantum.sql;
+
+import java.util.ArrayList;
+
+public class FilterSort {
+ private ArrayList filterList = new ArrayList();
+ private ArrayList sortList = new ArrayList();
+ private ArrayList ascDescList = new ArrayList();
+ public void addFilter(String column, String operator, String value, boolean isString) {
+ FilterRow row = new FilterRow();
+ row.column = column;
+ row.operator = operator;
+ row.value = value;
+ row.isString = isString;
+ filterList.add(row);
+ }
+ public void clearFilters() {
+ filterList.clear();
+ }
+ public void addSort(String column, String ascDesc) {
+ int ind = sortList.indexOf(column);
+ if (ind < 0) {
+ sortList.add(column);
+ ascDescList.add(ascDesc);
+ return;
+ }
+ if (ind < ascDescList.size()) {
+ ascDescList.remove(ind);
+ }
+ ascDescList.add(ind, ascDesc);
+ }
+ public void removeSort(String column) {
+ int ind = sortList.indexOf(column);
+ if (ind < 0) return;
+ sortList.remove(ind);
+ ascDescList.remove(ind);
+ }
+ public String toString() {
+ StringBuffer text = new StringBuffer();
+ if (filterList.size() > 0) {
+ text.append(" WHERE "); //$NON-NLS-1$
+ for (int i = 0; i < filterList.size(); i++) {
+ FilterRow row = (FilterRow) filterList.get(i);
+ text.append(row.column);
+ text.append(" "); //$NON-NLS-1$
+ text.append(row.operator);
+ text.append(" "); //$NON-NLS-1$
+ if (row.isString) {
+ text.append(escape(row.value));
+ } else {
+ text.append(row.value);
+ }
+ text.append(" "); //$NON-NLS-1$
+ if (i < filterList.size() - 1) {
+ text.append("AND "); //$NON-NLS-1$
+ }
+ }
+ }
+ if (sortList.size() > 0) {
+ text.append(" ORDER BY "); //$NON-NLS-1$
+ for (int i = 0; i < sortList.size(); i++) {
+ String value = (String) sortList.get(i);
+ text.append(value);
+ text.append(" ");
+ text.append(ascDescList.get(i));
+ if (i < sortList.size() - 1) {
+ text.append(", "); //$NON-NLS-1$
+ }
+ }
+ }
+ return text.toString();
+ }
+ public static String escape(String original) {
+ return '\'' + original + '\'';
+ }
+}
+
+class FilterRow {
+ public String column;
+ public String operator;
+ public String value;
+ public boolean isString;
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.sql;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.Driver;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Hashtable;
+import java.util.Properties;
+import java.util.Vector;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.ConnectionException;
+import com.quantum.model.Entity;
+import com.quantum.model.PasswordFinder;
+import com.quantum.sql.metadata.MetaDataJDBCInterface;
+import com.quantum.sql.metadata.ObjectMetaData;
+import com.quantum.view.LogProxy;
+import com.quantum.view.bookmark.EntityNode;
+import com.quantum.view.bookmark.TreeNode;
+
+
+/**
+ * MultiSQLServer is a Singleton, used as a interface with the sql drivers.
+ * Use MultiSQLServer.getInstance() to get the object.
+ */
+public class MultiSQLServer implements ConnectionEstablisher {
+ private static final int STREAM = 1024 * 2;
+ public static final String USERNAME = "user"; //$NON-NLS-1$
+ public static final String PASSWORD = "password"; //$NON-NLS-1$
+ private static MultiSQLServer instance = null;
+ private Hashtable classLoaderCache = new Hashtable();
+ boolean running = true;
+
+ public MultiSQLServer() {
+ //start();
+ }
+ public synchronized static MultiSQLServer getInstance() {
+ if (instance == null) {
+ instance = new MultiSQLServer();
+ }
+ return instance;
+ }
+
+ public void commit(Connection con) {
+ LogProxy log = LogProxy.getInstance();
+ try {
+ con.commit();
+ } catch (SQLException e) {
+ log.addText(LogProxy.ERROR, "Error commiting: " + e, e); //$NON-NLS-1$
+ }
+ }
+
+ public void rollback(Connection con) {
+ LogProxy log = LogProxy.getInstance();
+ try {
+ con.rollback();
+ } catch (SQLException e) {
+ log.addText(LogProxy.ERROR, "Error rolling back: " + e, e); //$NON-NLS-1$
+ }
+ }
+
+ public void setAutoCommit(Connection con, boolean enabled) {
+ LogProxy log = LogProxy.getInstance();
+ try {
+ if (con != null) {
+ con.setAutoCommit(enabled);
+ } else {
+ log.addText(LogProxy.ERROR, "Please connect before setting autocommit"); //$NON-NLS-1$
+ }
+ } catch (SQLException e) {
+ log.addText(LogProxy.ERROR, "Error setting autocommit: " + e, e); //$NON-NLS-1$
+ }
+ }
+
+ public void disconnect(Connection connection) throws ConnectionException {
+ try {
+ if (connection != null) {
+ connection.close();
+ }
+ } catch (SQLException e) {
+ throw new ConnectionException(e);
+ }
+ }
+
+ public Vector getSchemas(Connection con) {
+ ResultSet set;
+ Vector schemaList = new Vector();
+ try {
+ DatabaseMetaData meta = con.getMetaData();
+ set = meta.getSchemas();
+ while (set.next()) {
+ schemaList.add(set.getString("TABLE_SCHEM")); //$NON-NLS-1$
+ }
+ set.close();
+ } catch (SQLException e) {
+ LogProxy log = LogProxy.getInstance();
+ log.addText(LogProxy.ERROR, e);
+ }
+ return schemaList;
+ }
+ /**
+ * Makes a connection to a JDBC driver based on the data from a bookmark
+ * @param bookmark -
+ * The Bookmark with the data needed to make the connection
+ * @param passwordFinder -
+ * A utility class that can be invoked if the bookmark does not
+ * include a password
+ * @return The Connection object if everything went OK
+ */
+ public Connection connect(Bookmark bookmark, PasswordFinder passwordFinder)
+ throws ConnectionException {
+
+ String password = bookmark.getPassword();
+ if (bookmark.getPromptForPassword()) {
+ password = passwordFinder.getPassword();
+ if (passwordFinder.isPasswordMeantToBeSaved()) {
+ bookmark.setPassword(password);
+ }
+ }
+ Connection con;
+ if (password != null) {
+ con = connect(bookmark, password);
+ } else {
+ return null;
+ }
+ // Set the autoCommit state of the bookmark to the default on new connections
+ bookmark.setAutoCommit(bookmark.getDefaultAutoCommit());
+ // Set the autoCommit state of the JDBC connection to the bookmark autoCommit statec
+ setAutoCommit(con, bookmark.isAutoCommit());
+ return con;
+
+ }
+ private Connection connect(Bookmark bookmark, String password)
+ throws ConnectionException {
+ LogProxy log = LogProxy.getInstance();
+ log.addText(LogProxy.QUERY, "Connecting to: " + bookmark.getName()); //$NON-NLS-1$
+ URL urls[] = new URL[1];
+ try {
+ String driverFile = bookmark.getDriverFile();
+ URLClassLoader loader =
+ (URLClassLoader) classLoaderCache.get(driverFile);
+ if (loader == null) {
+ urls[0] = new File(driverFile).toURL();
+ loader = new URLClassLoader(urls);
+ classLoaderCache.put(driverFile, loader);
+ System.out.println("Creating new classloader"); //$NON-NLS-1$
+ } else {
+ System.out.println("Using classloader in cache"); //$NON-NLS-1$
+ }
+ Class driverClass = loader.loadClass(bookmark.getDriver());
+ Driver driver = (Driver) driverClass.newInstance();
+ Properties props = new Properties();
+ props.put(USERNAME, bookmark.getUsername());
+ props.put(PASSWORD, password);
+ Connection connection =
+ driver.connect(bookmark.getConnect(), props);
+ if (connection == null) {
+ throw new ConnectionException("Error: Driver returned a null connection: " + bookmark.toString()); //$NON-NLS-1$
+ }
+ log.addText(LogProxy.RESULTS, "Connected to: " + bookmark.getName()); //$NON-NLS-1$
+ System.out.println("Connected"); //$NON-NLS-1$
+ return connection;
+ } catch (SQLException e) {
+ throw new ConnectionException(e);
+ } catch (MalformedURLException e) {
+ throw new ConnectionException(e);
+ } catch (ClassNotFoundException e) {
+ throw new ConnectionException(e);
+ } catch (InstantiationException e) {
+ throw new ConnectionException(e);
+ } catch (IllegalAccessException e) {
+ throw new ConnectionException(e);
+ }
+ }
+ public SQLResults execute(Connection con, String s) throws SQLException {
+ return execute(con, s, -1, -1);
+ }
+ public SQLResults execute(Connection con, String s, int startRow, int endRow) throws SQLException {
+ return execute(con, s, -1, -1, Integer.MAX_VALUE);
+ }
+
+ public SQLResults execute(Connection con, String s, int startRow, int endRow, int maxLength) throws SQLException {
+ return execute(con, s, startRow, endRow, maxLength, ""); //$NON-NLS-1$
+ }
+
+ public SQLResults execute(
+ Connection con,
+ String s,
+ int startRow,
+ int endRow,
+ int maxLength,
+ String encoding)
+ throws SQLException {
+
+ SQLResults results = new SQLResults();
+
+ System.out.println("Executing"); //$NON-NLS-1$
+ LogProxy log = LogProxy.getInstance();
+ log.addText(LogProxy.QUERY, "Executing Request [" + s + "]"); //$NON-NLS-1$ //$NON-NLS-2$
+ boolean metadata = false;
+ if (s.startsWith("METADATA")) { //$NON-NLS-1$
+ metadata = true;
+ }
+ if (metadata) {
+ results.setQuery(s);
+ String table = s.substring(s.indexOf(':') + 1);
+ String query = "SELECT * FROM " + table + " WHERE (1 = 0)"; //$NON-NLS-1$ //$NON-NLS-2$
+ s = query;
+ log.addText(LogProxy.QUERY, "Metadata Request [" + s + "]"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ results.setQuery(s);
+ }
+
+ Statement stmt = con.createStatement();
+ boolean flag = stmt.execute(s);
+ results.setResultSet(flag);
+ if (metadata) {
+ genMetadataResultSet(results, stmt);
+ return results;
+ }
+ if (!flag) {
+ int updates = stmt.getUpdateCount();
+ results.setUpdateCount(updates);
+ log.addText(LogProxy.RESULTS, "Success: " + updates + " records updated"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ } else {
+ ResultSet set = stmt.getResultSet();
+ ResultSetMetaData metaData = set.getMetaData();
+ int columnCount = metaData.getColumnCount();
+ Vector columnNames = new Vector();
+ for (int i = 1; i <= columnCount; i++) {
+ columnNames.addElement(metaData.getColumnName(i));
+ }
+ results.setColumnNames(columnNames);
+ Vector columnTypes = new Vector();
+ for (int i = 1; i <= columnCount; i++) {
+ columnTypes.addElement(metaData.getColumnTypeName(i));
+ }
+ results.setColumnTypes(columnTypes);
+ int columnSizes[] = new int[columnCount];
+ for (int i = 1; i <= columnCount; i++) {
+ columnSizes[i - 1] = metaData.getColumnDisplaySize(i);
+ }
+ int rowCount = 1;
+ boolean exitEarly = false;
+ while (set.next()) {
+ boolean disable = startRow < 1 || endRow < 1;
+ boolean start = rowCount >= startRow;
+ boolean end = rowCount <= endRow;
+ if (disable || (start && end)) {
+ Vector row = new Vector();
+ for (int i = 1; i <= columnCount; i++) {
+ String value;
+ if (columnSizes[i - 1] < STREAM
+ && columnSizes[i - 1] < maxLength) {
+ if (encoding.equals("")) { //$NON-NLS-1$
+ value = set.getString(i);
+ } else {
+ try {
+ value =
+ new String(set.getBytes(i), encoding);
+ } catch (UnsupportedEncodingException e) {
+ log.addText(LogProxy.ERROR, "Error Unsupported encoding " + encoding.toString() + ":" + e.toString(), e); //$NON-NLS-1$ //$NON-NLS-2$
+ value = new String(set.getBytes(i));
+ }
+ }
+ } else {
+ try {
+ if (encoding.equals("")) { //$NON-NLS-1$
+ Reader reader = set.getCharacterStream(i);
+ StringBuffer buffer = new StringBuffer();
+ if (reader != null) {
+ int retVal = reader.read();
+ int count = 0;
+ while (retVal >= 0) {
+ buffer.append((char) retVal);
+ retVal = reader.read();
+ count++;
+ if (count > maxLength) {
+ buffer.append("...>>>"); //$NON-NLS-1$
+ break;
+ }
+ }
+ reader.close();
+ }
+ value = buffer.toString();
+ } else {
+ InputStream binaryStream =
+ set.getBinaryStream(i);
+ ByteArrayOutputStream baos =
+ new ByteArrayOutputStream();
+ if (binaryStream != null) {
+ int retVal = binaryStream.read();
+ int count = 0;
+ while (retVal >= 0) {
+ baos.write(retVal);
+ retVal = binaryStream.read();
+ count++;
+ if (count > maxLength) {
+ break;
+ }
+ }
+ binaryStream.close();
+ }
+ value =
+ new String(
+ baos.toByteArray(),
+ encoding);
+ }
+ } catch (Throwable e) {
+ // hack for mysql which doesn't implement
+ // character streams
+ value = set.getString(i);
+ }
+ }
+ if (set.wasNull()) {
+ row.addElement("<NULL>"); //$NON-NLS-1$
+ } else {
+ row.addElement(value);
+ }
+ }
+ results.addRow(row);
+ }
+ rowCount++;
+ if (!disable && (rowCount > endRow)) {
+ exitEarly = true;
+ break;
+ }
+ }
+ if (exitEarly) {
+ results.setHasMore(set.next());
+ } else {
+ results.setMaxSize(rowCount);
+ results.setHasMore(false);
+ }
+ set.close();
+ }
+ log.addText(LogProxy.RESULTS, "Success: result set displayed"); //$NON-NLS-1$
+ stmt.close();
+ System.out.println("Executed"); //$NON-NLS-1$
+ System.out.println();
+ return results;
+ }
+ private void genMetadataResultSet(SQLResults results, Statement stmt)
+ throws SQLException {
+ ResultSet set = stmt.getResultSet();
+ ResultSetMetaData metaData = set.getMetaData();
+ int columnCount = metaData.getColumnCount();
+ Vector columnNames = new Vector();
+ columnNames.addElement("ColumnName"); //$NON-NLS-1$
+ columnNames.addElement("Type"); //$NON-NLS-1$
+ columnNames.addElement("Size"); //$NON-NLS-1$
+ columnNames.addElement("Nullable"); //$NON-NLS-1$
+ columnNames.addElement("AutoIncrement"); //$NON-NLS-1$
+ results.setColumnNames(columnNames);
+ for (int i = 1; i <= columnCount; i++) {
+ Vector row = new Vector();
+ row.addElement(metaData.getColumnName(i));
+ row.addElement(metaData.getColumnTypeName(i));
+ int textSize = metaData.getColumnDisplaySize(i);
+ int precision = metaData.getPrecision(i);
+ int scale = metaData.getScale(i);
+ if (scale == 0 && precision == 0) {
+ row.addElement(Integer.toString(precision));
+ } else {
+ row.addElement(textSize + ", " + precision + ", " + scale); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ int nullable = metaData.isNullable(i);
+ if (nullable == ResultSetMetaData.columnNoNulls) {
+ row.addElement("Not Null"); //$NON-NLS-1$
+ } else if (nullable == ResultSetMetaData.columnNullable) {
+ row.addElement("Nullable"); //$NON-NLS-1$
+ } else if (
+ nullable == ResultSetMetaData.columnNullableUnknown) {
+ row.addElement("Nullable"); //$NON-NLS-1$
+ } else {
+ row.addElement("<Error>"); //$NON-NLS-1$
+ }
+ row.addElement(
+ (metaData.isAutoIncrement(i)
+ ? Boolean.TRUE
+ : Boolean.FALSE)
+ .toString());
+ results.addRow(row);
+ }
+ results.setHasMore(false);
+ set.close();
+ }
+
+ /**
+ * Returns an ObjectMetadata object got from the connection 'con' using the name and schema of the node.
+ * @param con
+ * @param node
+ * @return
+ * @throws SQLException
+ */
+ public ObjectMetaData getObjectMetadata(Connection con, TreeNode node) throws SQLException {
+ ObjectMetaData metadata = new ObjectMetaData();
+ if (!(node instanceof Entity)) return metadata;
+
+ String schema = ((Entity)node).getSchema();
+ String tableName = node.getName();
+
+ if (schema.length() == 0) schema = null;
+ metadata.setColumns(MetaDataJDBCInterface.getColumns(con, schema, tableName));
+ if (node instanceof EntityNode && ((EntityNode) node).isTable()) {
+ metadata.setPrimaryKeys(MetaDataJDBCInterface.getPrimaryKeys(con, schema, tableName));
+ metadata.setForeignKeys(MetaDataJDBCInterface.getForeignKeys(con, schema, tableName, true));
+ metadata.setIndexInfo(MetaDataJDBCInterface.getIndexInfo(con, schema, tableName));
+ metadata.setBestRowId(MetaDataJDBCInterface.getBestRowId(con, schema, tableName));
+ }
+ return metadata;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.sql;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Vector;
+
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.view.LogProxy;
+
+public class SQLHelper {
+
+ public static Vector getSchemas(Connection connection) {
+ return MultiSQLServer.getInstance().getSchemas(connection);
+ }
+ public static int getSize(Connection connection, String tableName, DatabaseAdapter adapter) throws SQLException {
+ SQLResults results = MultiSQLServer.getInstance().execute(
+ connection, adapter.getCountQuery(tableName));
+ if (results.getRowCount() > 0 && results.getColumnCount() > 0) {
+ return Integer.parseInt(results.getElement(1, 1).toString());
+ } else {
+ return -1;
+ }
+ }
+
+ public static SQLResults getResults(Connection connection, String query, int start, int end, int maxLength, String encoding) {
+ try {
+ return MultiSQLServer.getInstance().execute(connection,
+ query, start, end, maxLength, encoding);
+ } catch (SQLException e) {
+ LogProxy log = LogProxy.getInstance();
+ log.addText(
+ LogProxy.ERROR,
+ "Error Executing: " + query + ":" + e.toString(), e); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ SQLResults results = new SQLResults();
+ results.setIsError(true);
+ return results;
+ }
+
+ /**
+ * True if the type is Real (numeric and with decimal part) according to java.sql.Types
+ * @param type
+ * @return
+ */
+ public static boolean isReal(int type) {
+ return (type == java.sql.Types.DECIMAL || type == java.sql.Types.DOUBLE || type ==java.sql.Types.FLOAT ||
+ type == java.sql.Types.NUMERIC || type == java.sql.Types.REAL );
+ }
+
+ /**
+ * True if the type is Numeric according to java.sql.Types
+ * @param type
+ * @return
+ */
+ public static boolean isNumeric(int type) {
+ return (type == java.sql.Types.DECIMAL || type == java.sql.Types.DOUBLE || type ==java.sql.Types.FLOAT ||
+ type == java.sql.Types.NUMERIC || type == java.sql.Types.REAL || type == java.sql.Types.BIGINT ||
+ type == java.sql.Types.TINYINT || type == java.sql.Types.SMALLINT || type == java.sql.Types.INTEGER );
+ }
+ /**
+ * True if the type is textual according to java.sql.Types
+ * @param type
+ * @return
+ */
+ public static boolean isText(int type) {
+ return (type == java.sql.Types.CLOB || type == java.sql.Types.VARBINARY || type ==java.sql.Types.VARCHAR
+ || type == java.sql.Types.CHAR || type == java.sql.Types.LONGVARCHAR );
+ }
+
+ public static String getQualifiedName(String schema, String name) {
+ return (schema != null && schema.length() > 0) ? schema + "." + name : name;
+ }
+}
--- /dev/null
+package com.quantum.sql;
+
+import java.util.Vector;
+
+import com.quantum.sql.parser.SQLLexx;
+import com.quantum.sql.parser.Token;
+
+public class SQLParser {
+
+ /**
+ * Parses a query string into executable units.
+ * @param query
+ * @return a Vector of Strings, with the individual executable units.
+ */
+ public static Vector parse(String query) {
+ Vector commands = new Vector();
+ Vector groups = new Vector();
+ try {
+ Vector tokens = SQLLexx.parse(query);
+ StringBuffer buffer = new StringBuffer();
+ StringBuffer groupBuffer = new StringBuffer();
+ for (int i = 0; i < tokens.size(); i++) {
+ Token t = (Token) tokens.elementAt(i);
+ if (t.getType() == Token.COMMENT) {
+ // ignore comments
+ } else if (t.getType() == Token.SEPARATOR) {
+ groupBuffer.append(t.getValue());
+ String newCommand = buffer.toString().trim();
+ if (!newCommand.equals("")) { //$NON-NLS-1$
+ commands.addElement(newCommand);
+ }
+ buffer = new StringBuffer();
+ } else if (t.getType() == Token.GROUP) {
+ // We don't append the group token because it may be misinterpreted
+ //groupBuffer.append(t.getValue());
+ String newGroup = groupBuffer.toString().trim();
+ if (!newGroup.equals("")) { //$NON-NLS-1$
+ groups.addElement(newGroup);
+ //Groups have precedence over commands, so the preceding commands are erased
+ commands.clear();
+ }
+ groupBuffer = new StringBuffer();
+ } else {
+ // We append the tokens to the buffer until it's a separator or group.
+ buffer.append(t.getValue());
+ groupBuffer.append(t.getValue());
+ }
+ }
+ String newCommand = buffer.toString().trim();
+ if (!newCommand.equals("")) { //$NON-NLS-1$
+ commands.addElement(newCommand);
+ }
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+ System.out.println("Returning"); //$NON-NLS-1$
+ Vector result = new Vector();
+ result.addAll(groups);
+ result.addAll(commands);
+ return result;
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.sql;
+
+import java.util.ArrayList;
+import java.util.Vector;
+
+/**
+ * com.quantum project
+ * @author root
+ *
+*/
+public class SQLResults {
+ private String query;
+ private String table;
+ private ArrayList rows = new ArrayList();
+ private Vector columns;
+ private Vector columnTypes;
+ private int[] columnSizes;
+ private int updateCount = 0;
+ private boolean resultSet = false;
+ private boolean hasMore = false;
+ private boolean isError = false;
+ private int maxSize = -1;
+
+ public void setColumnNames(Vector columns) {
+ this.columns = columns;
+ }
+ public String getColumnName(int column) {
+ if (columns.size() < column) return ""; //$NON-NLS-1$
+ return columns.elementAt(column - 1).toString();
+
+ }
+ public void setColumnTypes(Vector columnsTypes) {
+ this.columnTypes = columnsTypes;
+ }
+ public String getColumnType(int column) {
+ if (columnTypes.size() < column) return ""; //$NON-NLS-1$
+ return columnTypes.elementAt(column - 1).toString();
+ }
+ public void setColumnSizes(int[] columnSizes) {
+ this.columnSizes = columnSizes;
+ }
+ public int getColumnSize(int column) {
+ if (columnSizes.length < column) return 0;
+ return columnSizes[column - 1];
+ }
+ public void addRow(Vector row) {
+ rows.add(row);
+ }
+ public Object getElement(int column, int row) {
+ return ((Vector) rows.get(row - 1)).elementAt(column - 1);
+ }
+ public int getColumnCount() {
+ if (columns.size() > 0) {
+ return columns.size();
+ }
+ return 0;
+ }
+ public int getRowCount() {
+ return rows.size();
+ }
+ /**
+ * Returns the query.
+ * @return String
+ */
+ public String getQuery() {
+ return query;
+ }
+
+ /**
+ * Sets the query.
+ * @param query The query to set
+ */
+ public void setQuery(String query) {
+ this.query = query;
+ }
+
+ /**
+ * Returns the resultSet.
+ * @return boolean
+ */
+ public boolean isResultSet() {
+ return resultSet;
+ }
+
+ /**
+ * Sets the resultSet.
+ * @param resultSet The resultSet to set
+ */
+ public void setResultSet(boolean resultSet) {
+ this.resultSet = resultSet;
+ }
+
+ public int getUpdateCount() {
+ return updateCount;
+ }
+
+ public void setUpdateCount(int updateCount) {
+ this.updateCount = updateCount;
+ }
+
+ public String getTable() {
+ return table;
+ }
+
+ public void setTable(String table) {
+ this.table = table;
+ }
+
+ public boolean hasMore() {
+ return hasMore;
+ }
+
+ public void setHasMore(boolean hasMore) {
+ this.hasMore = hasMore;
+ }
+
+ public int getMaxSize() {
+ return maxSize;
+ }
+
+ public void setMaxSize(int maxSize) {
+ this.maxSize = maxSize;
+ }
+
+ public boolean isError() {
+ return isError;
+ }
+
+ public void setIsError(boolean isError) {
+ this.isError = isError;
+ }
+ /**
+ *
+ */
+ public Object[] getRows() {
+ return rows.toArray();
+ }
+
+}
--- /dev/null
+package com.quantum.sql;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+import com.quantum.util.StringMatrix;
+
+public class TableRow {
+ private String[] columnNames;
+ private Bookmark bookmark;
+ private String table;
+ private Entity entity;
+ private StringMatrix fullTableData;
+
+ public TableRow(Entity entity, Bookmark bookmark, String table, StringMatrix tableData) {
+ this.entity = entity;
+ this.table = table;
+ // tableData will contain the first row of the tableData, for compatibility reasons with older code
+ // TODO: refactor the older code to allow for multiple selections
+ this.columnNames = tableData.getHeader();
+ this.bookmark = bookmark;
+ this.fullTableData = tableData;
+ }
+
+ public int getColumnCount() {
+ return columnNames.length;
+ }
+
+ public String[] getColumnNames() {
+ return columnNames;
+ }
+
+ public String getTable() {
+ return table;
+ }
+
+ public Bookmark getBookmark() {
+ return this.bookmark;
+ }
+
+ public Entity getEntity() {
+ return this.entity;
+ }
+
+ public void setColumnNames(String[] columnNames) {
+ this.columnNames = columnNames;
+ }
+
+ public String[] getTableData() {
+ return getTableRow(0);
+ }
+
+ public String[] getTableRow(int i) {
+ return fullTableData.getRow(i);
+ }
+
+ public StringMatrix getRowTableData() {
+ return fullTableData;
+ }
+
+}
--- /dev/null
+/*
+ * Created on 8/04/2003
+ *
+ */
+package com.quantum.sql.metadata;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import com.quantum.util.StringMatrix;
+
+/**
+ * Groups functions that allow extracting data from a JDBC connection
+ * in the form of StringMatrix objects
+ *
+ * @author panic
+ *
+ */
+public class MetaDataJDBCInterface {
+
+ /**
+ * @param con : A valid (open) connection to an JDBC database
+ * @param schema : Schema of the table. Must be null if not given
+ * @param table : Name of the table.
+ * @return a StringMatrix with the info of the columns' metadata, null if error
+ */
+ public static StringMatrix getColumns(Connection con, String schema, String table)
+ throws SQLException {
+
+ DatabaseMetaData meta = con.getMetaData();
+ ResultSet set = null;
+ StringMatrix columns = null;
+ try {
+ set = meta.getColumns(null, schema, table, null);
+ columns = fillMatrix(set);
+ set.close();
+
+ } catch (SQLException e) {
+ }
+ if (columns == null) {
+ columns = new StringMatrix();
+ String query = "SELECT * FROM \"" + table + "\" WHERE (1 = 0)"; //$NON-NLS-1$ //$NON-NLS-2$
+ Statement stmt = con.createStatement();
+ stmt.execute(query);
+ ResultSet rset = stmt.getResultSet();
+ ResultSetMetaData rsMetaData = rset.getMetaData();
+ int columnCount = rsMetaData.getColumnCount();
+ String headMatrix[] = {"TABLE_CAT","TABLE_SCHEM","TABLE_NAME","COLUMN_NAME","DATA_TYPE","TYPE_NAME","COLUMN_SIZE",
+ "BUFFER_LENGTH","DECIMAL_DIGITS","NUM_PREC_RADIX","NULLABLE","REMARKS",
+ "COLUMN_DEF","SQL_DATA_TYPE","SQL_DATETIME_SUB","CHAR_OCTET_LENGTH",
+ "ORDINAL_POSITION","IS_NULLABLE","SCOPE_CATLOG","SCOPE_SCHEMA","SCOPE_TABLE","SOURCE_DATA_TYPE"};
+ columns.addMatrixHeader(headMatrix);
+ for (int i = 0; i < columnCount; i++) {
+ columns.add(null, i); /* TABLE_CAT */
+ columns.add(schema, i); /* TABLE_SCHEM */
+ columns.add(table, i); /* TABLE_NAME */
+ columns.add(rsMetaData.getColumnName(i+1), i); /* COLUMN_NAME */
+ columns.add(String.valueOf(rsMetaData.getColumnType(i+1)), i); /* DATA_TYPE */
+ columns.add(rsMetaData.getColumnTypeName(i+1), i); /* TYPE_NAME */
+ columns.add(String.valueOf(rsMetaData.getPrecision(i+1)), i); /* COLUMN_SIZE */
+ columns.add(null, i); /* BUFFER_LENGTH */
+ columns.add(String.valueOf(rsMetaData.getScale(i+1)), i); /* DECIMAL_DIGITS */
+ columns.add(null, i); /* NUM_PREC_RADIX */
+ int isNullable = rsMetaData.isNullable(i+1);
+ columns.add(String.valueOf(isNullable), i); /* NULLABLE */
+ columns.add(null, i); /* REMARKS */
+ columns.add(null, i); /* COLUMN_DEF */
+ columns.add(null, i); /* SQL_DATA_TYPE */
+ columns.add(null, i); /* SQL_DATETIME_SUB */
+ columns.add(String.valueOf(rsMetaData.getColumnDisplaySize(i+1)), i); /* CHAR_OCTET_LENGTH */
+ columns.add(String.valueOf(i+1), i); /* ORDINAL_POSITION */
+ columns.add(isNullable == DatabaseMetaData.columnNullable ? "YES" : "NO", i );
+ columns.add(null, i); /* SCOPE_CATLOG */
+ columns.add(null, i); /* SCOPE_SCHEMA */
+ columns.add(null, i); /* SCOPE_TABLE */
+ columns.add(null, i); /* SOURCE_DATA_TYPE */
+ }
+ }
+ return columns;
+ }
+
+ /**
+ * @param con : A valid (open) connection to an JDBC database
+ * @param schema : Schema of the table. Must be null if not given
+ * @param table : Name of the table.
+ * @return a StringMatrix with the info of the primary keys
+ */
+ public static StringMatrix getPrimaryKeys(Connection con, String schema, String table) {
+
+ StringMatrix keys = new StringMatrix();
+ try {
+ DatabaseMetaData meta = con.getMetaData();
+ ResultSet set = meta.getPrimaryKeys(null, schema, table);
+ keys = fillMatrix(set);
+ set.close();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return keys;
+ }
+
+ /**
+ * @param con : A valid (open) connection to an JDBC database
+ * @param schema : Schema of the table. Must be null if not given
+ * @param table : Name of the table.
+ * @param imported : Determines if the foreign keys are the imported or exported ones
+ * @return a StringMatrix with the info of the foreign keys
+ */
+ public static StringMatrix getForeignKeys(Connection con, String schema, String table, boolean imported ) {
+
+ ResultSet set = null;
+ StringMatrix keys = new StringMatrix();
+ try {
+ DatabaseMetaData meta = con.getMetaData();
+ if (imported){
+ set = meta.getImportedKeys(null, schema, table);
+ } else {
+ set = meta.getExportedKeys(null, schema, table);
+ }
+ keys = fillMatrix(set);
+ set.close();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return keys;
+ }
+
+ /**
+ * @param con : A valid (open) connection to an JDBC database
+ * @param schema : Schema of the table. Must be null if not given
+ * @param table : Name of the table.
+ * @return a StringMatrix with the info of the indexes on that table
+ */
+ public static StringMatrix getIndexInfo(Connection con, String schema, String table) {
+
+ ResultSet set = null;
+ DatabaseMetaData meta;
+ StringMatrix keys = new StringMatrix();
+ try {
+ meta = con.getMetaData();
+ set = meta.getIndexInfo(null, schema, table, false, false);
+ keys = fillMatrix(set);
+ set.close();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return keys;
+ }
+
+
+ /**
+ *
+ * @param set
+ * @return a filled StringMatrix with the set results
+ * @throws SQLException
+ */
+ public static StringMatrix fillMatrix(ResultSet set) throws SQLException {
+ int columnCount = set.getMetaData().getColumnCount();
+ StringMatrix keys = new StringMatrix();
+ for (int i = 1; i <= columnCount; i++) {
+ keys.addHeader(set.getMetaData().getColumnName(i));
+ }
+ int row = 0;
+ while (set.next()) {
+ for (int i = 1; i <= columnCount; i++) {
+ keys.add(set.getString(i), row);
+ }
+ row++;
+ }
+ return keys;
+ }
+
+ /**
+ * @param con
+ * @param schema
+ * @param tableName
+ */
+ public static StringMatrix getBestRowId(Connection con, String schema, String table)
+ throws SQLException {
+
+ ResultSet set = null;
+ DatabaseMetaData meta = con.getMetaData();
+ set = meta.getBestRowIdentifier(null, schema, table, DatabaseMetaData.bestRowSession, true);
+ StringMatrix keys = fillMatrix(set);
+ set.close();
+ return keys;
+
+ }
+
+
+}
--- /dev/null
+/*
+ * Created on 15/04/2003
+ *
+ */
+package com.quantum.sql.metadata;
+
+import java.util.Vector;
+
+import com.quantum.util.StringMatrix;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+
+
+/**
+ * @author panic
+ * Handles interface between an ObjectMetaData and XML storage.
+ * It can write an existing metadata object to XML and generate
+ * a new ObjectMetaData from existing XML.
+ */
+public class MetaDataXMLInterface {
+
+ /**
+ * Exports an ObjectMetaData to an XML document, under a root Element
+ * @param metadata The ObjectMetaData to export
+ * @param doc A valid XML document to receive the export
+ * @param root The Element under which all the XML data will be written
+ */
+ public static void metaDataToXML(ObjectMetaData metadata, Document doc, Element root) {
+ StringMatrix columns = metadata.getColumns();
+ if (columns != null)
+ stringMatrixToXML(columns, doc, root, "COLUMN"); //$NON-NLS-1$
+ StringMatrix primaryKeys = metadata.getPrimaryKeys();
+ if (primaryKeys != null)
+ stringMatrixToXML(primaryKeys, doc, root, "PRIMARY_KEY_ITEM"); //$NON-NLS-1$
+ StringMatrix foreignKeys = metadata.getForeignKeys();
+ if (foreignKeys != null)
+ stringMatrixToXML(foreignKeys, doc, root, "FOREIGN_KEY_ITEM"); //$NON-NLS-1$
+ StringMatrix indexInfo = metadata.getIndexInfo();
+ if (indexInfo != null)
+ stringMatrixToXML(indexInfo, doc, root, "INDEX_ITEM"); //$NON-NLS-1$
+ }
+
+ /**
+ * Imports an XML element to an ObjectMetaData. The format has to be the same as extracted by
+ * the MetaDataToXML function.
+ * @param metadata The ObjectMetaData to fill up. Usually empty.
+ * @param root The Element having all the XML data
+ */
+ public static void xmlToMetaData(ObjectMetaData metadata, Element root) {
+ StringMatrix columns = new StringMatrix();
+ MetaDataXMLInterface.xmlToStringMatrix(columns, root, "COLUMN"); //$NON-NLS-1$
+ metadata.setColumns(columns);
+ StringMatrix primaryKeys = new StringMatrix();
+ MetaDataXMLInterface.xmlToStringMatrix(primaryKeys, root, "PRIMARY_KEY_ITEM"); //$NON-NLS-1$
+ metadata.setPrimaryKeys(primaryKeys);
+ StringMatrix foreignKeys = new StringMatrix();
+ MetaDataXMLInterface.xmlToStringMatrix(foreignKeys, root, "FOREIGN_KEY_ITEM"); //$NON-NLS-1$
+ metadata.setForeignKeys(foreignKeys);
+ StringMatrix indexInfo = new StringMatrix();
+ MetaDataXMLInterface.xmlToStringMatrix(indexInfo, root, "INDEX_ITEM"); //$NON-NLS-1$
+ metadata.setIndexInfo(indexInfo);
+ }
+
+ /**
+ * Adds a StringMatrix to an XML document
+ * @param matrix The StringMatrix to add
+ * @param doc The XmlDocument to which it will be added
+ * @param root An element of the previous document under which the info will be added
+ * @param sub A key under which each row of the StringMatrix will be added
+ */
+ public static void stringMatrixToXML(StringMatrix matrix, Document doc, Element root, String sub) {
+ for (int i = 0; i < matrix.size(); i++) {
+ Element localRoot = (Element) root.appendChild(doc.createElement(sub));
+ for (int j = 0; j < matrix.getNumColumns(); j++) {
+ String key = matrix.getHeaderColumn(j);
+ Element tableName = (Element) localRoot.appendChild(doc.createElement(key));
+ String value = matrix.get(key, i);
+ if (value != null)
+ tableName.appendChild(doc.createTextNode(value));
+ }
+ }
+ }
+
+ /**
+ * Fills a StringMatrix with the data from XML, usually extracted with the StringMatrixToXML function
+ * @param matrix The matrix to fill up, usually empty.
+ * @param root The Element with all the data in XML DOM
+ * @param sub The String to select the Nodes which interest us. Only the selected nodes will be added
+ * to the StringMatrix.
+ */
+ private static void xmlToStringMatrix(StringMatrix matrix, Element root, String sub) {
+ NodeList columns = root.getElementsByTagName(sub);
+ for (int i = 0; i < columns.getLength(); i++) {
+ Node column = columns.item(i);
+ NodeList columnList = column.getChildNodes();
+ for (int j = 0; j < columnList.getLength(); j++) {
+ Node node = columnList.item(j);
+ String header = node.getNodeName();
+ if (header.equals("#text")) //$NON-NLS-1$
+ continue;
+ String value = null;
+ if (node != null && node.hasChildNodes()) {
+ Node valueNode = node.getFirstChild();
+ if (valueNode instanceof Text) {
+ value = valueNode.getNodeValue();
+ }
+ }
+ if (!matrix.contains(header))
+ matrix.addHeader(header);
+ matrix.addAt(header, value, i);
+ }
+ }
+ }
+ /**
+ * Creates a new Element with a text value
+ * @param root
+ * @param key
+ * @param value
+ * @return
+ */
+ public static Element createElementText(Element root, String key, String value){
+ // get the XmlDocument for use as a factory
+ Document doc = root.getOwnerDocument();
+ Element newElement = doc.createElement(key);
+
+ root.appendChild(newElement);
+ if (value != null && value.length() > 0)
+ {
+ Text valueText = doc.createTextNode(value);
+ newElement.appendChild(valueText);
+ }
+ return newElement;
+ }
+
+ public static String getElementText(Element root, String key){
+ return getElementText(root, key, "");
+ }
+ /**
+ * gets the text value from an element or a child of it
+ * @param root element root
+ * @param key key to search
+ * @param defValue default string value if not found
+ * @return
+ */
+ public static String getElementText(Element root, String key, String defValue){
+ // get the XmlDocument for use as a factory
+ String value = defValue;
+ if (root.getNodeName().equals(key)){
+ value = extractText(root, defValue);
+ } else {
+ NodeList children = root.getElementsByTagName(key);
+ if (children.getLength() > 0) {
+ Element column = (Element) children.item(0);
+ value = extractText(column, defValue);
+ }
+ }
+ return value;
+ }
+
+ private static String extractText(Element node, String defValue){
+ String value = defValue;
+ if (node != null && node.hasChildNodes()) {
+ Node valueNode = node.getFirstChild();
+ if (valueNode instanceof Text) {
+ value = valueNode.getNodeValue();
+ }
+ }
+ return value;
+ }
+
+ /**
+ * Gets a Vector with the String values of the keys
+ * that are children of 'root' and that match 'key'
+ * @param root
+ * @param key
+ * @return
+ */
+ public static Vector getVectorText(Element root, String key) {
+ Vector result = new Vector();
+ NodeList children = root.getElementsByTagName(key);
+ for (int i = 0; i < children.getLength(); i++) {
+ Element column = (Element) children.item(i);
+ result.add(extractText(column, ""));
+ }
+ return result;
+ }
+}
--- /dev/null
+/*
+ * Created on 8/04/2003
+ *
+ */
+package com.quantum.sql.metadata;
+
+import java.util.Vector;
+
+import com.quantum.util.StringMatrix;
+
+
+/**
+ * Class to hold the Metadata of a database element
+ * @author panic
+ */
+public class ObjectMetaData {
+ private StringMatrix columns = new StringMatrix();
+ private StringMatrix primaryKeys = new StringMatrix();
+ private StringMatrix foreignKeys = new StringMatrix();
+ private StringMatrix indexInfo = new StringMatrix();
+ private StringMatrix bestRowId = new StringMatrix();
+
+
+ /**
+ * Gives the order of the column in the primary key
+ * @param column
+ * @return the order of the column in the primary key, 0 if it's not part of it.
+ */
+ public int getPrimaryKeyOrder(String column){
+ if (primaryKeys.size() == 0) return 0;
+ StringMatrix keyColumns = primaryKeys.select("COLUMN_NAME", column); //$NON-NLS-1$
+ if (keyColumns != null && keyColumns.size() > 0) {
+ String index = keyColumns.get("KEY_SEQ", 0); // We suppose there is only a primary key //$NON-NLS-1$
+ if (index != null ) return Integer.parseInt(index);
+ }
+ return 0;
+ }
+
+ /**
+ * Gives the type of the column
+ * @param column
+ * @return the type of the column using the values defined in java.sql.Types
+ */
+ public int getColumnType(String column){
+ StringMatrix selectCol = columns.select("COLUMN_NAME", column); //$NON-NLS-1$
+ if (selectCol != null && selectCol.size() > 0) {
+ String type = selectCol.get("DATA_TYPE", 0); // It should be only one column //$NON-NLS-1$
+ if (type != null ) return Integer.parseInt(type);
+ }
+ return 0;
+
+ }
+
+ /**
+ * Returns a String with the names of the columns, separated by commas
+ */
+ public String getColumnsString() {
+ String result = ""; //$NON-NLS-1$
+ Vector columnNames = columns.getColumn("COLUMN_NAME"); //$NON-NLS-1$
+ for (int i = 0; i < columnNames.size(); i++) {
+ if (i > 0) result += ", "; //$NON-NLS-1$
+ result += (String) columnNames.get(i);
+ }
+ return result;
+ }
+
+ /**
+ * Returns a vector of Strings with the names of the columns
+ */
+ public Vector getColumnNamesVector() {
+ Vector result = new Vector();
+ Vector columnNames = columns.getColumn("COLUMN_NAME"); //$NON-NLS-1$
+ for (int i = 0; i < columnNames.size(); i++) {
+ result.add((String) columnNames.get(i));
+ }
+ return result;
+ }
+
+ // Inmediate getters and setters
+
+ /**
+ * @param matrix
+ */
+ public void setColumns(StringMatrix matrix) {
+ columns = matrix;
+ }
+ /**
+ * @param matrix
+ */
+ public void setForeignKeys(StringMatrix matrix) {
+ foreignKeys = matrix;
+ }
+
+ /**
+ * @param matrix
+ */
+ public void setPrimaryKeys(StringMatrix matrix) {
+ primaryKeys = matrix;
+ }
+ /**
+ * @param matrix
+ */
+ public void setBestRowId(StringMatrix matrix) {
+ bestRowId = matrix;
+ }
+
+ /**
+ * @param matrix
+ */
+ public void setIndexInfo(StringMatrix matrix) {
+ indexInfo = matrix;
+ }
+
+ /**
+ * @return
+ */
+ public StringMatrix getColumns() {
+ return columns;
+ }
+
+ /**
+ * @return
+ */
+ public StringMatrix getForeignKeys() {
+ return foreignKeys;
+ }
+
+ /**
+ * @return
+ */
+ public StringMatrix getPrimaryKeys() {
+ return primaryKeys;
+ }
+
+
+ /**
+ * @return
+ */
+ public StringMatrix getIndexInfo() {
+ return indexInfo;
+ }
+ /**
+ * @return
+ */
+ public StringMatrix getBestRowId() {
+ return bestRowId;
+ }
+
+
+ /**
+ * @param column
+ */
+ public void dropColumn(String columnName) {
+ columns.dropMatching("COLUMN_NAME", columnName); //$NON-NLS-1$
+ }
+
+ // Common Object interface
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#clone()
+ */
+ public Object clone() {
+ ObjectMetaData result = new ObjectMetaData();
+ result.columns = (StringMatrix) columns.clone();
+ result.primaryKeys = (StringMatrix) primaryKeys.clone();
+ result.indexInfo = (StringMatrix) indexInfo.clone();
+ result.foreignKeys = (StringMatrix) foreignKeys.clone();
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof ObjectMetaData)) return false;
+ ObjectMetaData obMd = (ObjectMetaData) obj;
+ return (columns.equals(obMd.columns) &&
+ primaryKeys.equals(obMd.primaryKeys) &&
+ indexInfo.equals(obMd.indexInfo) &&
+ foreignKeys.equals(obMd.foreignKeys) );
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return ( columns.toString() +
+ foreignKeys.toString() +
+ indexInfo.toString() +
+ primaryKeys.toString());
+ }
+
+ public String getQualifiedTableName(){
+ if (columns.size() < 1) return "";
+ String result = columns.get("TABLE_NAME", 0);
+ String schema = columns.get("TABLE_SCHEM", 0);
+ if (schema != null && schema.length() > 0)
+ result = schema + "." + result;
+ return result;
+
+ }
+
+
+}
--- /dev/null
+package com.quantum.sql.parser;
+
+import java.util.Vector;
+
+public class SQLLexx {
+ private static String endline = ";"; //$NON-NLS-1$
+ private static String dash = "-"; //$NON-NLS-1$
+ private static String group = "/"; //$NON-NLS-1$
+ /**
+ * Parses a SQL text into tokens.
+ * @param text
+ * @return a vector of Token objects.
+ */
+ public static Vector parse(String text) {
+ Vector tokens = new Vector();
+ StringPointer p = new StringPointer(text);
+ try {
+ while (!p.isDone()) {
+ int offset = p.getOffset();
+ char c = p.getNext();
+ // Adds END_OF_LINE token
+ if (c == '\n') {
+ tokens.addElement(new Token(Token.END_OF_LINE, "\n", offset, offset + 1));
+ }
+ // Adds WHITESPACE token;
+ else if (Character.isWhitespace(c)) {
+ StringBuffer value = new StringBuffer();
+ while (Character.isWhitespace(c) && !p.isDone()) {
+ value.append(c);
+ c = p.getNext();
+ }
+ // done because of is done
+ if (Character.isWhitespace(c)) {
+ value.append(c);
+ } else if (!p.isDone()){
+ p.back();
+ }
+ tokens.addElement(new Token(Token.WHITESPACE, value.toString(), offset, offset + value.length()));
+ // Adds IDENTIFIER token (can be reserved SQL word or not);
+ } else if (Character.isLetter(c) || c == '_' || c == '$') {
+ StringBuffer value = new StringBuffer();
+ while ((Character.isLetterOrDigit(c) || c == '_' || c == '$') && !p.isDone()) {
+ value.append(c);
+ c = p.getNext();
+ }
+ if ((Character.isLetterOrDigit(c) || c == '_')) {
+ value.append(c);
+ } else if (!p.isDone()){
+ p.back();
+ }
+ tokens.addElement(new Token(Token.IDENTIFIER, value.toString(), offset, offset + value.length()));
+ // Adds LITERAL token;
+ } else if (c == '\'') {
+ StringBuffer value = new StringBuffer();
+ value.append(c);
+ if (!p.isDone()) {
+ c = p.getNext();
+ while (c != '\'' && c != '\n' && !p.isDone()) {
+ value.append(c);
+ c = p.getNext();
+ }
+ if (c == '\'' || p.isDone()) {
+ value.append(c);
+ } else if (!p.isDone()){
+ p.back();
+ }
+ }
+ tokens.addElement(new Token(Token.LITERAL, value.toString(), offset, offset + value.length()));
+ // Adds COMMENT token (or SYMBOL (dash) if only one dash);
+ } else if (c == '-') {
+ p.mark();
+ if (p.isDone()) {
+ tokens.addElement(new Token(Token.SYMBOL, dash, offset, offset + 1));
+ } else {
+ char next = p.getNext();
+ if (next == '-') {
+ StringBuffer value = new StringBuffer("--"); //$NON-NLS-1$
+ if (!p.isDone()) {
+ c = p.getNext();
+ while (c != '\n' && !p.isDone()) {
+ value.append(c);
+ c = p.getNext();
+ }
+ if (p.isDone()) {
+ value.append(c);
+ } else {
+ p.back();
+ }
+ }
+ tokens.addElement(new Token(Token.COMMENT, value.toString(), offset, offset + value.length()));
+ } else {
+ tokens.addElement(new Token(Token.SYMBOL, dash, offset, offset + 1));
+ p.reset();
+ }
+ }
+ // Adds SEPARATOR token (;), considers the rest of the line as COMMENT token;
+ } else if (c == ';') {
+ tokens.addElement(new Token(Token.SEPARATOR, endline, offset, offset + 1));
+ StringBuffer value = new StringBuffer();
+ if (!p.isDone()) {
+ c = p.getNext();
+ while (c != '\n' && !p.isDone()) {
+ value.append(c);
+ c = p.getNext();
+ }
+ if (p.isDone()) {
+ value.append(c);
+ } else {
+ p.back();
+ }
+ // We add to the offset so as to skip the initial ';'
+ offset++;
+ tokens.addElement(new Token(Token.COMMENT, value.toString(), offset, offset + value.length()));
+ }
+ // Adds NUMERIC token;
+ } else if (Character.isDigit(c)) {
+ StringBuffer value = new StringBuffer();
+ while ((Character.isDigit(c) || c == '.') && !p.isDone()) {
+ value.append(c);
+ c = p.getNext();
+ }
+ if ((Character.isDigit(c) || c == '.')) {
+ value.append(c);
+ } else {
+ p.back();
+ }
+ tokens.addElement(new Token(Token.NUMERIC, value.toString(), offset, offset + value.length()));
+ // Adds COMMENT token (or GROUP (slash) if only one slash);
+ } else if (c == '/') {
+ p.mark();
+ // If we have '/*', it's a comment till '*/' found or eof
+ if (p.peek() == '*') {
+ StringBuffer value = new StringBuffer();
+ c = p.getNext();
+ value.append('/');
+ while (!( c == '*' && p.peek() == '/' ) && !p.isDone()) {
+ value.append(c);
+ c = p.getNext();
+ }
+ if (!p.isDone()){
+ value.append(c);
+ c = p.getNext();
+ value.append(c);
+ }
+ tokens.addElement(new Token(Token.COMMENT, value.toString(), offset, offset + value.length()));
+ } else {
+ // It's not '/*' , so it's a group token
+ tokens.addElement(new Token(Token.GROUP, group, offset, offset + 1));
+ p.reset();
+ }
+ // Adds SYMBOL token;
+ } else {
+ tokens.addElement(new Token(Token.SYMBOL, new String(new char[] {c}), offset, offset + 1));
+ }
+ }
+ } catch (RuntimeException e) {
+ e.printStackTrace();
+ }
+
+// System.out.println("-------------------");
+// for (int i = 0; i < tokens.size(); i++) {
+// System.out.println((Token) tokens.elementAt(i));
+// }
+ return tokens;
+ }
+}
--- /dev/null
+package com.quantum.sql.parser;
+
+public class StringPointer {
+ char[] value;
+ int offset = 0;
+ int mark = 0;
+ public StringPointer(String s) {
+ value = s.toCharArray();
+ }
+ /**
+ * Returns the next character. Will return 0 if at end of file, but that's not
+ * checkeable because it can be a valid character. You should check with isDone();
+ * @return
+ */
+ public char getNext() {
+ char retVal = (offset < value.length) ? value[offset] : 0;
+ offset++;
+ return retVal;
+ }
+ /**
+ * Returns the next character, without advancing the pointer.
+ * Will return 0 if at end of file, but that's not
+ * checkeable because it can be a valid character. You should check with isDone();
+ * @return
+ */
+ public char peek() {
+ char retVal = (offset < value.length) ? value[offset] : 0;
+ return retVal;
+ }
+ /**
+ * Marks a poing of the stream to come back later (using reset());
+ */
+ public void mark() {
+ mark = offset;
+ }
+ /**
+ * Returns to a previously marked (with mark()) place.
+ */
+ public void reset() {
+ offset = mark;
+ }
+ /**
+ * Sets the pointer back a character, in fact 'pop'ing it back to the stream;
+ */
+ public void back() {
+ if (offset > 0) offset--;
+ }
+
+ public int getOffset() {
+ return offset;
+ }
+ /**
+ * @return true if the stream is at an end
+ */
+ public boolean isDone() {
+ return offset >= value.length;
+ }
+
+ public int getLength() {
+ return value.length;
+ }
+}
--- /dev/null
+package com.quantum.sql.parser;
+
+public class Token {
+ public static final char SEPARATOR = 'S';
+ public static final char SYMBOL = 'Y';
+ public static final char LITERAL = 'L';
+ public static final char IDENTIFIER = 'I';
+ public static final char COMMENT = 'C';
+ public static final char WHITESPACE = 'W';
+ public static final char NUMERIC = 'N';
+ public static final char GROUP = 'G';
+ public static final char END_OF_LINE = 'E';
+ private char type;
+ private int start;
+ private int end;
+ private String value;
+ public Token(char type, String value, int start, int end) {
+ this.type = type;
+ this.value = value;
+ this.start = start;
+ this.end = end;
+ }
+ public int getEnd() {
+ return end;
+ }
+
+ public int getStart() {
+ return start;
+ }
+
+ public int getType() {
+ return type;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setEnd(int end) {
+ this.end = end;
+ }
+
+ public void setStart(int start) {
+ this.start = start;
+ }
+
+ public void setType(char type) {
+ this.type = type;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+ public String toString() {
+ return type + " ->" + value + "<- [" + start + ", " + end + "]"; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+}
--- /dev/null
+package com.quantum.ui.dialog;
+
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+
+import com.quantum.Messages;
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkCollection;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * @author BC
+ */
+public class BookmarkSelectionDialog extends Dialog {
+
+ private List list;
+ private String selection = null;
+ private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
+
+ /**
+ * @param parentShell
+ */
+ public BookmarkSelectionDialog(Shell parentShell) {
+ super(parentShell);
+ int style = getShellStyle() | SWT.TITLE;
+ setShellStyle(style);
+ }
+
+ protected void configureShell(Shell shell) {
+ super.configureShell(shell);
+ shell.setText(Messages.getString("BookmarkSelectionDialog.title"));
+ }
+
+ /**
+ * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
+ */
+ protected Control createDialogArea(Composite parent) {
+
+ Composite composite = new Composite(parent, 0);
+ GridLayout layout = new GridLayout();
+ composite.setLayout(layout);
+ layout.numColumns = 1;
+ layout.verticalSpacing = 1;
+
+ Label label = new Label(composite, SWT.NULL);
+ label.setText(Messages.getString("BookmarkSelectionDialog.text"));
+
+ this.list = new List(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
+ Bookmark[] bookmarks = BookmarkCollection.getInstance().getBookmarks();
+
+ for (int i = 0, length = (bookmarks == null) ? 0 : bookmarks.length; i < length; i++) {
+ this.list.add(bookmarks[i].getName());
+ if (i == 0) {
+ this.list.select(i);
+ setSelection(bookmarks[i].getName());
+ }
+ }
+
+ final List list = this.list;
+ list.addListener(SWT.Selection, new Listener() {
+ public void handleEvent (Event event) {
+ String[] selections = list.getSelection();
+ if (selections != null && selections.length > 0) {
+ BookmarkSelectionDialog.this.setSelection(selections[0]);
+ }
+ }
+ });
+
+ GridData full = new GridData();
+ full.horizontalAlignment = GridData.FILL;
+ full.verticalAlignment = GridData.FILL;
+ full.heightHint = convertHeightInCharsToPixels(3);
+ this.list.setLayoutData(full);
+
+ return composite;
+ }
+
+ /**
+ * @param listener
+ */
+ public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
+ this.propertyChangeSupport.addPropertyChangeListener(listener);
+ }
+
+ /**
+ * @param listener
+ */
+ public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
+ this.propertyChangeSupport.removePropertyChangeListener(listener);
+ }
+
+ private void setSelection(String selection) {
+ String original = this.selection;
+ if (this.selection == null || !this.selection.equals(selection)) {
+ this.selection = selection;
+ this.propertyChangeSupport.firePropertyChange("selection", original, this.selection);
+ }
+ }
+}
--- /dev/null
+package com.quantum.ui.dialog;
+
+import com.quantum.Messages;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * @author BC
+ */
+public class ExceptionDisplayDialog extends Dialog {
+
+ private Control detailsArea;
+ private Throwable throwable;
+ private String message;
+
+ /**
+ * @param parentShell
+ */
+ public ExceptionDisplayDialog(Shell parentShell, Throwable throwable) {
+ super(parentShell);
+ this.throwable = throwable;
+ }
+
+ /**
+ * The Details button.
+ */
+ private Button detailsButton;
+
+ /**
+ * The title of the dialog.
+ */
+ private String title;
+
+ /**
+ * Indicates whether the error details viewer is currently created.
+ */
+ private boolean detailsShown = false;
+
+ /**
+ * Creates an error dialog.
+ * Note that the dialog will have no visual representation (no widgets)
+ * until it is told to open.
+ * <p>
+ * Normally one should use <code>openError</code> to create and open one of these.
+ * This constructor is useful only if the error object being displayed contains child
+ * items <it>and</it> you need to specify a mask which will be used to filter the
+ * displaying of these children.
+ * </p>
+ *
+ * @param parentShell the shell under which to create this dialog
+ * @param dialogTitle the title to use for this dialog,
+ * or <code>null</code> to indicate that the default title should be used
+ * @param message the message to show in this dialog,
+ * or <code>null</code> to indicate that the error's message should be shown
+ * as the primary message
+ * @param status the error to show to the user
+ * @param displayMask the mask to use to filter the displaying of child items,
+ * as per <code>IStatus.matches</code>
+ * @see org.eclipse.core.runtime.IStatus#matches(int)
+ */
+ public ExceptionDisplayDialog(
+ Shell parentShell,
+ String dialogTitle,
+ String message,
+ Throwable throwable) {
+ super(parentShell);
+
+ this.title = dialogTitle;
+ this.message = message;
+ this.throwable = throwable;
+
+ setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.APPLICATION_MODAL);
+ }
+
+ /* (non-Javadoc)
+ * Method declared on Dialog.
+ * Handles the pressing of the Ok or Details button in this dialog.
+ * If the Ok button was pressed then close this dialog. If the Details
+ * button was pressed then toggle the displaying of the error details area.
+ * Note that the Details button will only be visible if the error being
+ * displayed specifies child details.
+ */
+ protected void buttonPressed(int id) {
+ if (id == IDialogConstants.DETAILS_ID) {
+ // was the details button pressed?
+ toggleDetailsArea();
+ } else {
+ super.buttonPressed(id);
+ }
+ }
+ /* (non-Javadoc)
+ * Method declared in Window.
+ */
+ protected void configureShell(Shell shell) {
+ super.configureShell(shell);
+ shell.setText(title);
+ }
+ /* (non-Javadoc)
+ * Method declared on Dialog.
+ */
+ protected void createButtonsForButtonBar(Composite parent) {
+ // create OK and Details buttons
+ createButton(
+ parent,
+ IDialogConstants.OK_ID,
+ IDialogConstants.OK_LABEL,
+ true);
+ this.detailsButton =
+ createButton(
+ parent,
+ IDialogConstants.DETAILS_ID,
+ IDialogConstants.SHOW_DETAILS_LABEL,
+ false);
+ }
+
+ protected Control createDialogArea(Composite parent) {
+
+ // create a composite with standard margins and spacing
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.marginHeight =
+ convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
+ layout.marginWidth =
+ convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
+ layout.verticalSpacing =
+ convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
+ layout.horizontalSpacing =
+ convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
+ composite.setLayout(layout);
+ GridData childData = new GridData(GridData.FILL_BOTH);
+ childData.horizontalSpan = 2;
+ composite.setLayoutData(childData);
+ composite.setFont(parent.getFont());
+
+ Label label = new Label(composite, 0);
+ label.setText(this.message);
+ label.setFont(parent.getFont());
+
+
+ GridData full = new GridData();
+ full.horizontalAlignment = GridData.FILL;
+ full.verticalAlignment = GridData.FILL;
+ full.heightHint = convertHeightInCharsToPixels(3);
+ full.widthHint = convertWidthInCharsToPixels(60);
+ label.setLayoutData(full);
+
+ return composite;
+
+ }
+
+ /**
+ * Create the expandable details arae.
+ *
+ * @param parent the parent composite
+ * @return the details text control
+ */
+ protected Control createDetailsArea(Composite parent) {
+
+ // create a composite with standard margins and spacing
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.marginHeight =
+ convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
+ layout.marginWidth =
+ convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
+ layout.verticalSpacing =
+ convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
+ layout.horizontalSpacing =
+ convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
+ composite.setLayout(layout);
+ GridData childData = new GridData(GridData.FILL_BOTH);
+ childData.horizontalSpan = 2;
+ composite.setLayoutData(childData);
+ composite.setFont(parent.getFont());
+
+ Label label = new Label(composite, 0);
+ label.setText(Messages.getString("ExceptionDisplayDialog.stackTrace"));
+ label.setFont(parent.getFont());
+
+ GridData full = new GridData();
+ full.horizontalAlignment = GridData.FILL;
+ full.verticalAlignment = GridData.FILL;
+ full.heightHint = convertHeightInCharsToPixels(3);
+ full.widthHint = convertWidthInCharsToPixels(60);
+ label.setLayoutData(full);
+
+ Text text =
+ new Text(
+ composite,
+ SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
+
+ text.setText(this.throwable.getMessage());
+
+ GridData data =
+ new GridData(
+ GridData.HORIZONTAL_ALIGN_FILL
+ | GridData.GRAB_HORIZONTAL
+ | GridData.VERTICAL_ALIGN_FILL
+ | GridData.GRAB_VERTICAL);
+ data.heightHint = convertHeightInCharsToPixels(8);
+ text.setLayoutData(data);
+ text.setFont(parent.getFont());
+
+ this.detailsShown = true;
+ return composite;
+ }
+ /**
+ * Opens an error dialog to display the given error. Use this method if the
+ * error object being displayed contains child items <it>and</it> you wish to
+ * specify a mask which will be used to filter the displaying of these
+ * children. The error dialog will only be displayed if there is at
+ * least one child status matching the mask.
+ *
+ * @param parentShell -
+ * the parent shell of the dialog, or <code>null</code> if none
+ * @param dialogTitle the title to use for this dialog,
+ * or <code>null</code> to indicate that the default title should be used
+ * @param message the message to show in this dialog,
+ * or <code>null</code> to indicate that the error's message should be shown
+ * as the primary message
+ * as per <code>IStatus.matches</code>
+ * @return the code of the button that was pressed that resulted in this dialog
+ * closing. This will be <code>Dialog.OK</code> if the OK button was
+ * pressed, or <code>Dialog.CANCEL</code> if this dialog's close window
+ * decoration or the ESC key was used.
+ * @see org.eclipse.core.runtime.IStatus#matches(int)
+ */
+ public static int openError(
+ Shell parentShell,
+ String title,
+ String message,
+ Throwable throwable) {
+
+ if (title == null) {
+ title = Messages.getString(ExceptionDisplayDialog.class.getName() +
+ "." + throwable.getClass().getName() + ".title");
+ }
+ if (message == null) {
+ message = Messages.getString(ExceptionDisplayDialog.class.getName() +
+ "." + throwable.getClass().getName() + ".message");
+ }
+ ExceptionDisplayDialog dialog =
+ new ExceptionDisplayDialog(parentShell, title, message, throwable);
+ return dialog.open();
+ }
+
+ /**
+ * Toggles the unfolding of the details area. This is triggered by
+ * the user pressing the details button.
+ */
+ private void toggleDetailsArea() {
+ Point windowSize = getShell().getSize();
+ Point oldSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
+
+ if (this.detailsShown) {
+ this.detailsArea.dispose();
+ this.detailsShown = false;
+ detailsButton.setText(IDialogConstants.SHOW_DETAILS_LABEL);
+ } else {
+ this.detailsArea = createDetailsArea((Composite) getContents());
+ detailsButton.setText(IDialogConstants.HIDE_DETAILS_LABEL);
+ }
+
+ Point newSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
+
+ getShell().setSize(
+ new Point(windowSize.x, windowSize.y + (newSize.y - oldSize.y)));
+
+ }
+}
--- /dev/null
+/*
+ * Created on 28-ago-2003
+ *
+ */
+package com.quantum.ui.dialog;
+
+import com.quantum.Messages;
+import com.quantum.model.PasswordFinder;
+
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * @author panic
+ *
+ */
+public class PasswordDialog extends InputDialog {
+
+ static class PasswordFinderImpl implements PasswordFinder {
+ private boolean passwordMeantToBeSaved = false;
+ private String password;
+ private boolean prompted = false;
+ private Shell shell;
+
+ PasswordFinderImpl(Shell shell) {
+ this.shell = shell;
+ }
+
+ protected void prompt() {
+ PasswordDialog dialog =
+ new PasswordDialog(
+ this.shell,
+ Messages.getString("MultiSQLServer.PasswordNotProvided"),
+ Messages.getString("MultiSQLServer.Enter_Password"),
+ "",
+ this);
+ dialog.open();
+ this.prompted = true;
+ }
+
+ /**
+ * @return
+ */
+ public String getPassword() {
+ if (!this.prompted) {
+ prompt();
+ }
+ return password;
+ }
+
+ /**
+ * @return
+ */
+ public boolean isPasswordMeantToBeSaved() {
+ if (!this.prompted) {
+ prompt();
+ }
+ return passwordMeantToBeSaved;
+ }
+
+ /**
+ * @param string
+ */
+ public void setPassword(String string) {
+ password = string;
+ }
+
+ /**
+ * @param b
+ */
+ public void setPasswordMeantToBeSaved(boolean b) {
+ passwordMeantToBeSaved = b;
+ }
+
+ }
+
+ private PasswordFinderImpl passwordFinderImpl;
+
+ /**
+ * @param parentShell
+ * @param dialogTitle
+ * @param dialogMessage
+ * @param initialValue
+ * @param validator
+ */
+ protected PasswordDialog(
+ Shell parentShell,
+ String dialogTitle,
+ String dialogMessage,
+ String initialValue,
+ PasswordFinderImpl passwordFinderImpl) {
+ super(parentShell, dialogTitle, dialogMessage, initialValue, null);
+ this.passwordFinderImpl = passwordFinderImpl;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
+ */
+ protected Control createDialogArea(Composite parent) {
+
+ Control control = super.createDialogArea(parent);
+ Text text = getText();
+ text.setEchoChar('*');
+ return control;
+ }
+
+ public static PasswordFinder createPasswordFinder(Shell parentShell) {
+ PasswordFinderImpl passwordFinder = new PasswordFinderImpl(parentShell);
+ return passwordFinder;
+ }
+ /**
+ * @see org.eclipse.jface.dialogs.Dialog#okPressed()
+ */
+ protected void okPressed() {
+ this.passwordFinderImpl.setPassword(getText().getText());
+ super.okPressed();
+ }
+
+}
--- /dev/null
+/*
+ * Created on 11/08/2003
+ *
+ */
+package com.quantum.util;
+
+import java.util.Iterator;
+import java.util.Vector;
+
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+
+/**
+ * Class to clasify two levels of strings. It's called Nth Level but in fact it has only two levels :o)
+ * @author panic
+ *
+ */
+public class NthLevelConverter {
+ private final int DEFAULT_COLUMNS = 10;
+ private final int DEFAULT_INCREMENT = 10;
+
+ private Vector upper = new Vector(DEFAULT_COLUMNS,DEFAULT_INCREMENT);
+
+ public void add(String id, String parentId, int level) {
+ OneLevelConverter upperLine = new OneLevelConverter(id);
+ if (level == 1) { // If it's an upper leaf
+ if (!upper.contains(upperLine))
+ this.upper.add(upperLine);
+ }
+ else if (level == 0) { // It's a lower leaf
+ if (parentId == null) return; // No parent, what shall we do.
+ OneLevelConverter upperFinder = new OneLevelConverter(parentId);
+ // Search if its parent is already present in the upper level
+ int ind = upper.indexOf(upperFinder);
+ // If not, addIt and find its index
+ if (ind < 0) {
+ this.upper.add(upperFinder);
+ ind = upper.indexOf(upperFinder);
+ }
+ OneLevelConverter upperItem = (OneLevelConverter) upper.get(ind);
+ // If it has no children, we create a new Vector for the children
+ if (upperItem.getLower() == null)
+ upperItem.setLower(new Vector(DEFAULT_COLUMNS,DEFAULT_INCREMENT));
+ Vector children = upperItem.getLower();
+ // Is the item already present in the children of its parent?
+ int indChildren = children.indexOf(id);
+ // If it's not, we add it
+ if (indChildren < 0) {
+ OneLevelConverter leaf = new OneLevelConverter(id);
+ children.add(leaf);
+ }
+ }
+
+ }
+
+
+ /**
+ * @return
+ */
+ public Vector getUpper() {
+ return upper;
+ }
+
+ public Vector getLevel(String id, int level){
+ if (level == 1)
+ return upper;
+ else if (level == 0){
+ if (id == null) return null;
+ OneLevelConverter upperFinder = new OneLevelConverter(id);
+ int ind = upper.indexOf(upperFinder);
+ if (ind < 0)
+ return null;
+ else {
+ OneLevelConverter upperItem = (OneLevelConverter) upper.get(ind);
+ return upperItem.getLower();
+ }
+ }
+ return null;
+ }
+
+ public void convert(String ind){
+ IPreferenceStore store = QuantumPlugin.getDefault().getPreferenceStore();
+
+ String tableItem = QuantumUtil.trasposeEscape(store.getString("customCopyTableItem" + ind));
+ String tableSeparator = QuantumUtil.trasposeEscape(store.getString("customCopyTableSeparator" + ind));
+ String columnItem = QuantumUtil.trasposeEscape(store.getString("customCopyColumnItem" + ind));
+ String columnSeparator = QuantumUtil.trasposeEscape(store.getString("customCopyColumnSeparator" + ind));
+
+ for (Iterator iter = upper.iterator(); iter.hasNext();) {
+ OneLevelConverter oneLevel = (OneLevelConverter) iter.next();
+ String upperId = oneLevel.getId();
+ Vector lower = oneLevel.getLower();
+ if (lower != null) {
+ for (Iterator iterator = lower.iterator(); iterator.hasNext();) {
+ OneLevelConverter element = (OneLevelConverter) iterator.next();
+ String convLeaf = columnItem + (iterator.hasNext() ? columnSeparator : "");
+
+ convLeaf = StringUtil.substituteString(convLeaf, "${schema}", QuantumUtil.getSchemaName(upperId));
+ convLeaf = StringUtil.substituteString(convLeaf, "${qualified}", upperId);
+ convLeaf = StringUtil.substituteString(convLeaf, "${table}", QuantumUtil.getTableName(upperId));
+ convLeaf = StringUtil.substituteString(convLeaf, "${column}", element.getId());
+
+ element.setResult(convLeaf);
+ }
+ }
+ // We have all the leafs converted, we calculate the parent conversion
+ String convUpper = tableItem + (iter.hasNext() ? tableSeparator : "");
+ convUpper = StringUtil.substituteString(convUpper, "${schema}", QuantumUtil.getSchemaName(upperId));
+ convUpper = StringUtil.substituteString(convUpper, "${qualified}", upperId);
+ convUpper = StringUtil.substituteString(convUpper, "${table}", QuantumUtil.getTableName(upperId));
+ convUpper = StringUtil.substituteString(convUpper, "${column_list}", getColumnList(oneLevel));
+
+ oneLevel.setResult(convUpper);
+ }
+ }
+
+
+ /**
+ * Calculates the list of columns for an upper level converter. Has to be already converted.
+ * @param oneLevel
+ * @return
+ */
+ private String getColumnList(OneLevelConverter oneLevel) {
+
+ String result = "";
+ Vector lower = oneLevel.getLower();
+ if (lower != null) {
+ for (Iterator iterator = lower.iterator(); iterator.hasNext();) {
+ OneLevelConverter element = (OneLevelConverter) iterator.next();
+ result += element.getResult();
+ }
+ }
+ return result;
+ }
+
+ public String getTableList() {
+ String result = "";
+ for (Iterator iter = upper.iterator(); iter.hasNext();) {
+ OneLevelConverter oneLevel = (OneLevelConverter) iter.next();
+ result += oneLevel.getResult();
+ }
+ return result;
+ }
+}
--- /dev/null
+/*
+ * Created on 11/08/2003
+ *
+ */
+package com.quantum.util;
+
+import java.util.Vector;
+
+/**
+ * "record" class that holds an identifier and the resulting
+ * string. This string comes from applying rules to the identifier
+ * Also, can have a vector of lower-level classifiers.
+ *
+ * @author panic
+ *
+ */
+public class OneLevelConverter {
+ private String id = "";
+ private String result = "";
+ private Vector lower = null;
+
+ OneLevelConverter(String id) {
+ this.id = id;
+ }
+
+ // Getters and setters
+ /**
+ * @return
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * @return
+ */
+ public Vector getLower() {
+ return lower;
+ }
+
+ /**
+ * @return
+ */
+ public String getResult() {
+ return result;
+ }
+
+ /**
+ * @param string
+ */
+ public void setId(String string) {
+ id = string;
+ }
+
+ /**
+ * @param vector
+ */
+ public void setLower(Vector vector) {
+ lower = vector;
+ }
+
+ /**
+ * @param string
+ */
+ public void setResult(String string) {
+ result = string;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof OneLevelConverter)) return false;
+ return this.id.equals(((OneLevelConverter)obj).id);
+ }
+
+}
--- /dev/null
+/*
+ * Created on 24/08/2003
+ *
+ */
+package com.quantum.util;
+
+import java.util.StringTokenizer;
+
+/**
+ * @author panic
+ *
+ */
+public class QuantumUtil {
+ /**
+ * Gets the first string in a string with the structure XXXX.XXXX
+ * @param qualifiedName
+ * @return The schema name if present, else an empty string ("")
+ */
+ public static String getSchemaName(String qualifiedName) {
+ StringTokenizer st = new StringTokenizer(qualifiedName, "."); //$NON-NLS-1$
+ if (st.countTokens() > 1) {
+ return st.nextToken();
+ } else
+ return "";
+ }
+
+ /**
+ * Gets the second string in a string with the structure XXXX.XXXX
+ * @param qualifiedName
+ * @return The table name if present, else the received parameter
+ */
+ public static String getTableName(String qualifiedName) {
+ StringTokenizer st = new StringTokenizer(qualifiedName, "."); //$NON-NLS-1$
+ if (st.countTokens() > 1) {
+ st.nextToken();
+ return st.nextToken();
+ } else
+ return qualifiedName;
+ }
+
+ public static String trasposeEscape(String untrans){
+ String trasposed = StringUtil.substituteString(untrans, "\\n", "\n");
+ trasposed = StringUtil.substituteString(trasposed, "\\t", "\t");
+
+ return trasposed;
+ }
+}
--- /dev/null
+/*
+ * Created on 8/04/2003
+ *
+ */
+package com.quantum.util;
+
+import java.util.Vector;
+
+/**
+ * @author jparrai
+ * Generic class to hold a Matrix of Strings, that is a Vector of Vectors of Strings.
+ * The first Vector "line" is supposed to have headers to the values of the rest.
+ * Those headers will always be case insensitive
+ */
+public class StringMatrix {
+ private final int DEFAULT_COLUMNS = 10;
+ private final int DEFAULT_ROWS = 10;
+ private final int DEFAULT_INCREMENT = 10;
+
+ private Vector header = new Vector(DEFAULT_COLUMNS,DEFAULT_INCREMENT);
+ private Vector matrix = new Vector(DEFAULT_ROWS,DEFAULT_INCREMENT);
+
+ /**
+ * Adds a String to the end of the header keys
+ * @param header : The string to be added
+ */
+ public void addHeader(String header) {
+ this.header.add(header);
+ }
+ /**
+ * Adds a whole vector to the header
+ * @param header
+ */
+ private void addVectorHeader(Vector header){
+ this.header.addAll(header);
+ for (int i = 0; i < this.header.size(); i++) {
+ String element = (String) this.header.get(i);
+ this.header.setElementAt(element, i);
+ }
+ }
+ /**
+ * Adds a whole matrix to the header
+ * @param header
+ */
+ public void addMatrixHeader(String header[]){
+ for (int i = 0; i < header.length; i++) {
+ String element = (String) header[i];
+ this.header.add(element);
+ }
+ }
+ /**
+ * Adds a String to the end of the row indicated
+ * @param value : The string to be added
+ * @param row : The row to
+ */
+ public void add(String value, int row) {
+ grow(row);
+ Vector rowVector = (Vector) matrix.get(row);
+ rowVector.add(value);
+ }
+ /**
+ * Adds a StringMatrix to the end of the row indicated
+ * @param value : The string to be added
+ * @param row : The row to
+ */
+ public void add(StringMatrix value) {
+ int row = matrix.size();
+ for (int i = 0; i < value.size(); i++){
+ grow(row);
+ for (int j = 0; j < value.getNumColumns(); j++){
+ String header = value.getHeaderColumn(j);
+ addAt(header, value.get(header,i), row);
+ }
+ row++;
+ }
+ Vector rowVector = (Vector) matrix.get(row);
+ rowVector.add(value);
+ }
+
+ /**
+ * Converts the StringMatrix into a copy of the given
+ * @param origin - The StringMatrix to be copied
+ */
+ public void copy(StringMatrix origin) {
+ clear();
+ add(origin);
+ }
+
+ /**
+ * Clears (emtpies) the StringMatrix
+ */
+ public void clear(){
+ header.clear();
+ matrix.clear();
+ }
+ /**
+ * Adds a String to the row indicated, to the column that matches the key
+ * @param value : The string to be added
+ * @param row : The row to
+ */
+ public void addAt(String key, String value, int row) {
+ grow(row);
+ Vector rowVector = (Vector) matrix.get(row);
+ int ind = header.indexOf(key);
+ if (ind < 0) return;
+ if (rowVector.size() < ind+1) rowVector.setSize(ind);
+ rowVector.add(ind, value);
+ }
+ /**
+ * Adds a whole vector to the end of the row indicated
+ * @param value : The vector to be added
+ * @param row : The row to
+ */
+ private void addVector(Vector value, int row){
+ grow(row);
+ Vector rowVector = (Vector) matrix.get(row);
+ rowVector.addAll(value);
+ }
+
+ /**
+ * Tells if you have that particular key in your StringMatrix
+ * @param key
+ * @return
+ */
+ public boolean contains(String key){
+ return (findKey(key) >= 0);
+ }
+ /**
+ * Gets a String value from the row indicated, from the column that matches the key
+ * @param key
+ * @param row
+ * @return
+ */
+ public String get(String key, int row){
+ if (matrix.size() <= row) return null;
+ int col = findKey(key);
+ if (col < 0) return null;
+ Vector rowVector = (Vector) matrix.get(row);
+ if (rowVector == null) return null;
+ return (String) rowVector.get(col);
+ }
+ /**
+ * Finds the key in the header
+ * @param key
+ * @return
+ */
+ private int findKey(String key) {
+ for (int i = 0; i < header.size(); i++) {
+ String element = (String) header.get(i);
+ if (element.equalsIgnoreCase(key)) return i;
+ }
+ return -1;
+ }
+ /**
+ * @param key: selects the column
+ * @return a Vector with all the values in the selected column; null if empty
+ */
+ public Vector getColumn(String key){
+ if (size() < 1 ) return null;
+ Vector result = new Vector(size(),1);
+ for (int i = 0; i < size(); i++){
+ result.add(get(key, i));
+ }
+ return result;
+ }
+ /**
+ * @param key: selects the column
+ * @return a Vector with all the values in the selected column, dropping duplicates; null if empty
+ */
+ public Vector getUniqueColumn(String key){
+ if (size() < 1 ) return null;
+ Vector result = new Vector(size(),1);
+ for (int i = 0; i < size(); i++){
+ if (!result.contains(get(key, i))) result.add(get(key, i));
+ }
+ return result;
+ }
+ /**
+ * @param key: selects the column
+ * @return a Vector of Integers with all the indexes of the rows
+ * matching the selected column, dropping duplicates; null if empty
+ */
+ public Vector getIndexes(String key, String value){
+ Vector result = new Vector();
+ for (int i = 0; i < size(); i++){
+ if (get(key, i).equals(value))
+ result.add(new Integer(i));
+ }
+ return result;
+ }
+ /**
+ * Deletes all the rows that matches the value for the key
+ * @param key: selects the column
+ */
+ public void dropMatching(String key, String value){
+ for (int i = 0; i < size(); i++){
+ if (get(key, i).equals(value)) deleteRow(i);
+ }
+ }
+ /**
+ * Returns a StringMatrix with all the complete rows that match the key - value pair
+ * @param key The column key
+ * @param value The value to match
+ * @return a StringMatrix with only the rows where the key equals the value
+ */
+ public StringMatrix select(String key, String value){
+ StringMatrix result = new StringMatrix();
+ result.addVectorHeader(header);
+ int j = 0;
+ for (int i = 0; i < size(); i++){
+ if (get(key, i).equals(value)) {
+ result.addVector((Vector)matrix.get(i), j);
+ j++;
+ }
+ }
+ return result;
+ }
+
+ // Private functions
+ /**
+ * Grows the StringMatrix till it's able to hold "row" rows.
+ * @param row : The number of rows that must hold
+ */
+ private void grow(int row) {
+ if (matrix.size() <= row)
+ for (int i = matrix.size(); i <= row; i++) {
+ matrix.add(new Vector(header.size(), 1));
+ }
+ }
+ /**
+ * Gets a String value from the row indicated , from the column number
+ * @param col : 0-index column
+ * @param row : 0-index column
+ * @return
+ */
+ private String get(int col, int row){
+ if (col < 0 || row < 0) return null;
+ Vector rowVector = (Vector) matrix.get(row);
+ if (rowVector == null) return null;
+ return (String) rowVector.get(col);
+ }
+
+ // Generic interfaces
+ /**
+ * @param i
+ * @return : a StringMatrix with only one row, the selected by i
+ */
+ public StringMatrix rowMatrix(int i){
+ StringMatrix result = new StringMatrix();
+ result.addVectorHeader(header);
+ result.addVector((Vector)matrix.get(i),0);
+ return result;
+ }
+
+ /**
+ * Resturns a String[] with the selected row
+ * @param i The index of the row
+ * @return
+ */
+ public String[] getRow(int i) {
+ if (i < matrix.size()) {
+ String[] result = new String[header.size()];
+ Vector resVector = (Vector)matrix.get(i);
+ resVector.toArray(result);
+ return result;
+ }
+ return null;
+
+ }
+
+
+ /**
+ * @return the number of rows
+ */
+ public int size() {
+ return matrix.size();
+ }
+ public int getNumColumns() {
+ return header.size();
+ }
+ public String getHeaderColumn(int i){
+ return (String) header.get(i);
+ }
+ public void deleteRow(int i){
+ matrix.remove(i);
+ }
+
+
+ // Common Object interface
+ /* (non-Javadoc)
+ * @see java.lang.Object#clone()
+ */
+ public Object clone() {
+ // Deep clone
+ StringMatrix matrix = new StringMatrix();
+ matrix.copy(this);
+ return matrix;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ String result = "";
+ for (int j = 0; j < header.size(); j++){
+ result += (String) header.get(j);
+ result += "\t";
+ }
+ result += "\n";
+ // Write the lines
+ for (int i = 0; i < matrix.size(); i++){
+ for (int j = 0; j < header.size(); j++){
+ result += get(j,i);
+ result += "\t";
+ }
+ result += "\n";
+ }
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof StringMatrix)) return false;
+ StringMatrix sm = (StringMatrix) obj;
+ if (!header.equals(sm.header)) return false;
+ if (matrix.size() != sm.matrix.size()) return false;
+ for (int i = 0; i < matrix.size(); i++){
+ Vector row = (Vector) matrix.get(i);
+ Vector smRow = (Vector) sm.matrix.get(i);
+ if (!(row.equals(smRow))) return false;
+ }
+ return true;
+ }
+
+ /**
+ * @return
+ */
+ public Vector getMatrix() {
+ return matrix;
+ }
+ /**
+ * @return
+ */
+ public String[] getHeader() {
+ String[] result = new String[header.size()];
+ header.toArray(result);
+ return result;
+ }
+
+}
--- /dev/null
+/* Created on Jan 19, 2004 */
+package com.quantum.util;
+
+import java.util.Arrays;
+
+/**
+ * @author holmesbc
+ */
+public class StringUtil {
+
+ public static String substituteString(String original, String placeHolder, String replacementValue) {
+ StringBuffer buffer = new StringBuffer();
+ char[] originalChars = original == null ? new char[0] : original.toCharArray();
+ char[] placeHolderChars = placeHolder.toCharArray();
+ char[] placeHolderComparisonArray = new char[placeHolderChars.length];
+
+ for (int i = 0, length = originalChars.length; i < length; i++) {
+ if (i <= length - placeHolderChars.length) {
+ System.arraycopy(originalChars, i, placeHolderComparisonArray, 0, placeHolderComparisonArray.length);
+ if (Arrays.equals(placeHolderComparisonArray, placeHolderChars)) {
+ i += placeHolderComparisonArray.length - 1;
+ buffer.append(replacementValue);
+ } else {
+ buffer.append(originalChars[i]);
+ }
+ } else {
+ buffer.append(originalChars[i]);
+ }
+ }
+
+ return original == null ? null : buffer.toString();
+ }
+}
--- /dev/null
+package com.quantum.util.connection;
+
+import java.sql.Connection;
+
+import com.quantum.Messages;
+import com.quantum.model.Bookmark;
+import com.quantum.model.ConnectionException;
+import com.quantum.model.NotConnectedException;
+import com.quantum.ui.dialog.ExceptionDisplayDialog;
+import com.quantum.ui.dialog.PasswordDialog;
+
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * <p>This utility gets a connection from a bookmark, and handles any UI-specific
+ * interactions such as providing messages to the user and/or prompting for a
+ * password.
+ *
+ * @author BC
+ */
+public class ConnectionUtil {
+
+ public Connection getConnection(Bookmark bookmark, Shell shell) {
+ Connection connection = null;
+ try {
+ connection = bookmark.getConnection();
+ } catch (NotConnectedException e) {
+ connection = connect(bookmark, shell);
+ }
+ return connection;
+ }
+
+ public Connection connect(Bookmark bookmark, Shell shell) {
+ Connection connection = null;
+ try {
+ connection = bookmark.connect(PasswordDialog.createPasswordFinder(shell));
+ } catch (ConnectionException e) {
+ ExceptionDisplayDialog.openError(shell,
+ Messages.getString(getClass().getName() + ".title"),
+ Messages.getString(getClass().getName() + ".message") +
+ " (Bookmark:"+bookmark.getName()+")", e);
+ }
+ return connection;
+ }
+
+}
--- /dev/null
+package com.quantum.util.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @author BC
+ */
+public class InputStreamHelper {
+ public static String readIntoString(InputStream inputStream) throws IOException {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ for (int b = inputStream.read(); b >= 0; b = inputStream.read()) {
+ outputStream.write((byte) b);
+ }
+ return new String(outputStream.toByteArray());
+ }
+}
--- /dev/null
+/* Created on Jan 9, 2004 */
+package com.quantum.util.sql;
+
+import java.lang.reflect.Field;
+import java.sql.Types;
+
+/**
+ * @author holmesbc
+ */
+public class TypesHelper {
+
+ public static final int BIT = Types.BIT;
+ public static final int TINYINT = Types.TINYINT;
+ public static final int SMALLINT = Types.SMALLINT;
+ public static final int INTEGER = Types.INTEGER;
+ public static final int BIGINT = Types.BIGINT;
+ public static final int FLOAT = Types.FLOAT;
+ public static final int REAL = Types.REAL;
+ public static final int DOUBLE = Types.DOUBLE;
+ public static final int NUMERIC = Types.NUMERIC;
+ public static final int DECIMAL = Types.DECIMAL;
+ public static final int CHAR = Types.CHAR;
+ public static final int VARCHAR = Types.VARCHAR;
+ public static final int LONGVARCHAR = Types.LONGVARCHAR;
+ public static final int DATE = Types.DATE;
+ public static final int TIME = Types.TIME;
+ public static final int TIMESTAMP = Types.TIMESTAMP;
+ public static final int BINARY = Types.BINARY;
+ public static final int VARBINARY = Types.VARBINARY;
+ public static final int LONGVARBINARY = Types.LONGVARBINARY;
+ public static final int NULL = Types.NULL;
+ public static final int OTHER = Types.OTHER;
+ public static final int JAVA_OBJECT = Types.JAVA_OBJECT;
+ public static final int DISTINCT = Types.DISTINCT;
+ public static final int STRUCT = Types.STRUCT;
+ public static final int ARRAY = Types.ARRAY;
+ public static final int BLOB = Types.BLOB;
+ public static final int CLOB = Types.CLOB;
+ public static final int REF = Types.REF;
+ public static final int DATALINK;
+ public static final int BOOLEAN;
+
+ static {
+ // These fields only exist in the JDK 1.4 version of the Types class.
+ BOOLEAN = getType("BOOLEAN", 16);
+ DATALINK = getType("DATALINK", 70);
+ }
+
+ private static int getType(String typeName, int defaultValue) {
+ try {
+ Field field = Types.class.getField(typeName);
+ defaultValue = field.getInt(null);
+ } catch (NoSuchFieldException e) {
+ } catch (IllegalAccessException e) {
+ }
+ return defaultValue;
+ }
+
+}
--- /dev/null
+package com.quantum.util.versioning;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.widgets.FontDialog;
+
+/**
+ * This class provides backward compatibility between versions of Eclipse for
+ * known differences.
+ *
+ * @author BC
+ */
+public class VersioningHelper {
+
+ public static final int ECLIPSE_VERSION_2_1_1 = 2135;
+
+ /**
+ * Set the font in a FontDialog. In Eclipse 2.1.1, the
+ * <code>setFontData()</code> method was deprecated and an alternative
+ * method, <code>setFontList()</code> was suggested in its place.
+ *
+ * @param fontDialog
+ * @param fontData
+ */
+ public static void setFont(FontDialog fontDialog, FontData[] fontData) {
+ try {
+ if (SWT.getVersion() >= ECLIPSE_VERSION_2_1_1) {
+ Method method = fontDialog.getClass().getMethod(
+ "setFontList", new Class[] { fontData.getClass()});
+ method.invoke(fontDialog, new Object[] {fontData});
+ } else if (fontData.length > 0) {
+ Method method = fontDialog.getClass().getMethod(
+ "setFontData", new Class[] { FontData.class });
+ method.invoke(fontDialog, new Object[] { fontData[0] });
+ }
+ } catch (NoSuchMethodException e) {
+ // should not happen
+ } catch (IllegalArgumentException e) {
+ // should not happen
+ } catch (IllegalAccessException e) {
+ // should not happen
+ } catch (InvocationTargetException e) {
+ // should not happen
+ }
+ }
+}
--- /dev/null
+package com.quantum.util.xml;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Writer;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.xml.serialize.DOMSerializer;
+import org.apache.xml.serialize.OutputFormat;
+import org.apache.xml.serialize.XMLSerializer;
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
+
+
+/**
+ * <p>This class constructs a pretty-printing XML Serializer
+ *
+ * @author BC
+ */
+public class XMLHelper {
+
+ private XMLHelper() {}
+
+ public static DOMSerializer createDOMSerializer(Writer writer)
+ throws IOException {
+ XMLSerializer serializer = new XMLSerializer(writer, createOutputFormat());
+ return serializer.asDOMSerializer();
+ }
+
+ public static DOMSerializer createDOMSerializer(OutputStream stream)
+ throws IOException {
+ XMLSerializer serializer = new XMLSerializer(stream, createOutputFormat());
+ return serializer.asDOMSerializer();
+ }
+ private static OutputFormat createOutputFormat() {
+ OutputFormat format = new OutputFormat();
+ format.setIndenting(true);
+ format.setLineWidth(80);
+ return format;
+ }
+
+ public static Document createEmptyDocument() throws ParserConfigurationException {
+ DocumentBuilder builder = createDocumentBuilder();
+ return builder.newDocument();
+ }
+
+ public static Document createFromInputStream(InputStream stream)
+ throws IOException, SAXException, ParserConfigurationException {
+ DocumentBuilder builder = createDocumentBuilder();
+ return builder.parse(stream);
+ }
+
+ private static DocumentBuilder createDocumentBuilder()
+ throws FactoryConfigurationError, ParserConfigurationException {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ return factory.newDocumentBuilder();
+ }
+
+ public static void write(Writer writer, Document document)
+ throws IOException {
+ createDOMSerializer(writer).serialize(document);
+ }
+
+ public static void write(OutputStream stream, Document document)
+ throws IOException {
+ createDOMSerializer(stream).serialize(document);
+ }
+}
--- /dev/null
+/*
+ * Created on 28-jul-2003
+ *
+ */
+package com.quantum.view;
+
+import com.quantum.QuantumPlugin;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+
+
+public final class CopyAction extends Action {
+ private final TableView view;
+ private final Table table;
+ public CopyAction(TableView view, Table table) {
+ super();
+ this.view = view;
+ this.table = table;
+ }
+ public void run() {
+ TableItem items[] = table.getSelection();
+ StringBuffer text = new StringBuffer();
+ for (int i = 0; i < items.length; i++) {
+ int columns = table.getColumnCount();
+ for (int col = 0; col < columns; col++) {
+ text.append(items[i].getText(col));
+ text.append('\t');
+ }
+ text.append('\n');
+ }
+ QuantumPlugin.getDefault().getSysClip().setContents(
+ new Object[] { text.toString()},
+ new Transfer[] { TextTransfer.getInstance()});
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.view;
+
+public interface LogConstants {
+ public int QUERY = 1;
+ public int ERROR = 2;
+ public int RESULTS = 3;
+ public int WARNING = 4;
+ public int DEFAULT = 5;
+}
--- /dev/null
+package com.quantum.view;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+public class LogProxy implements LogConstants {
+ private static LogProxy instance = null;
+ private SQLLogView log = null;
+ private LogProxy() {
+ }
+ public synchronized static LogProxy getInstance() {
+ if (instance == null) {
+ instance = new LogProxy();
+ }
+ return instance;
+ }
+ public void addText(int type, String text) {
+ log = SQLLogView.getInstance();
+ if (log != null) {
+ log.addText(type, text);
+ }
+ }
+
+ public void addText(int type, String text, Exception e) {
+ addText(type, text);
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ addText(type, writer.toString());
+ }
+
+ public void addText(int type, Exception e) {
+ addText(type, "Error occured: " + e, e); //$NON-NLS-1$
+ }
+}
--- /dev/null
+package com.quantum.view;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.custom.StyledTextContent;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.part.ViewPart;
+
+public class SQLLogView extends ViewPart implements LogConstants {
+ private Color QUERY_COLOR;
+ private Color WARNING_COLOR;
+ private Color DEFAULT_COLOR;
+ private Color ERROR_COLOR;
+ private Color RESULTS_COLOR;
+ private StyledText widget;
+ private static SQLLogView instance = null;
+ private static final String newLine = "\n"; //$NON-NLS-1$
+ public static SQLLogView getInstance() {
+ return instance;
+ }
+
+ public void createPartControl(Composite parent) {
+ instance = this;
+ QUERY_COLOR = new Color(parent.getShell().getDisplay(), 0, 255, 0);
+ ERROR_COLOR = new Color(parent.getShell().getDisplay(), 255, 0, 0);
+ RESULTS_COLOR = new Color(parent.getShell().getDisplay(), 0, 0, 255);
+ DEFAULT_COLOR = new Color(parent.getShell().getDisplay(), 0, 0, 0);
+ WARNING_COLOR = new Color(parent.getShell().getDisplay(), 255, 127, 0);
+ widget = new StyledText(parent, SWT.H_SCROLL | SWT.V_SCROLL);
+ IActionBars bars = this.getViewSite().getActionBars();
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.COPY, copyAction);
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, selectAllAction);
+
+ IToolBarManager toolBar = getViewSite().getActionBars().getToolBarManager();
+ clearAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("clear.gif")); //$NON-NLS-1$
+ clearAction.setToolTipText(Messages.getString("SQLLogView.ClearLog")); //$NON-NLS-1$
+ toolBar.add(clearAction);
+
+ widget.setEditable(false);
+
+ widget.addDisposeListener(new DisposeListener() {
+ public void widgetDisposed(DisposeEvent e) {
+ instance = null;
+ }
+ });
+ }
+
+ public void addText(int style, String text) {
+ text = text + newLine;
+ int start = widget.getText().length();
+ StyleRange styleRange = new StyleRange();
+ styleRange.start = start;
+ styleRange.length = text.length();
+ if (style == QUERY) {
+ styleRange.foreground = QUERY_COLOR;
+ } else if (style == ERROR) {
+ styleRange.foreground = ERROR_COLOR;
+ } else if (style == RESULTS) {
+ styleRange.foreground = RESULTS_COLOR;
+ } else if (style == WARNING) {
+ styleRange.foreground = WARNING_COLOR;
+ } else {
+ styleRange.foreground = DEFAULT_COLOR;
+ }
+ widget.append(text);
+ widget.setStyleRange(styleRange);
+ revealEndOfDocument();
+ }
+
+ protected void revealEndOfDocument() {
+ StyledTextContent doc= widget.getContent();
+ int docLength= doc.getCharCount();
+ if (docLength > 0) {
+ widget.setCaretOffset(docLength);
+ widget.showSelection();
+ }
+ }
+
+ public void setFocus() {
+ widget.setFocus();
+ }
+
+ private Action copyAction = new Action() {
+ public void run() {
+ widget.copy();
+ }
+ };
+ private Action selectAllAction = new Action() {
+ public void run() {
+ widget.selectAll();
+ }
+ };
+ private Action clearAction = new Action() {
+ public void run() {
+ widget.setText(""); //$NON-NLS-1$
+ }
+ };
+}
--- /dev/null
+package com.quantum.view;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.LinkedList;
+import java.util.NoSuchElementException;
+import java.util.Vector;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ExtendedModifyEvent;
+import org.eclipse.swt.custom.ExtendedModifyListener;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.ProgressBar;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.ToolItem;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IKeyBindingService;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.part.ViewPart;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.actions.ExecuteAction;
+import com.quantum.actions.ExportQueryAction;
+import com.quantum.actions.ImportQueryAction;
+import com.quantum.model.Bookmark;
+import com.quantum.model.NotConnectedException;
+import com.quantum.sql.MultiSQLServer;
+import com.quantum.sql.parser.SQLLexx;
+import com.quantum.sql.parser.Token;
+import com.quantum.view.bookmark.BookmarkNode;
+import com.quantum.view.bookmark.BookmarkView;
+
+public class SQLQueryView extends ViewPart {
+ private ExecuteAction executeAction;
+ private ImportQueryAction importQueryAction;
+ private ExportQueryAction exportQueryAction;
+ private Label statusImage;
+ private Label status;
+ private ProgressBar progress;
+ private StyledText widget;
+ private ToolItem autoCommitItem;
+ private ToolItem commitItem;
+ private ToolItem rollbackItem;
+ private Color STRING_LITERAL;
+ private Color KEYWORD;
+ private Color COMMENT;
+ private Color NUMERIC;
+ private Color DEFAULT;
+ private long parseTime = 0;
+ private long fullTime = 0;
+ public SQLQueryView() {
+ super();
+ }
+ public void setFocus() {
+
+ String title = "Quantum SQL Query Editor";
+ BookmarkNode bookmarkNode = null;
+ Bookmark bookmark = null;
+ Connection con = null;
+ if (BookmarkView.getInstance() != null ) {
+ bookmarkNode = BookmarkView.getInstance().getCurrentBookmark();
+ }
+ if (bookmarkNode != null)
+ bookmark = bookmarkNode.getBookmark();
+ if (bookmark != null) {
+ title = bookmark.getName() + " (" + title + ")";
+ setTitle( title );
+ try {
+ con = bookmark.getConnection();
+ } catch (NotConnectedException e) {
+ // Doesn't matter, "con" remains null
+ }
+ }
+
+ updateAutoCommitState(bookmark, con);
+
+ widget.setFocus();
+
+ }
+ public static SQLQueryView getInstance() {
+ return (SQLQueryView) QuantumPlugin.getDefault().getView("com.quantum.view.sqlqueryview");
+
+ }
+
+ public void createPartControl(org.eclipse.swt.widgets.Composite parent) {
+ initActions();
+ KEYWORD = new Color(parent.getShell().getDisplay(), 126, 0, 75);
+ STRING_LITERAL = new Color(parent.getShell().getDisplay(), 0, 0, 255);
+ COMMENT = new Color(parent.getShell().getDisplay(), 88, 148, 64);
+ NUMERIC = new Color(parent.getShell().getDisplay(), 255, 0, 0);
+ DEFAULT = new Color(parent.getShell().getDisplay(), 0, 0, 0);
+ Composite main = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.horizontalSpacing = 0;
+ layout.verticalSpacing = 0;
+ main.setLayout(layout);
+ ToolBar toolbar = new ToolBar(main, SWT.HORIZONTAL);
+ ToolItem item = new ToolItem(toolbar, SWT.PUSH);
+ item.setImage(QuantumPlugin.getImage("play.gif")); //$NON-NLS-1$
+ item.setToolTipText(Messages.getString("sqlqueryview.executeQuery")); //$NON-NLS-1$
+ item.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ executeAction.run();
+ }
+ });
+ item = new ToolItem(toolbar, SWT.SEPARATOR);
+ item = new ToolItem(toolbar, SWT.PUSH);
+ item.setImage(QuantumPlugin.getImage("import.gif")); //$NON-NLS-1$
+ item.setToolTipText(Messages.getString("sqlqueryview.importQuery")); //$NON-NLS-1$
+ item.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ importQueryAction.run();
+ }
+ });
+ item = new ToolItem(toolbar, SWT.PUSH);
+ item.setImage(QuantumPlugin.getImage("export.gif")); //$NON-NLS-1$
+ item.setToolTipText(Messages.getString("sqlqueryview.exportQuery")); //$NON-NLS-1$
+ item.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ exportQueryAction.run();
+ }
+ });
+ item = new ToolItem(toolbar, SWT.PUSH);
+ item.setImage(QuantumPlugin.getImage("clear.gif")); //$NON-NLS-1$
+ item.setToolTipText(Messages.getString("sqlqueryview.clear")); //$NON-NLS-1$
+ item.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ setQuery(""); //$NON-NLS-1$
+ }
+ });
+
+ item = new ToolItem(toolbar, SWT.SEPARATOR);
+
+ commitItem = new ToolItem(toolbar, SWT.PUSH);
+ commitItem.setImage(QuantumPlugin.getImage("commit.gif")); //$NON-NLS-1$
+ commitItem.setToolTipText(Messages.getString("SQLQueryView.Commit")); //$NON-NLS-1$
+ commitItem.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent event) {
+ try {
+ BookmarkNode node = BookmarkView.getInstance().getCurrentBookmark();
+ if (node != null) MultiSQLServer.getInstance().commit(
+ node.getBookmark().getConnection());
+ } catch (NotConnectedException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+ rollbackItem = new ToolItem(toolbar, SWT.PUSH);
+ rollbackItem.setImage(QuantumPlugin.getImage("rollback.gif")); //$NON-NLS-1$
+ rollbackItem.setToolTipText(Messages.getString("SQLQueryView.RollBack")); //$NON-NLS-1$
+ rollbackItem.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent event) {
+ }
+ public void widgetSelected(SelectionEvent event) {
+ try {
+ BookmarkNode node = BookmarkView.getInstance().getCurrentBookmark();
+ if (node != null) MultiSQLServer.getInstance().rollback(
+ node.getBookmark().getConnection());
+ } catch (NotConnectedException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+ autoCommitItem = new ToolItem(toolbar, SWT.CHECK);
+ autoCommitItem.setImage(QuantumPlugin.getImage("autocommit.gif")); //$NON-NLS-1$
+ autoCommitItem.setToolTipText(Messages.getString("SQLQueryView.AutoCommit")); //$NON-NLS-1$
+ autoCommitItem.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent event) {
+ BookmarkNode node = BookmarkView.getInstance().getCurrentBookmark();
+ if (node == null) return;
+ Connection con = null;
+ try {
+ // Get the connection
+ con = node.getBookmark().getConnection();
+ // If connected (else will throw exception and jump out) switchs the state of the
+ // autoCommit option of the JDBC driver
+ MultiSQLServer.getInstance().setAutoCommit( con, autoCommitItem.getSelection());
+ } catch (NotConnectedException e) {
+ //Doesn't matter
+ }
+ // Update the bookmark and the buttons
+ updateAutoCommitState(node.getBookmark(), con);
+
+ }
+ });
+ BookmarkNode node = BookmarkView.getInstance().getCurrentBookmark();
+ if (node == null) autoCommitItem.setSelection(true);
+ else autoCommitItem.setSelection(node.getBookmark().isAutoCommit());
+ if (autoCommitItem.getSelection()) {
+ commitItem.setEnabled(false);
+ rollbackItem.setEnabled(false);
+ } else {
+ commitItem.setEnabled(true);
+ rollbackItem.setEnabled(true);
+ }
+ widget = new StyledText(main, SWT.H_SCROLL | SWT.V_SCROLL);
+
+ IActionBars bars = this.getViewSite().getActionBars();
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.CUT, cutAction);
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.COPY, copyAction);
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.PASTE, pasteAction);
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, selectAllAction);
+
+ widget.setEditable(true);
+ widget.addExtendedModifyListener(modifyListener);
+
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ widget.setLayoutData(gridData);
+
+ Composite bottomStatus = new Composite(main, SWT.NONE);
+ gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ bottomStatus.setLayoutData(gridData);
+
+ GridLayout horizontal = new GridLayout(3, false);
+ layout.horizontalSpacing = 0;
+ layout.verticalSpacing = 0;
+ layout.marginHeight = 0;
+ layout.marginWidth = 0;
+ bottomStatus.setLayout(horizontal);
+
+ statusImage = new Label(bottomStatus, SWT.NONE);
+ status = new Label(bottomStatus, SWT.NONE);
+ gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ status.setLayoutData(gridData);
+
+ progress = new ProgressBar(bottomStatus, SWT.HORIZONTAL);
+
+ status.setText(Messages.getString("sqlqueryview.done")); //$NON-NLS-1$
+ statusImage.setImage(QuantumPlugin.getImage("success.gif")); //$NON-NLS-1$
+ progress.setMinimum(0);
+
+ IKeyBindingService keyBindingService = getSite().getKeyBindingService();
+ // TODO: check the version numbers for this method
+ keyBindingService.setScopes(new String[] {
+ "org.eclipse.ui.globalScope",
+ "com.quantum.view.sql"
+ });
+ keyBindingService.registerAction(this.executeAction);
+ }
+
+ /**
+ * Sets the state of the "Commit", "Rollback" and "autoCommit" buttons
+ * to reflect the situation in the connection
+ */
+ protected void updateAutoCommitState(Bookmark bookmark, Connection con) {
+ boolean autoCommit = true;
+ // Calculate the state of the autoCommit option
+ if (con != null)
+ {
+ // If we have a connection, the autoCommit state is that of the connection
+ try {
+ autoCommit = con.getAutoCommit();
+ } catch (SQLException e) {
+ // Doesn't matter, we take default
+ }
+ } else {
+ // if no connection, we try the autoCommit of the bookmark, or else the default
+ if (bookmark != null) autoCommit = bookmark.isAutoCommit();
+ }
+ // Set the autoCommit state of the bookmark to the calculated
+ if (bookmark != null) bookmark.setAutoCommit(autoCommit);
+ // Set the state of the buttons to the correct autoCommit state
+ autoCommitItem.setSelection(autoCommit);
+ if (autoCommitItem.getSelection()) {
+ commitItem.setEnabled(false);
+ rollbackItem.setEnabled(false);
+ } else {
+ commitItem.setEnabled(true);
+ rollbackItem.setEnabled(true);
+ }
+ }
+ public void setProgress(int increment, int max) {
+ progress.setMaximum(max);
+ progress.setSelection(increment);
+ }
+
+ private void initActions() {
+ executeAction = new ExecuteAction();
+ executeAction.init(this);
+ importQueryAction = new ImportQueryAction();
+ importQueryAction.init(this);
+ exportQueryAction = new ExportQueryAction();
+ exportQueryAction.init(this);
+ }
+
+ public void setStatus(String text) {
+ statusImage.setImage(null);
+ status.setText(text);
+ }
+
+ public void setStatus(Image img, String text) {
+ statusImage.setImage(img);
+ status.setText(text);
+ }
+
+ public String getQuery() {
+ return widget.getText();
+ }
+
+ public void setQuery(String text) {
+ widget.setText(text);
+ }
+
+ private String[] keywords = {
+ "ADD", "ALL", "ALTER", "AND", "ANY",
+ "AS", "ASC", "AUTOINCREMENT", "AVA", "BETWEEN",
+ "BINARY", "BIT", "BOOLEAN", "BY", "CREATE",
+ "BYTE", "CHAR", "CHARACTER", "COLUMN", "CONSTRAINT",
+ "COUNT", "COUNTER", "CURRENCY", "DATABASE", "DATE",
+ "DATETIME", "DELETE", "DESC", "DISALLOW", "DISTINCT",
+ "DISTINCTROW", "DOUBLE", "DROP", "EXISTS", "FROM",
+ "FLOAT", "FLOAT4", "FLOAT8", "FOREIGN", "GENERAL",
+ "GROUP", "GUID", "HAVING", "INNER", "INSERT",
+ "IGNORE", "IMP", "IN", "INDEX", "INT",
+ "INTEGER", "INTEGER1", "INTEGER2", "INTEGER4", "INTO",
+ "IS", "JOIN", "KEY", "LEFT", "LEVEL",
+ "LIKE", "LOGICAL", "LONG", "LONGBINARY", "LONGTEXT",
+ "MAX", "MEMO", "MIN", "MOD", "MONEY",
+ "NOT", "NULL", "NUMBER", "NUMERIC", "OLEOBJECT",
+ "ON", "PIVOT", "OPTION", "PRIMARY", "ORDER",
+ "OUTER", "OWNERACCESS", "PARAMETERS", "PERCENT", "REAL",
+ "REFERENCES", "RIGHT", "SELECT", "SET", "SHORT",
+ "SINGLE", "SMALLINT", "SOME", "STDEV", "STDEVP",
+ "STRING", "SUM", "TABLE", "TABLEID", "TEXT",
+ "TIME", "TIMESTAMP", "TOP", "TRANSFORM", "UNION",
+ "UNIQUE", "UPDATE", "VALUE", "VALUES", "VAR",
+ "VARBINARY", "VARCHAR", "VARP", "WHERE", "WITH",
+ "YESNO" };
+
+ SyntaxHighlighter textUpdater = new SyntaxHighlighter();
+
+ private class UpdateRequest {
+ public UpdateRequest(String text, int start, int length) {
+ this.text = text;
+ this.start = start;
+ this.length = length;
+ }
+ public String text;
+ public int start;
+ public int length;
+ }
+
+ private class SyntaxHighlighter extends Thread {
+ private boolean running = true;
+ private LinkedList requests = new LinkedList();
+ public SyntaxHighlighter() {
+ super();
+ setPriority(Thread.MIN_PRIORITY);
+ start();
+ }
+ public synchronized void updateText(String text, int start, int length) {
+ requests.add(new UpdateRequest(text, start, length));
+ notify();
+ }
+ public synchronized void shutdown() {
+ running = false;
+ interrupt();
+ }
+ public void run() {
+ while (running) {
+ try {
+ synchronized (this) {
+ if (requests.size() <= 0) {
+ wait();
+ } else {
+ Thread.sleep(10);
+ }
+ }
+ UpdateRequest request = (UpdateRequest) requests.removeFirst();
+ String text = request.text.toUpperCase();
+ //int dirtyStart = request.start;
+ //int dirtyEnd = request.start + request.length;
+ StyleRange styleRange;
+ long startTime = System.currentTimeMillis();
+ Vector tokens = SQLLexx.parse(text);
+ long subTime = System.currentTimeMillis();
+ Vector styles = new Vector();
+ int min = Integer.MAX_VALUE;
+ int max = 0;
+ for (int i = 0; i < tokens.size(); i++) {
+ Token t = (Token) tokens.elementAt(i);
+ String value = t.getValue();
+ int start = t.getStart();
+ int length = t.getEnd() - t.getStart();
+ styleRange = new StyleRange();
+ styleRange.start = start;
+ styleRange.length = value.length();
+ styleRange.fontStyle = SWT.NULL;
+ styleRange.foreground = DEFAULT;
+ //boolean upper = start <= dirtyEnd && start >= dirtyStart;
+ //boolean lower = ((start + length) >= dirtyStart && (start + length) <= dirtyEnd);
+ //boolean both = (start <= dirtyStart && (start + length) >= dirtyEnd);
+ //if (upper || lower || both) {
+ if (true) { // Let's update the whole text, as some comment changes can alter everything
+ min = Math.min(start, min);
+ max = Math.max(max, start + length);
+ if (t.getType() == Token.IDENTIFIER) {
+ boolean keyword = false;
+ for (int index = 0; index < keywords.length; index++) {
+ if (value.equals(keywords[index])) {
+ keyword = true;
+ }
+ }
+ if (keyword) {
+ styleRange.fontStyle = SWT.BOLD;
+ styleRange.foreground = KEYWORD;
+ } else {
+ styleRange.foreground = DEFAULT;
+ }
+ styles.addElement(styleRange);
+ } else if (t.getType() == Token.COMMENT) {
+ styleRange.foreground = COMMENT;
+ styles.addElement(styleRange);
+ } else if (t.getType() == Token.LITERAL) {
+ styleRange.foreground = STRING_LITERAL;
+ styles.addElement(styleRange);
+ } else if (t.getType() == Token.NUMERIC) {
+ styleRange.foreground = NUMERIC;
+ styles.addElement(styleRange);
+ } else {
+ styles.addElement(styleRange);
+ }
+ }
+ }
+ StyleRange[] ranges = new StyleRange[styles.size()];
+ for (int k = 0; k < ranges.length; k++) {
+ ranges[k] = (StyleRange) styles.elementAt(k);
+ }
+ if (max >= 0 && ranges.length > 0) {
+ setStyles(ranges, min, max - min);
+ }
+ long endTime = System.currentTimeMillis();
+ parseTime = subTime - startTime;
+ fullTime = endTime - startTime;
+ } catch (NoSuchElementException e) {
+ // ignore a missing request
+ } catch (InterruptedException e) {
+ // ignore any interruptions
+ }
+ }
+ }
+ }
+ public void setStyles(final StyleRange[] styles, final int start, final int length) {
+ getViewSite().getShell().getDisplay().asyncExec(new Runnable() {
+ public void run() {
+ try {
+ for (int i = 0; i < styles.length; i++) {
+ widget.setStyleRange(styles[i]);
+ }
+ } catch (Throwable t) {
+ System.out.println("Error with styles: " + t.getClass().toString()); //$NON-NLS-1$
+ // ignore any errors
+ }
+ }
+ });
+ }
+
+ ExtendedModifyListener modifyListener = new ExtendedModifyListener() {
+ public void modifyText(ExtendedModifyEvent event) {
+ textUpdater.updateText(getQuery(), event.start, event.length);
+ }
+ };
+
+ private Action cutAction = new Action() {
+ public void run() {
+ widget.cut();
+ }
+ };
+ private Action copyAction = new Action() {
+ public void run() {
+ widget.copy();
+ }
+ };
+ private Action pasteAction = new Action() {
+ public void run() {
+ widget.paste();
+ }
+ };
+ private Action selectAllAction = new Action() {
+ public void run() {
+ widget.selectAll();
+ }
+ };
+}
--- /dev/null
+/*
+ * Created on 22-jul-2003
+ *
+ */
+package com.quantum.view;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.sql.MultiSQLServer;
+import com.quantum.sql.SQLResults;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IViewPart;
+
+/**
+ * @author panic
+ *
+ */
+public class ViewHelper {
+
+ public static SQLResults tryGetResults(IViewPart view, Connection con, String query) {
+ return tryGetResults(view.getSite().getShell(), con, query);
+ }
+
+ public static SQLResults tryGetResults(Shell shell, Connection con, String query) {
+ SQLResults results = null;
+ MultiSQLServer server = MultiSQLServer.getInstance();
+ try {
+ results = server.execute(con, query);
+ } catch (SQLException e) {
+ LogProxy log = LogProxy.getInstance();
+ log.addText(LogProxy.ERROR, e.getLocalizedMessage(), e); //$NON-NLS-1$ //$NON-NLS-2$
+ results = new SQLResults();
+ results.setIsError(true);
+ MessageDialog.openConfirm(shell, "Database returned error", e.getLocalizedMessage()); //$NON-NLS-1$
+ }
+ return results;
+ }
+
+ public static FileOutputStream askSaveFile(String key, Shell shell) {
+ return askSaveFile(key, shell, null, null);
+ }
+ /**
+ * Asks the user for a file to be saved. Uses a key to get the preferences and save the path.
+ * The preferences should be defined in the Messages file.
+ * @param key
+ * @param shell
+ * @param filterExt
+ * @param filterNames
+ * @return - An already opened FileOutputStream, or NULL if nothing selected, dialog canceled or some error.
+ */
+ public static FileOutputStream askSaveFile(String key, Shell shell, String[] filterExt, String[] filterNames) {
+
+ FileDialog dialog = new FileDialog(shell, SWT.SAVE);
+
+ if (filterExt == null) {
+ dialog.setFilterExtensions(new String[]{Messages.getString("filedialog."+key+".filter"),
+ Messages.getString("filedialog.allfiles.filter")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ dialog.setFilterNames(new String[]{ Messages.getString("filedialog."+key+".name"),
+ Messages.getString("filedialog.allfiles.name")}); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ dialog.setFilterExtensions(filterExt);
+ dialog.setFilterNames(filterNames);
+ }
+
+ dialog.setFilterPath(QuantumPlugin.getDefault().getPreferenceStore().getString("quantum.dialogs."+ key + ".path"));
+ String filename = dialog.open();
+ if (filename == null) return null;
+ // We save the used path
+ QuantumPlugin.getDefault().getPreferenceStore().setValue("quantum.dialogs."+ key + ".path", filename);
+
+ FileOutputStream out = null;
+ File target = new File(filename);
+ if (target.exists() && Messages.getString("filedialog.options.ConfirmOverwrite").equals("y")) {
+ boolean confirmOverwrite =
+ MessageDialog.openConfirm(shell, Messages.getString("filedialog.message.ConfirmOverwriteTitle"), //$NON-NLS-1$
+ Messages.getString("filedialog.message.ConfirmOverwriteMessage") + target.getName() + //$NON-NLS-1$
+ Messages.getString("filedialog.message.ConfirmOverwriteQuestion")); //$NON-NLS-1$
+ if (!confirmOverwrite) return null;
+ }
+
+ try {
+ out = new FileOutputStream(target);
+ } catch (FileNotFoundException e) {
+ MessageDialog.openConfirm(shell, Messages.getString("filedialog.message.CannotOpenFileTitle"), //$NON-NLS-1$
+ Messages.getString("filedialog.message.CannotOpenFileMessage") + filename+ //$NON-NLS-1$
+ Messages.getString("filedialog.message.CannotOpenFileExplain")); //$NON-NLS-1$
+
+ }
+ return out;
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.NotConnectedException;
+import com.quantum.sql.SQLHelper;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+
+final class AddSchemaAction extends SelectionListenerAction {
+ private final IViewPart view;
+ /**
+ * @param BookmarkView
+ */
+ public AddSchemaAction(IViewPart view) {
+ super(Messages.getString("BookmarkView.SetExtraSchemas")); //$NON-NLS-1$
+ setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("add_schema.gif")); //$NON-NLS-1$
+ this.view = view;
+ }
+
+ public void run() {
+ Bookmark bookmark = getBookmark();
+ if (bookmark != null) {
+ try {
+ Vector schemas = SQLHelper.getSchemas(bookmark.getConnection());
+ AddSchemaDialog dialog = new AddSchemaDialog(this.view.getSite().getShell(), schemas);
+ dialog.open();
+ if (dialog.getSelectedSchemas() != null) {
+ for (Iterator i = dialog.getSelectedSchemas().iterator(); i.hasNext();) {
+ bookmark.addSchema((String) i.next());
+ }
+ }
+ } catch (NotConnectedException e) {
+ }
+ }
+ }
+
+ protected Bookmark getBookmark() {
+ List list = getSelectedNonResources();
+ return (list.size() > 0) ? ((BookmarkNode) list.get(0)).getBookmark() : null;
+ }
+
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection) &
+ selection.size() == 1 &
+ (selection.getFirstElement() instanceof BookmarkNode);
+ return enabled & getBookmark().isConnected();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Created on 12-jul-2003
+ *
+ */
+package com.quantum.view.bookmark;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Vector;
+
+import com.quantum.IQuantumConstants;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.help.WorkbenchHelp;
+
+/**
+ * @author panic
+ *
+ */
+public class AddSchemaDialog extends Dialog {
+
+ protected Vector input;
+ protected List list;
+ private Vector selection;
+ /**
+ * Creates a new AddSchemaDialog.
+ */
+ public AddSchemaDialog(Shell parentShell, Vector input) {
+ super(parentShell);
+ this.input = input;
+ this.list = null;
+ selection = null;
+ }
+ /* (non-Javadoc)
+ * Method declared on Window.
+ */
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Set Schemas");
+ WorkbenchHelp.setHelp(
+ newShell,
+ IQuantumConstants.ADD_SCHEMA_DIALOG_CONTEXT);
+ }
+ /* (non-Javadoc)
+ * Method declared on Dialog
+ */
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = (Composite) super.createDialogArea(parent);
+
+ list = new List(composite, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
+ GridData data = new GridData(GridData.FILL_BOTH);
+ list.setLayoutData(data);
+ for (Iterator iter = input.iterator(); iter.hasNext();) {
+ String element = (String) iter.next();
+ list.add(element);
+ }
+ return composite;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.dialogs.Dialog#okPressed()
+ */
+ protected void okPressed() {
+ // If it's OK, then the selection is not null. Null is used to signal a canceled dialog.
+ selection = new Vector();
+ if (list != null) {
+ String selecStr[] = list.getSelection();
+ for (int i = 0; i < selecStr.length; i++) {
+ String string = selecStr[i];
+ selection.add(string);
+ }
+ }
+ super.okPressed();
+ }
+
+ public Collection getSelectedSchemas() {
+ return this.selection == null ? null : new ArrayList(this.selection);
+ }
+
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import com.quantum.model.Bookmark;
+
+/**
+ *
+ * TODO: There must be a better way to do this...
+ * @author BC
+ */
+public interface BookmarkClipboard {
+ public void setBookmark(Bookmark bookmark);
+ public Bookmark getBookmark();
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+public class BookmarkContentProvider implements ITreeContentProvider {
+
+ public Object[] getChildren(Object element) {
+ if (element instanceof TreeNode) {
+ TreeNode node = (TreeNode) element;
+ return node.getChildren();
+ }
+ return BookmarkListNode.EMPTY_ARRAY;
+ }
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
+
+ public Object getParent(Object element) {
+ if (element instanceof TreeNode) {
+ TreeNode node = (TreeNode) element;
+ return node.getParent();
+ }
+ return null;
+ }
+
+ public boolean hasChildren(Object element) {
+ if (element instanceof TreeNode) {
+ TreeNode node = (TreeNode) element;
+ return node.hasChildren();
+ }
+ return false;
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+
+ public void dispose() {
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * @author root
+ *
+ * Implements the ILabelProvider for the Bookmarks.
+ */
+public class BookmarkLabelProvider implements ILabelProvider {
+
+ private LabelDecorationInstructions labelDecorationInstructions = new LabelDecorationInstructions();
+
+ /**
+ * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ if (element != null && element instanceof TreeNode) {
+ return ((TreeNode) element).getImage();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+ if (element != null && element instanceof TreeNode) {
+ String labelName = ((TreeNode) element).getLabelName();
+ String decorations = ((TreeNode) element).getLabelDecorations(
+ this.labelDecorationInstructions);
+ if (decorations != null && decorations.trim().length() > 0) {
+ labelName += " " + decorations;
+ }
+ return labelName;
+ } else {
+ return element == null ? "<<empty>>" : element.toString();
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(ILabelProviderListener)
+ */
+ public void addListener(ILabelProviderListener listener) {
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(Object, String)
+ */
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(ILabelProviderListener)
+ */
+ public void removeListener(ILabelProviderListener listener) {
+ }
+ /**
+ * @return
+ */
+ public LabelDecorationInstructions getLabelDecorationInstructions() {
+ return labelDecorationInstructions;
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Map;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkCollection;
+
+
+/**
+ * @author root
+ */
+public final class BookmarkListNode extends TreeNode implements PropertyChangeListener {
+ final static BookmarkListNode instance = new BookmarkListNode();
+ final static TreeNode[] EMPTY_ARRAY = new TreeNode[0];
+ private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
+ private boolean initialized = false;
+
+ private BookmarkListNode() {
+ super(null);
+ }
+
+ public static BookmarkListNode getInstance() {
+ return BookmarkListNode.instance;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getChildren()
+ */
+ public Object[] getChildren() {
+ if (!initialized) {
+ initializeChildren();
+ BookmarkCollection.getInstance().addPropertyChangeListener(this);
+ }
+ BookmarkNode[] nodes = (BookmarkNode[]) this.children.toArray(
+ new BookmarkNode[this.children.size()]);
+ Arrays.sort(nodes);
+ return nodes;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#hasChildren()
+ */
+ public boolean hasChildren() {
+ return true;
+ }
+
+ public String getName() {
+ return "ROOT"; //$NON-NLS-1$
+ }
+ protected String getImageName() {
+ return null;
+ }
+ /**
+ * @param listener
+ */
+ public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
+ this.propertyChangeSupport.addPropertyChangeListener(listener);
+ }
+
+ /**
+ * @param listener
+ */
+ public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
+ this.propertyChangeSupport.removePropertyChangeListener(listener);
+ }
+ protected void firePropertyChange(PropertyChangeEvent event) {
+ this.propertyChangeSupport.firePropertyChange(event);
+ }
+
+ protected synchronized void initializeChildren() {
+ boolean changed = false;
+ Map temp = new Hashtable();
+ for (Iterator i = this.children.iterator(); i.hasNext();) {
+ BookmarkNode bookmark = (BookmarkNode) i.next();
+ temp.put(bookmark.getName(), bookmark);
+ }
+
+ this.children.clear();
+
+ Bookmark[] bookmarks = BookmarkCollection.getInstance().getBookmarks();
+ for (int i = 0, length = (bookmarks == null) ? 0 : bookmarks.length; i < length; i++) {
+
+ BookmarkNode node = (BookmarkNode) temp.remove(bookmarks[i].getName());
+ if (node == null) {
+ this.children.add(new BookmarkNode(this, bookmarks[i]));
+ changed = true;
+ } else {
+ this.children.add(node);
+ }
+ }
+
+ for (Iterator i = temp.values().iterator(); i.hasNext(); ) {
+ ((TreeNode) i.next()).dispose();
+ changed = true;
+ }
+
+ Collections.sort(this.children);
+ this.initialized = true;
+
+ if (changed) {
+ firePropertyChange("bookmarks", null, null);
+ }
+ }
+
+ /**
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ if ("bookmarks".equals(event.getPropertyName())) {
+ initializeChildren();
+ }
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.ConnectionException;
+import com.quantum.model.NotConnectedException;
+import com.quantum.model.Schema;
+
+public class BookmarkNode extends TreeNode implements PropertyChangeListener {
+ private Bookmark bookmark;
+
+ private QuickListNode quickListNode;
+ private QueryListNode queryListNode;
+
+ public BookmarkNode(TreeNode parent, Bookmark bookmark) {
+ super(parent);
+ this.bookmark = bookmark;
+ this.bookmark.addPropertyChangeListener(this);
+ }
+
+ public Object[] getChildren() {
+ if (bookmark.isConnected() && this.children.isEmpty()) {
+ initializeChildren();
+ }
+ if (this.bookmark.isConnected()) {
+ return (TreeNode[]) this.children.toArray(new TreeNode[this.children.size()]);
+ } else {
+ return BookmarkListNode.EMPTY_ARRAY;
+ }
+ }
+
+ protected void initializeChildren() {
+ boolean changed = false;
+ Map temp = new HashMap();
+ for (Iterator i = this.children.iterator(); i.hasNext(); ) {
+ TreeNode node = (TreeNode) i.next();
+ if (node instanceof SchemaNode) {
+ temp.put(node.getName(), node);
+ }
+ }
+
+ this.children.clear();
+ if (this.quickListNode == null) {
+ this.quickListNode = new QuickListNode(this);
+ }
+ if (this.queryListNode == null) {
+ this.queryListNode = new QueryListNode(this);
+ }
+ this.children.add(this.quickListNode);
+ this.children.add(this.queryListNode);
+ Bookmark bookmark = getBookmark();
+
+ Schema[] schemas = bookmark.getSchemas();
+ for (int i = 0, length = (schemas == null) ? 0 : schemas.length;
+ i < length;
+ i++) {
+ SchemaNode node = (SchemaNode) temp.remove(schemas[i].getDisplayName());
+ if (node == null) {
+ this.children.add(new SchemaNode(this, schemas[i]));
+ } else {
+ changed = true;
+ this.children.add(node);
+ }
+ }
+
+ for (Iterator i = temp.values().iterator(); i.hasNext(); ) {
+ ((TreeNode) i.next()).dispose();
+ changed = true;
+ }
+
+ if (changed) {
+ firePropertyChange("children", null, null);
+ }
+ }
+
+ public boolean hasChildren() {
+ // If the bookmark is connected but hasn't loaded the tables and views, we suppose it may have some
+ if (bookmark.isConnected() && this.children.isEmpty()) {
+ return true;
+ } else if (!bookmark.isConnected()) {
+ return false;
+ } else if (children != null && children.size() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ protected void dispose() {
+ try {
+ this.bookmark.removePropertyChangeListener(this);
+ if (this.bookmark.isConnected()) {
+ this.bookmark.disconnect();
+ }
+ } catch (ConnectionException e) {
+ }
+ }
+
+ /**
+ * @see com.quantum.model.TreeNode#getName()
+ */
+ public String getName() {
+ return this.bookmark == null ? "<<new>>" : this.bookmark.getName();
+ }
+
+ /**
+ * @return
+ */
+ public Bookmark getBookmark() {
+ return this.bookmark;
+ }
+
+ protected String getImageName() {
+ return this.bookmark.isConnected() ? "connected.gif" : "bookmarks.gif";
+ }
+
+ /* (non-Javadoc)
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ if ("connected".equals(event.getPropertyName())) {
+ if (Boolean.FALSE.equals(event.getNewValue())) {
+ removeAllChildren();
+ }
+ firePropertyChange("connected", event.getOldValue(), event.getNewValue());
+ } else if ("schemas".equals(event.getPropertyName())) {
+ initializeChildren();
+ firePropertyChange("children", event.getOldValue(), event.getNewValue());
+ } else if ("name".equals(event.getPropertyName())) {
+ firePropertyChange("name", event.getOldValue(), event.getNewValue());
+ }
+ }
+
+ protected void removeAllChildren() {
+ if (this.quickListNode != null) {
+ this.quickListNode.dispose();
+ this.quickListNode = null;
+ }
+ if (this.queryListNode != null) {
+ this.queryListNode.dispose();
+ this.queryListNode = null;
+ }
+ super.removeAllChildren();
+
+ }
+ public String getLabelDecorations(LabelDecorationInstructions labelDecorationInstructions) {
+ if (!labelDecorationInstructions.isDatabaseDataVisible()) {
+ return null;
+ } else if (!this.bookmark.isConnected()) {
+ return null;
+ } else {
+ try {
+ String decoration = this.bookmark.getDatabase().getInformation();
+ return decoration == null ? null : "[" + decoration + "]";
+ } catch (NotConnectedException e) {
+ return null;
+ } catch (SQLException e) {
+ return null;
+ }
+ }
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.Vector;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IMenuListener;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.viewers.IOpenListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.OpenEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.WorkbenchException;
+import org.eclipse.ui.actions.ActionContext;
+import org.eclipse.ui.part.ViewPart;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.actions.CustomCopyAction;
+import com.quantum.extensions.ExtensionAction;
+import com.quantum.extensions.ProcessServiceMembers;
+
+public class BookmarkView extends ViewPart implements PropertyChangeListener {
+ private CustomCopyAction customCopyAction1;
+ private CustomCopyAction customCopyAction2;
+ private CustomCopyAction customCopyAction3;
+ private Vector extensionVector;
+
+ private BookmarkViewActionGroup actionGroup;
+
+ private TreeViewer treeViewer;
+ private BookmarkLabelProvider labelProvider = new BookmarkLabelProvider();
+
+ /**
+ * @return -
+ * The instance of the BookmarkView. There is no guarantee of it being a singleton
+ * due to the workspace creating a new one (does the workspace call getInstance() ? ).
+ * It seems to work.
+ */
+ public synchronized static BookmarkView getInstance() {
+ return (BookmarkView) QuantumPlugin.getDefault().getView("com.quantum.view.bookmarkview");
+ }
+ /**
+ * Returns the current selected object in the tree. If it's a multiple selection, return the first.
+ * @return
+ */
+ public Object getCurrent() {
+ if (treeViewer == null) return null;
+ return ((StructuredSelection) treeViewer.getSelection())
+ .getFirstElement();
+ }
+ /**
+ * Returns the current selected objects in the tree, in the form of a StructuredSelection.
+ * @return
+ */
+ public StructuredSelection getSelection() {
+ if (treeViewer == null) return null;
+ return ((StructuredSelection) treeViewer.getSelection());
+ }
+
+ /**
+ * Navigates the tree to get the current bookmark (root) of the selected element.
+ * If it's a multiple selection, it takes the first one.
+ * @return
+ */
+ public BookmarkNode getCurrentBookmark() {
+ TreeNode current = (TreeNode) getCurrent();
+ return getRoot(current);
+ }
+
+ private static BookmarkNode getRoot(TreeNode node){
+ if (node == null) return null;
+ if (! (node instanceof TreeNode)) return null;
+ while (!( node instanceof BookmarkNode))
+ {
+ node = (TreeNode) node.getParent();
+ }
+ if (node instanceof BookmarkNode) return (BookmarkNode) node;
+ else return null;
+
+ }
+ public void refresh() {
+ treeViewer.refresh();
+ }
+ public void createPartControl(org.eclipse.swt.widgets.Composite parent) {
+
+ treeViewer = new TreeViewer(
+ parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+ treeViewer.setContentProvider(new BookmarkContentProvider());
+ treeViewer.setLabelProvider(this.labelProvider);
+ BookmarkListNode input = BookmarkListNode.getInstance();
+ treeViewer.setInput(input);
+ initActions();
+
+ input.addPropertyChangeListener(this);
+
+ initializePopUpMenu();
+ fillActionBars();
+
+ treeViewer.addOpenListener(new IOpenListener() {
+ public void open(OpenEvent event) {
+ ActionContext context = new ActionContext(
+ getSelection());
+ BookmarkView.this.actionGroup.setContext(context);
+ IAction action = actionGroup.getOpenAction();
+ if (action != null) {
+ action.run();
+ }
+ }
+ });
+
+ }
+ private void fillActionBars() {
+ Action enableTableSizes = new Action() {
+ public void run() {
+ labelProvider.getLabelDecorationInstructions().setSizeVisible(isChecked());
+ treeViewer.refresh();
+ }
+ };
+ enableTableSizes.setText(Messages.getString("BookmarkView.ShowTableSizes")); //$NON-NLS-1$
+ enableTableSizes.setChecked(false);
+
+ IActionBars actionBars = getViewSite().getActionBars();
+ actionBars.getMenuManager().add(enableTableSizes);
+
+ Action showDatabaseData = new Action() {
+ public void run() {
+ labelProvider.getLabelDecorationInstructions().setDatabaseDataVisible(isChecked());
+ treeViewer.refresh();
+ }
+ };
+ showDatabaseData.setText(Messages.getString("BookmarkView.ShowDatabaseData")); //$NON-NLS-1$
+ showDatabaseData.setChecked(false);
+ actionBars.getMenuManager().add(showDatabaseData);
+
+ this.actionGroup.fillActionBars(actionBars);
+ }
+
+ private void initializePopUpMenu() {
+ MenuManager manager = new MenuManager();
+ manager.setRemoveAllWhenShown(true);
+ manager.addMenuListener(new IMenuListener() {
+ public void menuAboutToShow(IMenuManager mgr) {
+ fillContextMenu(mgr);
+ }
+ });
+ Menu fTextContextMenu =
+ manager.createContextMenu(treeViewer.getControl());
+ treeViewer.getControl().setMenu(fTextContextMenu);
+ // register the menu to the site so that we can allow
+ // actions to be plugged in
+ getSite().registerContextMenu(manager, this.treeViewer);
+ }
+ public void initActions() {
+
+ this.actionGroup = new BookmarkViewActionGroup(this, this.treeViewer);
+
+// openDataEditorAction = new OpenDataEditorAction();
+// openDataEditorAction.setText("Edit Data");
+// openDataEditorAction.setImageDescriptor(
+// QuantumPlugin.getImageDescriptor("greentable.gif")); //$NON-NLS-1$
+// openDataEditorAction.init(this);
+
+ IPreferenceStore store = QuantumPlugin.getDefault().getPreferenceStore();
+ this.customCopyAction1 = new CustomCopyAction(this,1); // 1 is unused, just in case more custom copies are defined
+ this.customCopyAction1.setText(store.getString("customCopyName1")); //$NON-NLS-1$
+ this.customCopyAction1.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("copy.gif")); //$NON-NLS-1$
+ this.customCopyAction2 = new CustomCopyAction(this,2); // 1 is unused, just in case more custom copies are defined
+ this.customCopyAction2.setText(store.getString("customCopyName2")); //$NON-NLS-1$
+ this.customCopyAction2.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("copy.gif")); //$NON-NLS-1$
+ this.customCopyAction3 = new CustomCopyAction(this,3); // 1 is unused, just in case more custom copies are defined
+ this.customCopyAction3.setText(store.getString("customCopyName3")); //$NON-NLS-1$
+ this.customCopyAction3.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("copy.gif")); //$NON-NLS-1$
+
+ extensionVector = new Vector();
+ try {
+ ProcessServiceMembers.process(this, extensionVector);
+ } catch (WorkbenchException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public void dispose(){
+ super.dispose();
+ BookmarkListNode.getInstance().removePropertyChangeListener(this);
+ }
+
+ public Shell getShell() {
+ return getSite().getShell();
+ }
+
+ /**
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ if ("bookmarks".equals(event.getPropertyName())) {
+ refresh();
+ } else if ("name".equals(event.getPropertyName()) &&
+ event.getSource() instanceof BookmarkNode) {
+ refresh();
+ } else if ("connected".equals(event.getPropertyName())) {
+ treeViewer.refresh(event.getSource());
+ if (Boolean.TRUE.equals(event.getNewValue())) {
+ treeViewer.setExpandedState(event.getSource(), true);
+ }
+ } else {
+ treeViewer.refresh(event.getSource());
+ }
+ }
+
+ private void fillContextMenu(IMenuManager mgr) {
+ // TODO: this method is pretty barfy... make it cleaner
+
+ IStructuredSelection selection = getSelection();
+ ActionContext context = new ActionContext(selection);
+ this.actionGroup.setContext(context);
+ this.actionGroup.fillContextMenu(mgr);
+
+ Object sel = getCurrent();
+ // If selection is a BookmarkNode
+ if (sel instanceof EntityNode) {
+ EntityNode entityNode = (EntityNode) sel;
+ if (!entityNode.isSequence()) {
+ mgr.add(new Separator());
+ MenuManager subMenu = new MenuManager(Messages.getString("bookmarkview.customCopyAction"));
+ subMenu.add(customCopyAction1);
+ subMenu.add(customCopyAction2);
+ subMenu.add(customCopyAction3);
+ mgr.add(subMenu);
+
+ MenuManager subMenuExtension = new MenuManager("Extensions");
+ for (int i = 0; i < extensionVector.size(); i++) {
+ ExtensionAction extensionAction = (ExtensionAction) extensionVector.get(i);
+ subMenuExtension.add(extensionAction);
+ }
+ if (extensionVector.size() > 0) mgr.add(subMenuExtension);
+ }
+ } else if (sel instanceof ColumnNode) {
+ MenuManager subMenu = new MenuManager(Messages.getString("bookmarkview.customCopyAction"));
+ subMenu.add(customCopyAction1);
+ subMenu.add(customCopyAction2);
+ subMenu.add(customCopyAction3);
+ mgr.add(subMenu);
+
+ }
+ }
+ /**
+ * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
+ */
+ public void setFocus() {
+ }
+
+
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.util.Iterator;
+
+import com.quantum.QuantumPlugin;
+import com.quantum.actions.AddToQuickListAction;
+import com.quantum.actions.ConnectAction;
+import com.quantum.actions.DeleteAllRowsAction;
+import com.quantum.actions.DeleteBookmarkAction;
+import com.quantum.actions.DisconnectAction;
+import com.quantum.actions.NewBookmarkAction;
+import com.quantum.actions.NextSequenceAction;
+import com.quantum.actions.OpenQueryAction;
+import com.quantum.actions.PrevSequenceAction;
+import com.quantum.actions.RefreshBookmarkAction;
+import com.quantum.actions.RemoveFromQuickListAction;
+import com.quantum.actions.ViewTableAction;
+import com.quantum.actions.ViewTableDetailsAction;
+import com.quantum.model.Bookmark;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.actions.ActionGroup;
+import org.eclipse.ui.actions.ExportResourcesAction;
+import org.eclipse.ui.actions.SelectionListenerAction;
+import org.eclipse.ui.actions.SelectionProviderAction;
+import org.eclipse.ui.dialogs.PropertyDialogAction;
+
+/**
+ * @author BC
+ */
+public class BookmarkViewActionGroup extends ActionGroup
+ implements BookmarkClipboard {
+
+ private Bookmark bookmarkClipboard;
+
+ private Action newBookmarkAction;
+
+ // bookmark node actions
+ private SelectionListenerAction connectAction;
+ private SelectionListenerAction disconnectAction;
+ private SelectionListenerAction deleteBookmarkAction;
+
+ // Query node actions
+ private SelectionListenerAction openQueryAction;
+
+ // Entity node actions
+ private SelectionListenerAction addToQuickListAction;
+ private SelectionListenerAction removeFromQuickListAction;
+ private SelectionListenerAction viewTableAction;
+ private SelectionListenerAction addSchemaAction;
+ private SelectionListenerAction viewTableDetailsAction;
+
+ private SelectionListenerAction nextSequenceAction;
+ private SelectionListenerAction previousSequenceAction;
+
+
+ // other actions
+ private SelectionListenerAction refreshAction;
+ private SelectionListenerAction renameAction;
+
+ private ExportResourcesAction exportAction;
+
+
+ private SelectionProviderAction propertiesAction;
+
+ private SelectionListenerAction copyAction;
+ private SelectionListenerAction pasteAction;
+ private SelectionListenerAction deleteAllRowsAction;
+
+ private IViewPart viewPart;
+
+ public BookmarkViewActionGroup(
+ IViewPart viewPart, ISelectionProvider selectionProvider) {
+ this.viewPart = viewPart;
+
+ this.newBookmarkAction = new NewBookmarkAction(this.viewPart);
+
+ // bookmark actions
+ this.connectAction = new ConnectAction(this.viewPart);
+ this.disconnectAction = new DisconnectAction(this.viewPart);
+ this.deleteBookmarkAction = new DeleteBookmarkAction(this.viewPart);
+
+ // entity actions
+ this.previousSequenceAction = new PrevSequenceAction(this.viewPart);
+ this.nextSequenceAction = new NextSequenceAction(this.viewPart);
+ this.addToQuickListAction = new AddToQuickListAction(this.viewPart);
+ this.removeFromQuickListAction = new RemoveFromQuickListAction(this.viewPart);
+ this.deleteAllRowsAction = new DeleteAllRowsAction(this.viewPart);
+ this.viewTableDetailsAction = new ViewTableDetailsAction(this.viewPart);
+
+ this.openQueryAction = new OpenQueryAction(this.viewPart);
+
+ this.viewTableAction = new ViewTableAction(this.viewPart);
+ this.addSchemaAction = new AddSchemaAction(this.viewPart);
+ this.refreshAction = new RefreshBookmarkAction(this.viewPart);
+ this.renameAction = new RenameAction(this.viewPart);
+ this.copyAction = new CopyAction(this.viewPart, this, selectionProvider);
+ this.pasteAction = new PasteAction(this.viewPart, this, selectionProvider);
+ this.exportAction = new ExportResourcesAction(
+ this.viewPart.getViewSite().getWorkbenchWindow());
+ this.exportAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("export.gif"));
+
+ this.propertiesAction = new PropertyDialogAction(
+ this.viewPart.getSite().getShell(), selectionProvider);
+ }
+
+
+ /**
+ * @see org.eclipse.ui.actions.ActionGroup#fillContextMenu(org.eclipse.jface.action.IMenuManager)
+ */
+ public void fillContextMenu(IMenuManager menu) {
+
+ menu.add(this.newBookmarkAction);
+ menu.add(new Separator());
+
+ if (getStructuredSelection().size() > 0 &&
+ isEverySelectionInstanceof(BookmarkNode.class)) {
+
+ addToMenu(menu, this.connectAction);
+ addToMenu(menu, this.disconnectAction);
+ }
+
+ menu.add(new Separator());
+ menu.add(this.copyAction);
+ // TODO: paste needs to change enablement whenever something is added
+ // to the clipboard
+ addToMenu(menu, this.pasteAction);
+ addToMenu(menu, this.deleteBookmarkAction);
+
+ if (getStructuredSelection().size() == 1 &&
+ isEverySelectionInstanceof(BookmarkNode.class)) {
+
+ addToMenu(menu, this.renameAction);
+ }
+
+ menu.add(new Separator());
+
+ // NOTE: In Eclipse 3.0.0 M6, Export is no longer a sub-class of
+ // SelectionListenerAction.
+ this.exportAction.selectionChanged(getStructuredSelection());
+ menu.add(this.exportAction);
+
+ if (getStructuredSelection().size() == 1 &&
+ isEverySelectionInstanceof(BookmarkNode.class)) {
+
+ menu.add(new Separator());
+ addToMenu(menu, this.addSchemaAction);
+ }
+
+ if (isEverySelectionInstanceof(QueryNode.class)) {
+ if (getStructuredSelection().size() == 1) {
+ addToMenu(menu, this.openQueryAction);
+ }
+ }
+
+ if (getStructuredSelection().size() > 0 &&
+ isEverySelectionInstanceof(EntityNode.class)) {
+
+ menu.add(new Separator());
+
+ if (getStructuredSelection().size() == 1) {
+ if (((EntityNode) getStructuredSelection().getFirstElement()).isSequence()) {
+ addToMenu(menu, this.nextSequenceAction);
+ addToMenu(menu, this.previousSequenceAction);
+ } else {
+ addToMenu(menu, this.viewTableAction);
+ addToMenu(menu, this.deleteAllRowsAction);
+ addToMenu(menu, this.viewTableDetailsAction);
+ }
+ }
+
+ addToMenu(menu, this.addToQuickListAction);
+ addToMenu(menu, this.removeFromQuickListAction);
+ }
+
+ if (getStructuredSelection().size() == 1) {
+ menu.add(new Separator());
+ addToMenu(menu, this.refreshAction);
+ }
+
+ createMarkerForActionsProvidedByOtherPlugins(menu);
+
+ if (getStructuredSelection().size() == 1) {
+ addToMenu(menu, this.propertiesAction);
+ }
+
+ }
+
+ private void addToMenu(IMenuManager menu, SelectionListenerAction action) {
+ action.selectionChanged(getStructuredSelection());
+ menu.add(action);
+ }
+
+ private void addToMenu(IMenuManager menu, SelectionProviderAction action) {
+ action.selectionChanged(getStructuredSelection());
+ menu.add(action);
+ }
+
+
+ private IStructuredSelection getStructuredSelection() {
+ return (IStructuredSelection) getContext().getSelection();
+ }
+
+ private boolean isEverySelectionInstanceof(Class selectedClass) {
+ boolean result = true;
+ IStructuredSelection selection = getStructuredSelection();
+ for (Iterator i = selection.iterator(); result && i.hasNext(); ) {
+ Object object = i.next();
+ result &= selectedClass.isAssignableFrom(object.getClass());
+ }
+
+ return result;
+ }
+
+ public IAction getOpenAction() {
+ if (isEverySelectionInstanceof(BookmarkNode.class)) {
+ this.connectAction.selectionChanged(getStructuredSelection());
+ return this.connectAction.isEnabled() ? this.connectAction : null;
+ } else if (isEverySelectionInstanceof(EntityNode.class)) {
+ this.viewTableAction.selectionChanged(getStructuredSelection());
+ return this.viewTableAction.isEnabled() ? this.viewTableAction : null;
+ } else if (isEverySelectionInstanceof(QueryNode.class)) {
+ this.openQueryAction.selectionChanged(getStructuredSelection());
+ return this.openQueryAction.isEnabled() ? this.openQueryAction : null;
+ } else {
+ return null;
+ }
+ }
+
+ private void createMarkerForActionsProvidedByOtherPlugins(IMenuManager mgr) {
+ mgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+ mgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS + "-end")); //$NON-NLS-1$
+ mgr.add(new Separator());
+ }
+ public void fillActionBars(IActionBars actionBars) {
+ IToolBarManager toolBar = actionBars.getToolBarManager();
+ toolBar.add(this.newBookmarkAction);
+
+ actionBars.setGlobalActionHandler(IWorkbenchActionConstants.COPY, this.copyAction);
+ }
+
+
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.BookmarkClipboard#setBookmark(com.quantum.model.Bookmark)
+ */
+ public void setBookmark(Bookmark bookmark) {
+ this.bookmarkClipboard = bookmark;
+ }
+
+
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.BookmarkClipboard#getBookmark()
+ */
+ public Bookmark getBookmark() {
+ return this.bookmarkClipboard;
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import com.quantum.model.Column;
+
+/**
+ * @author BC
+ */
+public class ColumnNode extends TreeNode {
+
+ private Column column;
+
+ public ColumnNode(TreeNode parent, Column column) {
+ super(parent);
+ this.column = column;
+ }
+
+ public Object[] getChildren() {
+ return BookmarkListNode.EMPTY_ARRAY;
+ }
+
+ public boolean hasChildren() {
+ return false;
+ }
+
+ public String getName() {
+ return this.column.getName();
+ }
+
+ protected String getImageName() {
+ return this.column.isPrimaryKey() ? "keycolumn.gif" : "column.gif";
+ }
+
+ public String getLabelName() {
+ String label = getName() + " : " + this.column.getTypeName(); //$NON-NLS-1$
+ if (this.column.isNumeric()) {
+ if (this.column.getSize() > 0 || this.column.getNumberOfFractionalDigits() > 0) {
+ label += "(" + Integer.toString(this.column.getSize()); //$NON-NLS-1$
+ if (this.column.getNumberOfFractionalDigits() > 0) {
+ label += "," + Integer.toString(this.column.getNumberOfFractionalDigits()); //$NON-NLS-1$
+ }
+ label += ")"; //$NON-NLS-1$
+ }
+ } else if (this.column.getSize() > 0) {
+ label += "(" + Integer.toString(this.column.getSize()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return label;
+ }
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.TreeNode#initializeChildren()
+ */
+ protected void initializeChildren() {
+ }
+ protected boolean isInitialized() {
+ return true;
+ }
+
+ /**
+ * @return
+ */
+ public Column getColumn() {
+ return column;
+ }
+
+}
--- /dev/null
+/*
+ * Created on 11/08/2003
+ *
+ */
+package com.quantum.view.bookmark;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.xml.ModelToXMLConverter;
+import com.quantum.util.QuantumUtil;
+import com.quantum.util.xml.XMLHelper;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+
+final class CopyAction extends SelectionListenerAction {
+ private IViewPart view;
+ private BookmarkClipboard bookmarkClipboard;
+
+ /**
+ * @param BookmarkView
+ */
+ public CopyAction(IViewPart view, BookmarkClipboard bookmarkClipboard,
+ ISelectionProvider selectionProvider) {
+ super(Messages.getString(CopyAction.class.getName() + ".text"));
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("copy.gif"));
+ this.view = view;
+ this.bookmarkClipboard = bookmarkClipboard;
+ selectionProvider.addSelectionChangedListener(this);
+ }
+ public void run() {
+
+ List list = getSelectedNonResources();
+ Object selection = list.get(0);
+
+ if (selection instanceof BookmarkNode) {
+ Bookmark bookmark = ((BookmarkNode) selection).getBookmark();
+ this.bookmarkClipboard.setBookmark(bookmark);
+ QuantumPlugin.getDefault().getSysClip().setContents(
+ new Object[] { bookmark.getName()},
+ new Transfer[] { TextTransfer.getInstance()});
+
+ } else if (selection instanceof EntityNode) {
+ try {
+ Document doc = XMLHelper.createEmptyDocument();
+ Element root = doc.createElement("metadata");
+ doc.appendChild(root);
+ ModelToXMLConverter.getInstance().convert(root, ((EntityNode) selection).getEntity());
+ StringWriter text = new StringWriter();
+ try {
+ XMLHelper.createDOMSerializer(text).serialize(doc);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ String textXml = new String(text.getBuffer());
+ QuantumPlugin.getDefault().getSysClip().setContents(
+ new Object[] { textXml },
+ new Transfer[] { TextTransfer.getInstance()});
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ }
+ } else if (selection instanceof ColumnNode) {
+ String copyText = ""; //$NON-NLS-1$
+ Iterator iter = list.iterator();
+ IPreferenceStore store = QuantumPlugin.getDefault().getPreferenceStore();
+
+ while (iter.hasNext()) {
+ Object current = iter.next();
+ if (current instanceof ColumnNode) {
+ ColumnNode column = (ColumnNode) current;
+ if (column != null) {
+ copyText += column.getName();
+ if (iter.hasNext()) copyText += QuantumUtil.trasposeEscape(store.getString("copyColumnSeparator")); //$NON-NLS-1$
+ }
+ }
+ }
+
+ QuantumPlugin.getDefault().getSysClip().setContents(
+ new Object[] { copyText },
+ new Transfer[] { TextTransfer.getInstance()});
+ }
+
+ }
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.actions.SelectionListenerAction#updateSelection(org.eclipse.jface.viewers.IStructuredSelection)
+ */
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+
+ return enabled;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.view.bookmark;
+
+import com.quantum.model.Column;
+import com.quantum.model.Entity;
+import com.quantum.model.EntityHolder;
+import com.quantum.model.SchemaHolder;
+import com.quantum.model.Table;
+import com.quantum.model.View;
+
+/**
+ * @author BC
+ */
+public class EntityNode extends TreeNode implements EntityHolder {
+
+ private Entity entity;
+ private boolean longFormName;
+
+ public EntityNode(TreeNode parent, Entity entity) {
+ this(parent, entity, false);
+ }
+ public EntityNode(TreeNode parent, Entity entity, boolean longFormName) {
+ super(parent);
+ this.entity = entity;
+ this.longFormName = longFormName;
+
+ if (parent instanceof SchemaHolder) {
+ SchemaHolder schemaHolder = (SchemaHolder) parent;
+ if (!schemaHolder.getSchema().getDisplayName().equals(entity.getSchema())) {
+ this.longFormName = true;
+ }
+ }
+ }
+
+ public Object[] getChildren() {
+ initializeChildren();
+ if (this.children.size() > 0) {
+ return (ColumnNode[]) this.children.toArray(new ColumnNode[this.children.size()]);
+ } else {
+ return BookmarkListNode.EMPTY_ARRAY;
+ }
+ }
+
+ protected synchronized void initializeChildren() {
+ this.children.clear();
+ Column[] columns = this.entity.getColumns();
+ for (int i = 0, length = (columns == null) ? 0 : columns.length;
+ i < length;
+ i++) {
+ this.children.add(new ColumnNode(this, columns[i]));
+ }
+ // TODO: fire property change event
+ }
+
+ public boolean hasChildren() {
+ if (!isSequence()) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public Entity getEntity() {
+ return this.entity;
+ }
+
+ public String getName() {
+ return this.entity.getName();
+ }
+
+ public String getLabelName() {
+ return (this.longFormName) ? this.entity.getCondQualifiedName() : this.entity.getName();
+ }
+
+ public boolean isTable() {
+ return Entity.TABLE_TYPE.equals(this.entity.getType());
+ }
+
+ public boolean isView() {
+ return Entity.VIEW_TYPE.equals(this.entity.getType());
+ }
+
+ public boolean isSequence() {
+ return Entity.SEQUENCE_TYPE.equals(this.entity.getType());
+ }
+
+ protected String getImageName() {
+ if (isSequence()) {
+ return "sequence.gif";
+ } else if (isView()) {
+ return "view.gif";
+ } else {
+ return (this.entity.exists() == null || this.entity.exists().booleanValue())
+ ? "bigtable.gif" : "missingtable.gif";
+ }
+ }
+
+ public String getLabelDecorations(LabelDecorationInstructions instructions) {
+ String decoration = null;
+ if (instructions.isSizeVisible()) {
+ Integer size = getSize();
+ if (size != null) {
+ decoration = ((decoration == null) ? "" : decoration)
+ + "[" + size + "]";
+ }
+ }
+ return decoration;
+ }
+
+ private Integer getSize() {
+ if (isTable()) {
+ return ((Table) this.entity).getSize();
+ } else if (isView()) {
+ return ((View) this.entity).getSize();
+ } else {
+ return null;
+ }
+ }
+
+ public int compareTo(Object o) {
+ if (o instanceof EntityNode) {
+ EntityNode that = (EntityNode) o;
+ return this.entity.getCondQualifiedName().compareTo(
+ that.entity.getCondQualifiedName());
+ } else {
+ return super.compareTo(o);
+ }
+ }
+}
--- /dev/null
+/*
+ * Created on 27/06/2003
+ *
+ */
+package com.quantum.view.bookmark;
+
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import com.quantum.Messages;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+import com.quantum.model.Schema;
+import com.quantum.model.SchemaHolder;
+
+/**
+ * GroupNode represents a level of grouping in the BookmarkView hierarchy
+ * It will have categories like "TABLE", "VIEW" and so on, usually gotten from
+ * the JDBC driver.
+ *
+ * @author panic
+ */
+public class GroupNode extends TreeNode implements Comparable, SchemaHolder {
+ private String type = null;
+ private Schema schema = null;
+
+ public GroupNode(TreeNode parent, Schema schema, String type) {
+ super(parent);
+ this.schema = schema;
+ this.type = type;
+ }
+ public boolean hasChildren() {
+ if (!isInitialized()) {
+ return true;
+ } else {
+ return !this.children.isEmpty();
+ }
+ }
+ public Object[] getChildren() {
+ if (!isInitialized() && getBookmark().isConnected()) {
+ initializeChildren();
+ }
+ return (TreeNode[]) this.children.toArray(new TreeNode[this.children.size()]);
+ }
+ protected void initializeChildren() {
+ try {
+ boolean firstTimeInitialization = !isInitialized();
+ boolean changed = false;
+ Map temp = new HashMap();
+ for (Iterator i = this.children.iterator(); i.hasNext();) {
+ TreeNode treeNode = (TreeNode) i.next();
+ temp.put(treeNode.getName(), treeNode);
+ }
+ this.children.clear();
+
+ Bookmark bookmark = getBookmark();
+ Entity[] entities = bookmark.getEntitiesForSchema(schema, type);
+ for (int i = 0,
+ length = (entities == null) ? 0 : entities.length;
+ i < length;
+ i++) {
+
+ String name = entities[i].getName();
+ EntityNode entityNode = (EntityNode) temp.remove(name);
+ if (entityNode == null) {
+ this.children.add(new EntityNode(this, entities[i]));
+ changed = true;
+ } else {
+ this.children.add(entityNode);
+ }
+ }
+ if (changed && !firstTimeInitialization) {
+ firePropertyChange("children", null, null);
+ }
+ } catch (SQLException e) {
+ }
+ }
+ public String getName() {
+ return Messages.getString(getClass().getName() + "." + this.type);
+ }
+ protected String getImageName() {
+ return "entitygroup.gif"; //$NON-NLS-1$
+ }
+ /**
+ * @return
+ */
+ public Schema getSchema() {
+ return schema;
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+/**
+ * <p>Label decorations are specified for the entire view<p>.
+ *
+ * @author BC
+ */
+public class LabelDecorationInstructions {
+ private boolean sizeVisible = false;
+ private boolean databaseDataVisible = false;
+ /**
+ * @return
+ */
+ public boolean isSizeVisible() {
+ return sizeVisible;
+ }
+
+ /**
+ * @param b
+ */
+ public void setSizeVisible(boolean b) {
+ sizeVisible = b;
+ }
+
+ /**
+ * @return
+ */
+ public boolean isDatabaseDataVisible() {
+ return databaseDataVisible;
+ }
+
+ /**
+ * @param b
+ */
+ public void setDatabaseDataVisible(boolean b) {
+ databaseDataVisible = b;
+ }
+
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkCollection;
+
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+
+final class PasteAction extends SelectionListenerAction {
+ private IViewPart view;
+ private BookmarkClipboard bookmarkClipboard;
+ /**
+ * @param BookmarkView
+ */
+ public PasteAction(IViewPart view, BookmarkClipboard bookmarkClipboard,
+ ISelectionProvider selectionProvider) {
+ super(Messages.getString(PasteAction.class.getName() + ".text"));
+ setImageDescriptor(QuantumPlugin.getImageDescriptor("paste.gif"));
+ this.view = view;
+ selectionProvider.addSelectionChangedListener(this);
+ this.bookmarkClipboard = bookmarkClipboard;
+ }
+ public void run() {
+ if (this.bookmarkClipboard.getBookmark() != null) {
+ Bookmark bookmark = new Bookmark(this.bookmarkClipboard.getBookmark());
+ String copyName = BookmarkCollection.getInstance().getCopyName(bookmark.getName());
+ bookmark.setName(copyName); //$NON-NLS-1$
+ BookmarkCollection.getInstance().addBookmark(bookmark);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.actions.SelectionListenerAction#updateSelection(org.eclipse.jface.viewers.IStructuredSelection)
+ */
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ enabled &= this.bookmarkClipboard.getBookmark() != null;
+ return enabled;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+
+import com.quantum.Messages;
+
+/**
+ * @author BC
+ */
+public class QueryListNode extends TreeNode implements PropertyChangeListener {
+
+ /**
+ * @param parent
+ */
+ public QueryListNode(TreeNode parent) {
+ super(parent);
+ getBookmark().addPropertyChangeListener(this);
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getChildren()
+ */
+ public Object[] getChildren() {
+ initializeChildren();
+ return (TreeNode[]) this.children.toArray(new TreeNode[this.children.size()]);
+ }
+
+ protected void initializeChildren() {
+ this.children.clear();
+ String[] queries = getBookmark().getQueries();
+ for (int i = 0, length = (queries == null) ? 0 : queries.length;
+ i < length;
+ i++) {
+ this.children.add(new QueryNode(this, queries[i]));
+ }
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#hasChildren()
+ */
+ public boolean hasChildren() {
+ return getBookmark().getQueries().length > 0;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getName()
+ */
+ public String getName() {
+ return Messages.getString(getClass().getName() + ".labelName");
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getImageName()
+ */
+ protected String getImageName() {
+ return "group.gif";
+ }
+
+ /**
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ if ("queries".equals(event.getPropertyName())) {
+ firePropertyChange("queries", null, null);
+ }
+ }
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#dispose()
+ */
+ protected void dispose() {
+ getBookmark().removePropertyChangeListener(this);
+ super.dispose();
+ }
+
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import com.quantum.sql.metadata.ObjectMetaData;
+
+public class QueryNode extends TreeNode {
+
+ private String query;
+ private static final int MAX_SIZE = 30;
+
+ public QueryNode(TreeNode parent, String query) {
+ super(parent);
+ this.query = query;
+ }
+
+ public ObjectMetaData getMetaData() {
+ return null; //no metadata implementation for now
+ }
+
+ public String getQuery() {
+ return this.query;
+ }
+
+ public String getName() {
+ String name = this.query.trim();
+ boolean trimmed = false;
+ name = name.replace('\n', ' ');
+
+ if (name.length() > MAX_SIZE) {
+ name = name.substring(0, MAX_SIZE);
+ trimmed = true;
+ }
+ if (trimmed) {
+ name += "...->"; //$NON-NLS-1$
+ }
+ return name;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getChildren()
+ */
+ public Object[] getChildren() {
+ return BookmarkListNode.EMPTY_ARRAY;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#hasChildren()
+ */
+ public boolean hasChildren() {
+ return false;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getImageName()
+ */
+ protected String getImageName() {
+ return "script.gif";
+ }
+
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.TreeNode#initializeChildren()
+ */
+ protected void initializeChildren() {
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+
+import com.quantum.Messages;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+
+/**
+ * <p>A "quick list" is a set of favourite entities that a user may want
+ * to work with without having to sift through the (somtimes lengthy) longer
+ * list of tables.</p>
+ *
+ * @author bcholmes
+ */
+public class QuickListNode extends TreeNode implements PropertyChangeListener {
+
+ private Map children = new Hashtable();
+
+ /**
+ * @param parent
+ */
+ public QuickListNode(BookmarkNode parent) {
+ super(parent);
+
+ Bookmark bookmark = getBookmark();
+ bookmark.addPropertyChangeListener(this);
+ }
+
+ /**
+ * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ if ("quickList".equals(event.getPropertyName())) {
+ initializeChildren();
+ firePropertyChange("quickList", null, null);
+ }
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#hasChildren()
+ */
+ public boolean hasChildren() {
+ return getBookmark().hasQuickList();
+ }
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getImageName()
+ */
+ protected String getImageName() {
+ return "group.gif";
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getChildren()
+ */
+ public Object[] getChildren() {
+ Bookmark bookmark = getBookmark();
+ if (children.isEmpty() && bookmark.hasQuickList()) {
+ initializeChildren();
+ }
+ List list = new ArrayList(this.children.values());
+ Collections.sort(list);
+
+ return (TreeNode[]) list.toArray(new TreeNode[list.size()]);
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getName()
+ */
+ public String getName() {
+ return Messages.getString(QuickListNode.class.getName() + ".labelName");
+ }
+
+ protected synchronized void initializeChildren() {
+ this.children.clear();
+ Entity[] entities = getBookmark().getQuickListEntries();
+ for (int i = 0, length = (entities == null) ? 0 : entities.length;
+ i < length;
+ i++) {
+
+ this.children.put(entities[i].getCondQualifiedName(),
+ new EntityNode(this, entities[i], true));
+ }
+ }
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.TreeNode#isInitialized()
+ */
+ protected boolean isInitialized() {
+ return true;
+ }
+
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import com.quantum.Messages;
+import com.quantum.model.Bookmark;
+
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.actions.SelectionListenerAction;
+
+/**
+ * @author BC
+ */
+public class RenameAction extends SelectionListenerAction {
+
+ private IViewPart viewPart;
+
+ /**
+ * @param text
+ */
+ protected RenameAction(IViewPart viewPart) {
+ super(Messages.getString(RenameAction.class.getName() + ".text"));
+ this.viewPart = viewPart;
+ }
+
+
+
+ /**
+ * @see org.eclipse.ui.actions.SelectionListenerAction#updateSelection(org.eclipse.jface.viewers.IStructuredSelection)
+ */
+ protected boolean updateSelection(IStructuredSelection selection) {
+ boolean enabled = super.updateSelection(selection);
+ return enabled & selection.size() == 1 &
+ selection.getFirstElement() instanceof BookmarkNode;
+ }
+
+ private Bookmark getBookmark() {
+ return ((BookmarkNode) getSelectedNonResources().get(0)).getBookmark();
+ }
+
+ /**
+ * @see org.eclipse.jface.action.IAction#run()
+ */
+ public void run() {
+ InputDialog dialog = new InputDialog(this.viewPart.getSite().getShell(), "Select a new name",
+ "Name: ", getBookmark().getName(), null);
+ int result = dialog.open();
+ if (result == InputDialog.OK) {
+ getBookmark().setName(dialog.getValue());
+ }
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.sql.SQLException;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.NotConnectedException;
+import com.quantum.model.Schema;
+import com.quantum.model.SchemaHolder;
+
+/**
+ * @author BC
+ */
+public class SchemaNode extends TreeNode implements SchemaHolder {
+
+ private Schema schema;
+ /**
+ * @param parent
+ */
+ public SchemaNode(TreeNode parent, Schema schema) {
+ super(parent);
+ this.schema = schema;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getChildren()
+ */
+ public Object[] getChildren() {
+ Bookmark bookmark = getBookmark();
+ if (!bookmark.isConnected()) {
+ return BookmarkListNode.EMPTY_ARRAY;
+ } else {
+ if (this.children.isEmpty()) {
+ initializeChildren();
+ }
+ }
+ return (TreeNode[]) this.children.toArray(new TreeNode[this.children.size()]);
+ }
+
+ protected void initializeChildren() {
+ this.children.clear();
+ Bookmark bookmark = getBookmark();
+ try {
+ String[] types = bookmark.getDatabase().getEntityTypes();
+ for (int i = 0, length = (types == null) ? 0 : types.length;
+ i < length;
+ i++) {
+ this.children.add(new GroupNode(this, this.schema, types[i]));
+ }
+ } catch (NotConnectedException e) {
+ } catch (SQLException e) {
+ }
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#hasChildren()
+ */
+ public boolean hasChildren() {
+ return getBookmark().isConnected();
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getName()
+ */
+ public String getName() {
+ return this.schema.getDisplayName();
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getImageName()
+ */
+ protected String getImageName() {
+ return this.schema.isDefault() ? "user.gif" : "schema.gif";
+ }
+
+ /**
+ * @see com.quantum.model.SchemaHolder#getSchema()
+ */
+ public Schema getSchema() {
+ return this.schema;
+ }
+}
--- /dev/null
+package com.quantum.view.bookmark;
+
+import java.beans.PropertyChangeEvent;
+import java.util.Iterator;
+import java.util.Vector;
+
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkHolder;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Base class for all nodes of the internal tree of data. Basically allows navigation.
+ * @author root
+ */
+public abstract class TreeNode
+ implements BookmarkHolder, Comparable, IAdaptable {
+
+ private TreeNode parent = null;
+ protected Vector children = new Vector();
+ private boolean disposed = false;
+
+ public TreeNode(TreeNode parent) {
+ this.parent = parent;
+ }
+
+ public abstract Object[] getChildren();
+ public TreeNode getParent() {
+ return this.parent;
+ }
+ public abstract boolean hasChildren();
+ public abstract String getName();
+
+ public Bookmark getBookmark() {
+ return getParent().getBookmark();
+ }
+
+ public String getLabelName() {
+ return getName();
+ }
+
+ /**
+ * @return an Image object to appear in the view, null if not found
+ */
+ public Image getImage() {
+ return QuantumPlugin.getImage(getImageName());
+ }
+
+ /**
+ * @return
+ */
+ protected abstract String getImageName();
+
+
+ /**
+ * @see java.lang.Comparable#compareTo(java.lang.Object)
+ */
+ public int compareTo(Object object) {
+ TreeNode that = (TreeNode) object;
+ return this.getLabelName().compareTo(that.getLabelName());
+ }
+
+ public String toString() {
+ return getLabelName();
+ }
+
+ public String getLabelDecorations(LabelDecorationInstructions labelDecorationInstructions) {
+ return null;
+ }
+ /**
+ * @param propertyName
+ * @param oldValue
+ * @param newValue
+ */
+ protected void firePropertyChange(
+ String propertyName,
+ Object oldValue,
+ Object newValue) {
+
+ firePropertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue));
+ }
+
+ /**
+ * @param propertyName
+ * @param oldValue
+ * @param newValue
+ */
+ protected void firePropertyChange(PropertyChangeEvent event) {
+ TreeNode parent = getParent();
+ if (parent != null && !this.disposed) {
+ parent.firePropertyChange(event);
+ }
+ }
+
+ protected void dispose() {
+ this.disposed = true;
+ removeAllChildren();
+ }
+ protected void removeAllChildren() {
+ for (Iterator i = this.children.iterator(); i.hasNext();) {
+ TreeNode element = (TreeNode) i.next();
+ element.dispose();
+ }
+ }
+
+ protected boolean isInitialized() {
+ return !this.children.isEmpty();
+ }
+
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
+ protected abstract void initializeChildren();
+ public void reload() {
+ if (isInitialized()) {
+ initializeChildren();
+ for (Iterator i = this.children.iterator(); i.hasNext(); ) {
+ ((TreeNode) i.next()).reload();
+ }
+ }
+ }
+}
--- /dev/null
+package com.quantum.view.subset;
+
+import java.sql.SQLException;
+
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkCollection;
+import com.quantum.model.Column;
+import com.quantum.model.Entity;
+import com.quantum.model.Index;
+import com.quantum.model.Schema;
+
+/**
+ * @author BC
+ */
+public class EntitySubset implements Entity {
+
+ private String name;
+ private String schema;
+ private String bookmarkName;
+
+ public EntitySubset(String name, String schema, String bookmarkName) {
+ this.name = name;
+ this.schema = schema;
+ this.bookmarkName = bookmarkName;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public String getSchema() {
+ return schema;
+ }
+
+ public String getType() {
+ return null;
+ }
+
+ public Column[] getColumns() {
+ // TODO: limit the columns
+ Entity relatedEntity = getEntityFromBookmark();
+ if (relatedEntity != null) {
+ Column[] columns = relatedEntity.getColumns();
+ return columns;
+ } else {
+ return null;
+ }
+ }
+
+ public Index[] getIndexes() {
+ return new Index[0];
+ }
+
+ public Column getColumn(String columnName) {
+ Entity relatedEntity = getEntityFromBookmark();
+ return relatedEntity == null
+ ? null : relatedEntity.getColumn(columnName);
+ }
+
+ public String getCondQualifiedName() {
+ return this.schema + "." + this.name;
+ }
+
+ public Boolean exists() {
+ return null;
+ }
+
+ public Bookmark getBookmark() {
+ return BookmarkCollection.getInstance().find(this.bookmarkName);
+ }
+
+ private Entity getEntityFromBookmark() {
+ try {
+ return getBookmark().getEntity(
+ new Schema(schema), name);
+ } catch (SQLException e) {
+ return null;
+ }
+ }
+ /**
+ * @see com.quantum.model.Entity#getQuotedTableName()
+ */
+ public String getQuotedTableName() {
+ return getBookmark().getAdapter().filterTableName(getCondQualifiedName());
+ }
+}
--- /dev/null
+package com.quantum.view.subset;
+
+import com.quantum.IQuantumConstants;
+import com.quantum.Messages;
+import com.quantum.model.Entity;
+import com.quantum.model.EntityHolder;
+import com.quantum.sql.metadata.MetaDataXMLInterface;
+import com.quantum.sql.metadata.ObjectMetaData;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Defines a node for the Subset. It contains an editable ObjectMetaData
+ * where you can erase columns you are not interested in.
+ * @author jparrai
+ *
+ */
+public class ObjectNode implements Comparable, EntityHolder {
+ private SubsetNode parent = null;
+ private ObjectMetaData metadata = null;
+ private int order = 0;
+ private Entity entity;
+
+ public ObjectNode(SubsetNode parent, ObjectMetaData metadata, String bookmark, String name, String schema) {
+ this.parent = parent;
+ this.metadata = metadata;
+ this.entity = new EntitySubset(name, schema, bookmark);
+ }
+
+ public ObjectNode(){
+ }
+ public String getType(){
+ return IQuantumConstants.View;
+ }
+
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.TreeNode#getChildren()
+ * We consider the columns of the metadata to be the children.
+ */
+ public Object[] getChildren() {
+// if (metadata != null && ColumnMetaData.getColumnsMetaDataNode(metadata, this) != null) {
+// return ColumnMetaData.getColumnsMetaDataNode(metadata, this).toArray();
+// } else {
+ return SubsetRoot.EMPTY_ARRAY;
+// }
+ }
+
+ public Object getParent() {
+ return parent;
+ }
+
+ public boolean hasChildren() {
+// if (metadata == null) return false;
+// return (ColumnMetaData.getColumnsMetaDataNode(metadata, this) != null &&
+// ColumnMetaData.getColumnsMetaDataNode(metadata, this).size() > 0);
+ return false;
+ }
+
+ public String getName() {
+ return this.entity.getName();
+ }
+
+ public String toString() {
+ return getName();
+ }
+
+ public int compareTo(Object o) {
+ if (o instanceof ObjectNode) {
+ ObjectNode node = (ObjectNode) o;
+ if (node.getOrder() > getOrder()) return -1;
+ if (node.getOrder() < getOrder()) return 1;
+ // If the order is the same, we use alphabetical order
+ return getEntity().getCondQualifiedName().compareTo(
+ node.getEntity().getCondQualifiedName());
+ } else throw new ClassCastException();
+ }
+
+ public void setObjectMetadata(ObjectMetaData metadata) {
+ this.metadata = metadata;
+ }
+ /**
+ * @return
+ */
+ public ObjectMetaData getMetaData() {
+ return metadata;
+ }
+
+ /**
+ * @return The order of this ObjectNode inside the SubsetNode
+ */
+ public int getOrder() {
+ return order;
+ }
+ /**
+ * Sets an ordering (inside the SubsetNode) to the ObjectNode
+ * @param i
+ */
+ public void setOrder(int i) {
+ order = i;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof ObjectNode)) return false;
+ return (getEntity().getCondQualifiedName().equals(
+ ((ObjectNode) obj).getEntity().getCondQualifiedName()));
+ }
+
+ /**
+ * Imports one ObjectNode from an XMLDocument. There must be a tag for the Table Name, another for the Bookmark
+ * name and other for the metadata. The complement function is exportXML()
+ * @param root Document to get the data from
+ * @param parent The SubsetNode to which to add the new ObjectNode
+ * @return The newly created ObjectNode, or null if some error.
+ */
+ public static ObjectNode importXML(Element root, SubsetNode parent){
+ // Get the name tag value into objName
+ String objName = MetaDataXMLInterface.getElementText(root, Messages.getString("ExportXMLAction.TableName")); //$NON-NLS-1$
+ String objSchema = MetaDataXMLInterface.getElementText(root, Messages.getString("ExportXMLAction.SchemaName")); //$NON-NLS-1$
+ if (objName == "") return null; //$NON-NLS-1$
+ // Get the bookmark tag value into objName
+ String bookmarkName = MetaDataXMLInterface.getElementText(root, Messages.getString("ExportXMLAction.BookmarkName")); //$NON-NLS-1$
+ if (bookmarkName == "") return null; //$NON-NLS-1$
+ ObjectMetaData metadata = new ObjectMetaData();
+ // The rest of the tags go to be the metadata
+ MetaDataXMLInterface.xmlToMetaData(metadata, root);
+ // We can finally create the new ObjectNode with the collected data
+ ObjectNode objectNode = new ObjectNode(parent, metadata, bookmarkName, objName, objSchema);
+ return objectNode;
+ }
+
+ /**
+ * Exports an ObjectNode to an XMLDocument. The complement function is importXML()
+ * @param root Document to write the XML tags to
+ */
+ public void exportXML(Element root){
+ Document doc = root.getOwnerDocument();
+ Element sub = (Element) root.appendChild(doc.createElement(Messages.getString("ExportXMLAction.Table"))); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(sub,Messages.getString("ExportXMLAction.TableName"), getEntity().getName()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(sub,Messages.getString("ExportXMLAction.SchemaName"), getEntity().getSchema()); //$NON-NLS-1$
+ MetaDataXMLInterface.createElementText(sub,Messages.getString("ExportXMLAction.BookmarkName"), getEntity().getBookmark().getName()); //$NON-NLS-1$
+ if (this.metadata != null)
+ MetaDataXMLInterface.metaDataToXML(this.metadata, doc, sub);
+ }
+
+ /**
+ * Generates a query with all the columns in the metadata of the ObjectNode.
+ * "SELECT *" would not be valid because you can have less columns in the ObjectNode than in the table or view.
+ * @return String with the Query
+ */
+ public String getQuery() {
+ String result = new String(""); //$NON-NLS-1$
+ result = "SELECT " + metadata.getColumnsString() + " FROM " + getEntity().getCondQualifiedName(); //$NON-NLS-1$ //$NON-NLS-2$
+ return result;
+ }
+
+ /**
+ * @see com.quantum.model.EntityHolder#getEntity()
+ */
+ public Entity getEntity() {
+ return this.entity;
+ }
+
+}
--- /dev/null
+package com.quantum.view.subset;
+
+import java.util.Vector;
+
+import com.quantum.Messages;
+import com.quantum.sql.metadata.MetaDataXMLInterface;
+import com.quantum.view.bookmark.ColumnNode;
+import com.quantum.view.bookmark.TreeNode;
+
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+public class SubsetContentProvider implements ITreeContentProvider {
+ private Vector subsets = new Vector();
+ private static SubsetContentProvider instance = null;
+ private boolean hasChanged = false;
+
+ /**
+ * Singleton accessor
+ */
+ public static synchronized SubsetContentProvider getInstance() {
+ if (instance == null) {
+ instance = new SubsetContentProvider();
+ }
+ return instance;
+ }
+
+ private SubsetContentProvider() {
+ }
+
+ public void exportXML(Element root) {
+ System.out.println("Subsets: Saving to Element"); //$NON-NLS-1$
+ Element subsetRoot = MetaDataXMLInterface.createElementText(root,Messages.getString("ExportXMLAction.Subsets"), ""); //$NON-NLS-1$ //$NON-NLS-2$
+ for (int i = 0; i < subsets.size(); i++) {
+ SubsetNode current = (SubsetNode) subsets.get(i);
+ current.exportXML(subsetRoot);
+ }
+ }
+
+ /**
+ * Imports the data from an XML file to the tree. Does not set the tree to
+ * changed because it's usually invoked from the initial import routine.
+ * @param root
+ */
+ public void importXML(Element root){
+ System.out.println("Bookmarks: Loading from Element"); //$NON-NLS-1$
+ Vector newSubsets = new Vector();
+ NodeList nodes = root.getElementsByTagName(Messages.getString("ExportXMLAction.Subset")); //$NON-NLS-1$
+ for (int i = 0; i < nodes.getLength(); i++) {
+ SubsetNode subset = new SubsetNode();
+ Element node = (Element) nodes.item(i);
+ subset.importXML(node,true);
+ newSubsets.add(subset);
+ }
+ subsets = newSubsets;
+ }
+
+
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement.equals(SubsetRoot.ROOT)) {
+ return subsets.toArray();
+ } else if (parentElement instanceof TreeNode) {
+ TreeNode node = (TreeNode) parentElement;
+ return node.getChildren();
+ }
+ return SubsetRoot.EMPTY_ARRAY;
+ }
+
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
+
+ public Object getParent(Object element) {
+ if (element.equals(SubsetRoot.ROOT)) {
+ return null;
+ } else if (element instanceof TreeNode) {
+ TreeNode node = (TreeNode) element;
+ return node.getParent();
+ }
+ return null;
+ }
+
+ public boolean hasChildren(Object element) {
+ if (element.equals(SubsetRoot.ROOT)) {
+ return true;
+ } else if (element instanceof TreeNode) {
+ TreeNode node = (TreeNode) element;
+ return node.hasChildren();
+ }
+ return false;
+ }
+
+ public void setChildren(SubsetNode b, Vector tables) {
+ b.setChildren(tables);
+ }
+
+ public void addSubset(SubsetNode b) {
+ hasChanged = true;
+ if (!subsets.contains(b)) {
+ subsets.addElement(b);
+ }
+ }
+ public void removeSubset(SubsetNode b) {
+ hasChanged = true;
+ if (subsets.contains(b)) {
+ subsets.removeElement(b);
+ }
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+
+ public void dispose() {
+ }
+
+ public boolean hasChanged() {
+ return hasChanged;
+ }
+
+ public int getSize() {
+ return subsets.size();
+ }
+
+ /**
+ * @param b
+ */
+ public void setHasChanged(boolean b) {
+ hasChanged = b;
+ }
+
+ /**
+ * @param column
+ */
+ public void deleteColumn(ColumnNode column) {
+ // TODO: reinstate this
+// TreeNode node = (TreeNode) column.getParent();
+// if (!(node instanceof HasMetaData)) return;
+// ObjectMetaData metadata = ((HasMetaData)node).getMetaData();
+// if (metadata == null) return;
+// metadata.dropColumn(column.getName());
+// setHasChanged(true);
+//
+ }
+
+ /**
+ * @param object
+ */
+ public void deleteObject(ObjectNode object) {
+ SubsetNode node = (SubsetNode) object.getParent();
+ if (!(node instanceof SubsetNode)) return;
+ node.remove(object);
+ setHasChanged(true);
+
+ }
+
+}
--- /dev/null
+package com.quantum.view.subset;
+
+import com.quantum.view.bookmark.TreeNode;
+
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * @author root
+ *
+ * Implements the ILabelProvider for the Bookmarks.
+ */
+public class SubsetLabelProvider implements ILabelProvider {
+ /**
+ * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ if (element instanceof TreeNode) {
+ return ((TreeNode) element).getImage();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+ if (element instanceof TreeNode) {
+ return ((TreeNode) element).getLabelName();
+ } else {
+ return element.toString();
+ }
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(ILabelProviderListener)
+ */
+ public void addListener(ILabelProviderListener listener) {
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(Object, String)
+ */
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(ILabelProviderListener)
+ */
+ public void removeListener(ILabelProviderListener listener) {
+ }
+}
--- /dev/null
+package com.quantum.view.subset;
+
+import java.util.Collections;
+import java.util.Vector;
+
+import com.quantum.Messages;
+import com.quantum.sql.metadata.MetaDataXMLInterface;
+import com.quantum.view.bookmark.TreeNode;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+public class SubsetNode extends TreeNode {
+ private String name = null;
+ private Vector children = new Vector();
+
+ public SubsetNode(SubsetNode param) {
+ super(param.getParent());
+ name = param.name;
+ children.addAll(param.children);
+ }
+
+ public SubsetNode() {
+ super(SubsetRoot.ROOT);
+ }
+
+ public SubsetNode(String name) {
+ super(SubsetRoot.ROOT);
+ this.name = name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName(){
+ return name;
+ }
+
+ public Object[] getChildren() {
+ return children.toArray();
+ }
+
+ public boolean hasChildren() {
+ if (children != null && children.size() > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public void setChildren(Vector children) {
+ for (int i = 0; i < children.size(); i++) {
+ Object obj = children.elementAt(i);
+ isValid(obj);
+ }
+ Collections.sort(children);
+ this.children = children;
+ }
+
+ public void isValid(Object child) {
+ boolean valid = false;
+ if (child instanceof ObjectNode ) {
+ valid = true;
+ }
+ if (!valid) {
+ throw new RuntimeException("Invalid SubsetNode child: " + child.getClass().getName()); //$NON-NLS-1$
+ }
+ }
+
+
+ /**
+ * Finds a child of the SubsetNode with the said name
+ * @param name
+ * @return the TreeNode found. null if none
+ */
+ public TreeNode find(String name){
+ for (int i = 0; i < children.size(); i++) {
+ Object obj = children.elementAt(i);
+ if (obj instanceof TreeNode){
+ TreeNode node = (TreeNode) obj;
+ if (name.equals(node.getName())) return node;
+ }
+ }
+ return null;
+ }
+
+ public boolean add(ObjectNode object){
+ if (children.indexOf(object) >= 0) return false;
+ children.add(object);
+ return true;
+ }
+
+ public boolean addReplace(ObjectNode object){
+ children.remove(object);
+ return add(object);
+ }
+
+ public boolean remove(ObjectNode object){
+ return children.remove(object);
+ }
+
+ public void exportXML(Element root) {
+ Element sub = MetaDataXMLInterface.createElementText(root,Messages.getString("ExportXMLAction.Subset"), ""); //$NON-NLS-1$ //$NON-NLS-2$
+ MetaDataXMLInterface.createElementText(sub,Messages.getString("ExportXMLAction.SubsetName"), getName()); //$NON-NLS-1$
+ for (int i = 0; i < children.size(); i++) {
+ Object obj = children.elementAt(i);
+ if (obj instanceof ObjectNode){
+ ((ObjectNode) obj).exportXML(sub);
+ }
+ }
+
+ }
+
+ /**
+ * Imports a set of XML tags (parsed into a XMLDocument) into a Subset
+ * @param root Document to get the data from
+ * @param replace True if you want to replace already-existing elements with the same name, false if not
+ */
+ public void importXML(Element root, boolean replace) {
+ if (replace) {
+ String name = MetaDataXMLInterface.getElementText(root, Messages.getString("ExportXMLAction.SubsetName")); //$NON-NLS-1$
+ if (name == "") return; //$NON-NLS-1$
+ setName(name);
+ }
+ importElementXML(root, replace, Messages.getString("ExportXMLAction.Table")); //$NON-NLS-1$
+ importElementXML(root, replace, Messages.getString("ExportXMLAction.View")); //$NON-NLS-1$
+
+ }
+
+
+ /**
+ *
+ * Imports one type of element from a XMLDocument (possibly a part of one) into a Subset
+ * @param root Document to get the data from
+ * @param replace True if you want to replace already-existing elements with the same name, false if not
+ * @param type The type of element to import, has to correspond with the XML tag
+ */
+ private void importElementXML(Element root, boolean replace, String type) {
+ // We get all the tags named as the type
+ NodeList tables = root.getElementsByTagName(type);
+ for (int i = 0; i < tables.getLength(); i++) {
+ Element table = (Element) tables.item(i);
+ ObjectNode objectNode = ObjectNode.importXML(table, this);
+ if (replace)addReplace(objectNode);
+ else add(objectNode);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.TreeNode#getImageName()
+ */
+ protected String getImageName() {
+ return "subset.gif";
+ }
+
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.TreeNode#initializeChildren()
+ */
+ protected void initializeChildren() {
+ }
+
+}
--- /dev/null
+package com.quantum.view.subset;
+
+import com.quantum.view.bookmark.TreeNode;
+
+
+/**
+ * @author root
+ */
+public final class SubsetRoot extends TreeNode {
+ public final static SubsetRoot ROOT = new SubsetRoot();
+ public final static TreeNode[] EMPTY_ARRAY = new TreeNode[0];
+
+ private SubsetRoot() {
+ super(null);
+ }
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#getChildren()
+ */
+ public Object[] getChildren() {
+ return EMPTY_ARRAY;
+ }
+
+ /**
+ * @see com.quantum.view.bookmark.TreeNode#hasChildren()
+ */
+ public boolean hasChildren() {
+ return true;
+ }
+
+ public String getName() {
+ return "ROOT"; //$NON-NLS-1$
+ }
+ protected String getImageName() {
+ return null;
+ }
+ /* (non-Javadoc)
+ * @see com.quantum.view.bookmark.TreeNode#initializeChildren()
+ */
+ protected void initializeChildren() {
+ }
+}
--- /dev/null
+package com.quantum.view.subset;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.Vector;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.actions.CustomCopyAction;
+import com.quantum.actions.DeleteColumnAction;
+import com.quantum.actions.DeleteObjectAction;
+import com.quantum.actions.DeleteSubsetAction;
+import com.quantum.actions.ExportXMLAction;
+import com.quantum.actions.NewSubsetAction;
+import com.quantum.actions.ViewTableAction;
+import com.quantum.view.bookmark.ColumnNode;
+import com.quantum.view.bookmark.TreeNode;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IMenuListener;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.part.ViewPart;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * @author panic
+ *
+ * View for subsets
+ * */
+public class SubsetView extends ViewPart {
+
+ private SubsetContentProvider provider = SubsetContentProvider.getInstance();
+ private NewSubsetAction newSubsetAction;
+ private DeleteSubsetAction deleteSubsetAction;
+ private DeleteObjectAction deleteObjectAction;
+ private DeleteColumnAction deleteColumnAction;
+ private CustomCopyAction customCopyAction;
+
+ private ViewTableAction viewTableAction;
+ private ExportXMLAction exportXMLAction;
+ private static SubsetView instance = null;
+ private TreeViewer treeViewer;
+ private Label status;
+ public synchronized static SubsetView getInstance() {
+ return instance;
+ }
+ /**
+ * Returns the current selected object in the tree. If it's a multiple selection, return the first.
+ * @return
+ */
+ public Object getCurrent() {
+ if (treeViewer == null) return null;
+ return ((StructuredSelection) treeViewer.getSelection())
+ .getFirstElement();
+ }
+ /**
+ * Returns the current selected objects in the tree, in the form of a StructuredSelection.
+ * @return
+ */
+ public StructuredSelection getSelection() {
+ if (treeViewer == null) return null;
+ return ((StructuredSelection) treeViewer.getSelection());
+ }
+
+ /**
+ * Navigates the tree to get the current subset (root) of the selected element.
+ * If it's a multiple selection, it takes the first one.
+ * @return
+ */
+ public SubsetNode getCurrentSubset() {
+ TreeNode current = (TreeNode) getCurrent();
+
+ return getRoot(current);
+ }
+
+ /**
+ * Navigates a given TreeNode till finds a SubsetNode
+ * @param node
+ * @return
+ */
+ private static SubsetNode getRoot(TreeNode node){
+ while (!( node instanceof SubsetNode))
+ {
+ node = (TreeNode) node.getParent();
+ }
+ return (SubsetNode) node;
+
+ }
+
+
+ /**
+ * Deletes the current node (first selected) in the tree
+ */
+ public void deleteCurrent() {
+ provider.removeSubset(getCurrentSubset());
+ treeViewer.refresh();
+ }
+
+ public void refreshSubsetData(){
+ //if (treeViewer == null) return;
+ //SubsetContentProvider provider = (SubsetContentProvider) treeViewer.getContentProvider();
+ //Object[] objects = provider.getElements(Root.ROOT);
+ //for (int i = 0; i < objects.length; i++) {
+ //SubsetNode current = (SubsetNode) objects[i];
+
+ //}
+ }
+
+ public void expandCurrent(SubsetNode node) {
+ treeViewer.setExpandedState(node, true);
+ treeViewer.refresh(node, false);
+ }
+ public void refresh() {
+ treeViewer.refresh();
+ }
+ public void disconnect() {
+ }
+
+ public void createPartControl(org.eclipse.swt.widgets.Composite parent) {
+ instance = this;
+ initActions();
+ Composite main = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.horizontalSpacing = 0;
+ layout.verticalSpacing = 0;
+ main.setLayout(layout);
+
+
+ treeViewer = new TreeViewer(main);
+ treeViewer.setContentProvider(provider);
+ treeViewer.setLabelProvider(new SubsetLabelProvider());
+ treeViewer.setInput(SubsetRoot.ROOT);
+ MenuManager manager = new MenuManager();
+ manager.setRemoveAllWhenShown(true);
+ Menu fTextContextMenu =
+ manager.createContextMenu(treeViewer.getControl());
+ treeViewer.getControl().setMenu(fTextContextMenu);
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+ public void doubleClick(DoubleClickEvent event) {
+ Object sel = getCurrent();
+ if (sel instanceof ObjectNode) {
+ viewTableAction.run();
+ }
+ }
+ });
+
+ manager.addMenuListener(new IMenuListener() {
+ public void menuAboutToShow(IMenuManager mgr) {
+ Object sel = getCurrent();
+ if (sel instanceof SubsetNode) {
+ mgr.add(deleteSubsetAction);
+ deleteSubsetAction.setText(Messages.getString("SubsetView.Delete")); //$NON-NLS-1$
+ deleteSubsetAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("delete.gif")); //$NON-NLS-1$
+ mgr.add(pasteAction);
+ pasteAction.setText(Messages.getString("SubsetView.Paste")); //$NON-NLS-1$
+ pasteAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("paste.gif")); //$NON-NLS-1$
+ mgr.add(exportXMLAction);
+ exportXMLAction.setText(Messages.getString("bookmarkview.exportXML")); //$NON-NLS-1$
+ exportXMLAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("xml.gif")); //$NON-NLS-1$
+
+ } else if (sel instanceof ObjectNode) {
+ mgr.add(deleteObjectAction);
+ deleteObjectAction.setText(Messages.getString("SubsetView.Delete")); //$NON-NLS-1$
+ deleteObjectAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("delete.gif")); //$NON-NLS-1$
+ mgr.add(viewTableAction);
+ viewTableAction.setText(Messages.getString("bookmarkview.viewTable")); //$NON-NLS-1$
+ viewTableAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("table.gif")); //$NON-NLS-1$
+ mgr.add(exportXMLAction);
+ exportXMLAction.setText(Messages.getString("bookmarkview.exportXML")); //$NON-NLS-1$
+ exportXMLAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("xml.gif")); //$NON-NLS-1$
+ customCopyAction.selectionChanged(
+ (IStructuredSelection) treeViewer.getSelection());
+ mgr.add(customCopyAction);
+ } else if (sel instanceof ColumnNode){
+ mgr.add(deleteColumnAction);
+ deleteColumnAction.setText(Messages.getString("SubsetView.Delete")); //$NON-NLS-1$
+ deleteColumnAction.setImageDescriptor(QuantumPlugin.getImageDescriptor("delete.gif")); //$NON-NLS-1$
+ customCopyAction.selectionChanged(
+ (IStructuredSelection) treeViewer.getSelection());
+ mgr.add(customCopyAction);
+
+ } else {
+ mgr.add(newSubsetAction);
+ }
+ }
+ });
+
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ treeViewer.getControl().setLayoutData(gridData);
+ status = new Label(main, SWT.NONE);
+ gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ status.setLayoutData(gridData);
+
+ IActionBars bars = getViewSite().getActionBars();
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.PASTE, pasteAction);
+ bars.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, deleteSubsetAction);
+
+ IToolBarManager toolBar = getViewSite().getActionBars().getToolBarManager();
+ toolBar.add(newSubsetAction);
+
+ status.setText(Messages.getString("bookmarkview.done")); //$NON-NLS-1$
+ }
+ public void initActions() {
+ newSubsetAction = new NewSubsetAction();
+ newSubsetAction.setText("New Subset"); //$NON-NLS-1$
+ newSubsetAction.setToolTipText(Messages.getString("SubsetView.CreatesANewEmptySubset")); //$NON-NLS-1$
+ newSubsetAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("subset.gif")); //$NON-NLS-1$
+ newSubsetAction.init(this);
+ deleteColumnAction = new DeleteColumnAction();
+ deleteColumnAction.setText("Delete Column"); //$NON-NLS-1$
+ deleteColumnAction.setToolTipText(Messages.getString("SubsetView.DeletesTheSelectedColumns")); //$NON-NLS-1$
+ deleteColumnAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("delete.gif")); //$NON-NLS-1$
+ deleteColumnAction.init(this);
+ deleteObjectAction = new DeleteObjectAction();
+ deleteObjectAction.setText("Delete Object"); //$NON-NLS-1$
+ deleteObjectAction.setToolTipText(Messages.getString("SubsetView.DeletesTheSelectedObject")); //$NON-NLS-1$
+ deleteObjectAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("delete.gif")); //$NON-NLS-1$
+ deleteObjectAction.init(this);
+ deleteSubsetAction = new DeleteSubsetAction();
+ deleteSubsetAction.setText("Delete Subset"); //$NON-NLS-1$
+ deleteSubsetAction.setToolTipText(Messages.getString("SubsetView.DeletesTheSelectedSubset")); //$NON-NLS-1$
+ deleteSubsetAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("delete.gif")); //$NON-NLS-1$
+ deleteSubsetAction.init(this);
+// viewTableAction = new ViewTableAction();
+// viewTableAction.setText(Messages.getString("bookmarkview.viewTable")); //$NON-NLS-1$
+// viewTableAction.setImageDescriptor(
+// QuantumPlugin.getImageDescriptor("table.gif")); //$NON-NLS-1$
+// viewTableAction.init(this);
+ exportXMLAction = new ExportXMLAction();
+ exportXMLAction.setText(Messages.getString("bookmarkview.exportXML")); //$NON-NLS-1$
+ exportXMLAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("table.gif")); //$NON-NLS-1$
+ exportXMLAction.init(this);
+
+ this.customCopyAction = new CustomCopyAction(this,1); // 1 is unused, just in case more custom copies are defined
+ this.customCopyAction.setText(Messages.getString("bookmarkview.customCopyAction")); //$NON-NLS-1$
+ this.customCopyAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("copy.gif")); //$NON-NLS-1$
+
+
+
+ }
+ public void setFocus() {
+ }
+
+ private Action pasteAction = new Action() {
+ public void run() {
+ Object sel = getCurrent();
+ if (sel == null) return;
+ if (!(sel instanceof SubsetNode)) return;
+
+ SubsetNode subset = (SubsetNode) sel;
+
+ TextTransfer transfer = TextTransfer.getInstance();
+ String xmlMetaData = (String) QuantumPlugin.getDefault().getSysClip().getContents(transfer);
+ StringReader text = new StringReader(xmlMetaData);
+ InputSource source = new InputSource(text);
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder parser;
+ Document doc;
+ try {
+ parser = factory.newDocumentBuilder();
+ doc = parser.parse(source);
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ return;
+ } catch (SAXException e) {
+ e.printStackTrace();
+ return;
+ } catch (IOException e) {
+ e.printStackTrace();
+ return;
+ }
+ Element root = doc.getDocumentElement();
+ subset.importXML(root, false);
+ treeViewer.refresh();
+ provider.setHasChanged(true);
+
+ }
+ };
+
+ public void addNewSubset(SubsetNode subset) {
+ provider.addSubset(subset);
+ treeViewer.refresh();
+ }
+ public void setStatus(String text) {
+ status.setText(text);
+ }
+ public void dispose(){
+ super.dispose();
+ }
+
+ /**
+ * Returs a Vector with all the elements of the treeViewer
+ * @return
+ */
+ public Vector getElements(){
+ Vector result = new Vector();
+ if (treeViewer == null) return result;
+ SubsetContentProvider provider = (SubsetContentProvider) treeViewer.getContentProvider();
+ Object[] objects = provider.getElements(SubsetRoot.ROOT);
+ for (int i = 0; i < objects.length; i++) {
+ SubsetNode current = (SubsetNode) objects[i];
+ result.add(current);
+ }
+ return result;
+ }
+
+ public void deleteColumn (ColumnNode column){
+ provider.deleteColumn(column);
+ treeViewer.refresh();
+ }
+
+ public void deleteObject (ObjectNode object){
+ provider.deleteObject(object);
+ treeViewer.refresh();
+ }
+
+
+}
--- /dev/null
+package com.quantum.view.tableview;
+
+public class DefaultSizes {
+ public static int PAGE_SIZE = 200;
+ public static int MAX_COLUMN_SIZE = 1024 * 2;
+}
--- /dev/null
+package com.quantum.view.tableview;
+
+import java.sql.SQLException;
+import java.util.Vector;
+
+import com.quantum.Messages;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+import com.quantum.model.NotConnectedException;
+import com.quantum.sql.FilterSort;
+import com.quantum.sql.SQLHelper;
+import com.quantum.sql.SQLResults;
+
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.swt.widgets.Text;
+
+public class TableAdapter {
+
+ private Table table = null;
+
+ public static final String DEFAULT = ""; //$NON-NLS-1$
+ public static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
+ public static final String UTF_16 = "UTF-16"; //$NON-NLS-1$
+
+ private int pageSize = DefaultSizes.PAGE_SIZE;
+ private int maxColumnSize = DefaultSizes.MAX_COLUMN_SIZE;
+ private FilterSort extra = new FilterSort();
+ private int offset = 1;
+ private int totalSize = -1;
+ private Vector rows = new Vector();
+ private Vector columnNames = new Vector();
+ private boolean hasMore = false;
+
+ private Bookmark bookmark = null;
+ private Entity entity = null;
+ private String query;
+
+ private String encoding = ""; //$NON-NLS-1$
+
+ private TableAdapter(Entity entity) {
+ this.entity = entity;
+ this.bookmark = entity.getBookmark();
+ }
+ private TableAdapter(Bookmark bookmark) {
+ this.bookmark = bookmark;
+ }
+ public void fullMode() {
+ offset = 1;
+ pageSize = Integer.MAX_VALUE;
+ }
+ public void resetMode() {
+ offset = 1;
+ pageSize = DefaultSizes.PAGE_SIZE;
+ }
+ public static TableAdapter createFromQuery(Bookmark bookmark, SQLResults results) throws NotConnectedException {
+ TableAdapter retVal = new TableAdapter(bookmark);
+ retVal.setQuery(results.getQuery());
+ retVal.setData(results);
+ return retVal;
+ }
+ public static TableAdapter createFromTable(Entity entity) {
+ TableAdapter retVal = new TableAdapter(entity);
+ return retVal;
+ }
+ private void loadSize() {
+ try {
+ if (entity != null) {
+ totalSize = SQLHelper.getSize(
+ bookmark.getConnection(), entity.getCondQualifiedName(),
+ AdapterFactory.getInstance().getAdapter(bookmark.getType()));
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ } catch (NotConnectedException e) {
+ e.printStackTrace();
+ }
+ }
+ public int getStartIndex() {
+ if (totalSize == 0) {
+ return 0;
+ }
+ return offset;
+ }
+ public int getEndIndex() {
+ return offset + rows.size() - 1;
+ }
+ public int getTotalSize() {
+ return totalSize;
+ }
+ public void nextPage() {
+ loadSize();
+ offset = offset + pageSize;
+ if (totalSize >= 0 && offset > totalSize) {
+ offset = offset - pageSize;
+ }
+ }
+ public void previousPage() {
+ offset = offset - pageSize;
+ if (offset < 1) {
+ offset = 1;
+ }
+ }
+ public boolean hasNextPage() {
+ if (entity != null) {
+ if (offset + pageSize <= totalSize) {
+ return true;
+ }
+ return false;
+ }
+ return hasMore;
+ }
+ public boolean hasPreviousPage() {
+ if (offset > 1) {
+ return true;
+ }
+ return false;
+ }
+
+ public String getQuery() {
+ if (entity != null) {
+ DatabaseAdapter adapter = AdapterFactory.getInstance().getAdapter(bookmark.getType());
+ if (adapter == null) throw new RuntimeException();
+ else return adapter.getTableQuery((entity).getCondQualifiedName()) + extra.toString();
+ }
+ return query;
+ }
+ public void loadData() throws NotConnectedException {
+ loadSize();
+ if (entity != null) {
+ if (offset > totalSize) {
+ offset = 1;
+ }
+ }
+ String query = getQuery();
+ System.out.println(offset + Messages.getString("TableAdapter.to") + (offset + pageSize - 1)); //$NON-NLS-1$
+ SQLResults results = SQLHelper.getResults(bookmark.getConnection(), query, offset, offset + pageSize - 1, maxColumnSize, encoding);
+ setData(results);
+ }
+ public void resetOffset() {
+ offset = 1;
+ }
+ public void setData(SQLResults results) throws NotConnectedException {
+ if (results.isError()) return;
+ int rowCount = results.getRowCount();
+ int columnCount = results.getColumnCount();
+ rows = new Vector();
+ columnNames = new Vector();
+ for (int col = 1; col <= columnCount; col++) {
+ columnNames.addElement(results.getColumnName(col));
+ }
+ for (int row = 1; row <= rowCount; row++) {
+ String rowData[] = new String[columnCount];
+ for (int col = 1; col <= columnCount; col++) {
+ rowData[col - 1] = results.getElement(col, row).toString();
+ }
+ rows.addElement(rowData);
+ }
+ hasMore = results.hasMore();
+ if (entity == null && results.getMaxSize() >= 0) {
+ if (offset > results.getMaxSize()) {
+ offset = 1;
+ loadData();
+ }
+ }
+ }
+ public void loadTable(Table table) {
+ this.table = table;
+ table.setHeaderVisible(true);
+ for (int i = 0; i < columnNames.size(); i++) {
+ TableColumn column = new TableColumn(table, SWT.NONE);
+ column.setText(columnNames.elementAt(i).toString());
+ }
+ for (int i = 0; i < columnNames.size(); i++) {
+ table.getColumn(i).pack();
+ }
+ for (int row = 0; row < rows.size(); row++) {
+ TableItem item = new TableItem(table, SWT.NONE);
+ String itemData[] = (String[]) rows.elementAt(row);
+ item.setText(itemData);
+ }
+ for (int i = 0; i < columnNames.size(); i++) {
+ table.getColumn(i).pack();
+ }
+ }
+
+ public TableViewer addTableViewer(Table table) {
+ TableViewer tableViewer = new TableViewer(table);
+ tableViewer.setUseHashlookup(true);
+ String[] colNams = new String[columnNames.size()];
+ for (int i = 0; i < columnNames.size(); i++) {
+ colNams[i] = (String) columnNames.get(i);
+ }
+ tableViewer.setColumnProperties(colNams);
+
+ // Create the cell editors
+ CellEditor[] editors = new CellEditor[columnNames.size()];
+ for (int i = 0; i < columnNames.size(); i++) {
+ TextCellEditor textEditor = new TextCellEditor(table);
+ ((Text) textEditor.getControl()).setTextLimit(60);
+ editors[i] = textEditor;
+ }
+ // Assign the cell editors to the viewer
+ tableViewer.setCellEditors(editors);
+ // Set the cell modifier for the viewer
+ //tableViewer.setCellModifier(new MetaDataModifier(this));
+ // Set the default sorter for the viewer
+ //tableViewer.setSorter(new ExampleTaskSorter(ExampleTaskSorter.DESCRIPTION));
+
+ return tableViewer;
+ }
+
+ public int getPageSize() {
+ return pageSize;
+ }
+
+ public void setFilterSort(FilterSort extra) {
+ this.extra = extra;
+ }
+ public String getTable() {
+ return (entity != null) ? entity.getCondQualifiedName() : null;
+ }
+
+ public void setQuery(String query) {
+ this.query = query;
+ }
+ public String getEncoding() {
+ return encoding;
+ }
+
+ public void setEncoding(String encoding) {
+ this.encoding = encoding;
+ }
+ public String getStatusString() {
+ String status = getStartIndex() + Messages.getString("TableAdapter.to") + getEndIndex() + Messages.getString("TableAdapter.of") + //$NON-NLS-1$ //$NON-NLS-2$
+ getTotalSize();
+ if (!encoding.equals(DEFAULT)) {
+ status += " (" + encoding + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ String filterText = extra.toString();
+ if (!filterText.equals("")) { //$NON-NLS-1$
+ status += " (" + filterText + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (pageSize == Integer.MAX_VALUE) {
+ status += Messages.getString("TableAdapter.full"); //$NON-NLS-1$
+ }
+ return status;
+ }
+ /**
+ * @return
+ */
+ public Bookmark getBookmark() {
+ return this.bookmark;
+ }
+ /**
+ * @return
+ */
+ public Entity getEntity() {
+ return entity;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.view.tableview;
+
+import java.util.Vector;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IMenuListener;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.TabFolder;
+import org.eclipse.swt.widgets.TabItem;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.WorkbenchException;
+import org.eclipse.ui.part.ViewPart;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.extensions.ProcessServiceMembers;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+import com.quantum.model.NotConnectedException;
+import com.quantum.sql.SQLResults;
+import com.quantum.ui.dialog.ExceptionDisplayDialog;
+import com.quantum.view.LogProxy;
+
+/**
+ * The Table View. Displays tables and Queries.
+ */
+public class TableView extends ViewPart implements ISelectionListener {
+
+ private class DefaultEncodingAction extends Action {
+ private final TableAdapter ta;
+ private DefaultEncodingAction(TableAdapter ta) {
+ super();
+ this.ta = ta;
+ }
+ public void run() {
+ ta.setEncoding(TableAdapter.DEFAULT);
+ }
+ }
+ private static TableView instance = null;
+ private TabFolder tabs = null;
+ private Composite parent;
+ private Vector extensionVector;
+
+ /**
+ * Generic contructor
+ */
+ public TableView() {
+ }
+
+
+ public void setFocus() {
+ setQualifiedTitle();
+ }
+
+ /**
+ * Gets the instance of the TableView. This view can appear on multiple
+ * perspectives, but tabs within the view are shared no matter which perspective
+ * is open.
+ *
+ * @return the TableView instance.
+ */
+ public static TableView getInstance() {
+ return (TableView) QuantumPlugin.getDefault().getView("com.quantum.view.tableview.TableView");
+ }
+
+ /**
+ * Close the current tab, disposing of it
+ */
+ public void closeCurrent() {
+ if (tabs == null) return;
+
+ if (tabs.getSelectionIndex() >= 0) {
+ try {
+ TabItem item = tabs.getItem(tabs.getSelectionIndex());
+ item.dispose();
+ } catch (Throwable e) {
+ LogProxy.getInstance().addText(LogProxy.ERROR, "Error Closing Current: " + e.toString()); //$NON-NLS-1$
+ e.printStackTrace();
+ }
+ }
+ if (tabs.getItemCount() == 0) {
+ setTitle(Messages.getString("tableview.QuantumTableViewName")); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Reload table or query data into the selected tab
+ */
+ public void refreshCurrent() {
+ TabItem item = tabs.getItem(tabs.getSelectionIndex());
+ TableAdapter adapter = (TableAdapter) item.getData();
+ Bookmark bookmark = adapter.getBookmark();
+ String table = adapter.getTable();
+ if (table == null) {
+ loadTable(bookmark, item, null, null, true, true);
+ } else {
+ loadTable(bookmark, item, null, null, true, true);
+ }
+ String title = Messages.getString("tableview.QuantumTableViewName"); //$NON-NLS-1$
+ if (bookmark != null)
+ title = bookmark.getName() + Messages.getString("tableview.ViewNameInitialDecoration") + title + Messages.getString("tableview.ViewNameFinalDecoration"); //$NON-NLS-1$ //$NON-NLS-2$
+ setTitle(title);
+ }
+
+ public void loadQuery(Bookmark bookmark, SQLResults results) {
+ loadTable(bookmark, null, null, results, true, false);
+ }
+ public void loadTable(Entity entity) {
+ loadTable(entity.getBookmark(), null, entity, null, false, true);
+ }
+ public void loadTable(Bookmark bookmark, TabItem tabItem, Entity entity, SQLResults results, boolean query, boolean reload) {
+ try {
+ TableAdapter adapter;
+ // If no TabItem is given we have to create a new one, with the info of the table or view.
+ if (tabItem == null) {
+ tabItem = new TabItem(tabs, SWT.NONE);
+ // Data is stored in a TableAdapter object
+ if (query) {
+ adapter = TableAdapter.createFromQuery(bookmark, results);
+ } else {
+ adapter = TableAdapter.createFromTable(entity);
+ }
+ // That is stored in the tabItem, so it won't get lost
+ tabItem.setData(adapter);
+ // This does not really belong here, but it'll fail if done before the creation of the
+ // first TabItem, so it remains here till a better place found.
+ // We set a function to change the Title of the window depending on the selected tab.
+ tabs.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ setQualifiedTitle();
+ }
+ });
+ } else {
+ // If there is already a TabItem, we take its TableAdapter object
+ adapter = (TableAdapter) tabItem.getData();
+ }
+
+ // We create a Composite widget (main) to display our data, with a GridLayout
+ Composite main = new Composite(tabs, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.horizontalSpacing = 0;
+ layout.verticalSpacing = 0;
+ main.setLayout(layout);
+
+
+ // load widgets, the order of loading them determines the appearance in screen
+ ToolBar widgetToolBar = new ToolBar(main, SWT.HORIZONTAL);
+ // We fill up our Composite widget, the main table display, etc.
+ final Table table = new Table(main, SWT.FULL_SELECTION | SWT.MULTI);
+ final Label label = new Label(main, SWT.NULL);
+ TableViewToolBar toolBar = new TableViewToolBar(this, widgetToolBar, table, adapter, label);
+
+
+ // load table
+ if (reload) {
+ adapter.resetOffset();
+ adapter.loadData();
+ }
+ // Load the table data from the adapter into the widget
+ adapter.loadTable(table);
+ // Experimental, won't make it into 2.2
+ // final TableViewer viewer = adapter.addTableViewer(table);
+
+ String tableName = adapter.getTable();
+ if (tableName != null) {
+ tabItem.setText(bookmark.getName() + ":" + tableName);
+ } else {
+ tabItem.setText(bookmark.getName() + ":" + adapter.getQuery());
+ }
+
+ toolBar.getPrevious().setEnabled(adapter.hasPreviousPage());
+ toolBar.getNext().setEnabled(adapter.hasNextPage());
+ label.setText(adapter.getStatusString());
+
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ table.setLayoutData(gridData);
+
+ gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ label.setLayoutData(gridData);
+
+
+ toolBar.setColumns(this, adapter, table);
+ final TableAdapter ta = adapter;
+ final Action defaultEncodingAction = new DefaultEncodingAction(ta);
+ defaultEncodingAction.setText(Messages.getString("tableview.defaultEncoding")); //$NON-NLS-1$
+ final Action UTF8EncodingAction = new Action() {
+ public void run() {
+ ta.setEncoding(TableAdapter.UTF_8);
+ }
+ };
+ UTF8EncodingAction.setText(Messages.getString("tableview.UTF8Encoding")); //$NON-NLS-1$
+ final Action UTF16EncodingAction = new Action() {
+ public void run() {
+ ta.setEncoding(TableAdapter.UTF_16);
+ }
+ };
+ UTF16EncodingAction.setText(Messages.getString("tableview.UTF16Encoding")); //$NON-NLS-1$
+
+ IMenuListener menuListener = new TableViewMenuListener(this, table, UTF16EncodingAction, ta, defaultEncodingAction, UTF8EncodingAction, extensionVector);
+
+ // final setup
+ MenuManager manager = new MenuManager();
+ manager.setRemoveAllWhenShown(true);
+ Menu fTextContextMenu = manager.createContextMenu(table);
+ table.setMenu(fTextContextMenu);
+ table.setLinesVisible(true);
+ manager.addMenuListener(menuListener);
+
+ tabItem.setControl(main);
+ tabs.setSelection(tabs.indexOf(tabItem));
+
+ setQualifiedTitle();
+ } catch (NotConnectedException e) {
+ e.printStackTrace();
+ handleException(e);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ protected void handleException(Exception e) {
+ ExceptionDisplayDialog.openError(getSite().getShell(), null, null, e);
+ }
+
+ /**
+ * @return
+ */
+ /**
+ * Sets the title of the window to the text of the selected tab
+ */
+ private void setQualifiedTitle() {
+ if (tabs.getSelectionIndex() < 0) return;
+ TabItem item = tabs.getItem(tabs.getSelectionIndex());
+ String defTitle = Messages.getString("tableview.QuantumTableViewName"); //$NON-NLS-1$
+ String title = item.getText();
+ int ind = title.indexOf(Messages.getString("tableview.BookmarkSeparator")); //$NON-NLS-1$
+ if (ind > 0) defTitle = title.substring(0,ind)
+ + Messages.getString("tableview.ViewNameInitialDecoration") //$NON-NLS-1$
+ + defTitle
+ + Messages.getString("tableview.ViewNameFinalDecoration"); //$NON-NLS-1$
+ setTitle(defTitle);
+ }
+
+ public void createPartControl(Composite parent) {
+ instance = this;
+ this.parent = parent;
+ initActions();
+ tabs = new TabFolder(parent, SWT.NONE);
+ }
+
+ public void initActions() {
+ extensionVector = new Vector();
+ try {
+ ProcessServiceMembers.process(this, extensionVector);
+ } catch (WorkbenchException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public void selectionChanged(IWorkbenchPart part, ISelection selection) {
+
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Created on 28-jul-2003
+ *
+ */
+package com.quantum.view.tableview;
+
+import java.util.Vector;
+
+import com.quantum.Messages;
+import com.quantum.extensions.ExtensionAction;
+import com.quantum.sql.TableRow;
+import com.quantum.util.StringMatrix;
+import com.quantum.wizards.DeleteRowPage;
+import com.quantum.wizards.InsertRowPage;
+import com.quantum.wizards.SQLRowWizard;
+import com.quantum.wizards.UpdateRowPage;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IMenuListener;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+
+
+public final class TableViewMenuListener implements IMenuListener {
+ private final TableView tableView;
+ private final Table table;
+ private final Action UTF16EncodingAction;
+ private final TableAdapter ta;
+ private final Action defaultEncodingAction;
+ private final Action UTF8EncodingAction;
+ private final Vector extensionVector;
+
+ public TableViewMenuListener(
+ TableView view,
+ Table table,
+ Action UTF16EncodingAction,
+ TableAdapter ta,
+ Action defaultEncodingAction,
+ Action UTF8EncodingAction,
+ Vector extensionVector ) {
+
+ super();
+ this.tableView = view;
+ this.table = table;
+ this.UTF16EncodingAction = UTF16EncodingAction;
+ this.ta = ta;
+ this.defaultEncodingAction = defaultEncodingAction;
+ this.UTF8EncodingAction = UTF8EncodingAction;
+ this.extensionVector = extensionVector;
+ }
+ public void menuAboutToShow(IMenuManager mgr) {
+ if (ta.getTable() != null) {
+ TableItem[] selection = table.getSelection();
+ TableColumn[] columns = table.getColumns();
+ // Copy in columnNames the names of the columns of the selected rows
+ String columnNames[] = new String[columns.length];
+ for (int i = 0; i < columns.length; i++) {
+ columnNames[i] = columns[i].getText();
+ }
+ // Copy in data the values of the data columns of the selected rows
+ StringMatrix data = new StringMatrix();
+ data.addMatrixHeader(columnNames);
+ if (selection != null && selection.length > 0) {
+ for (int iRow = 0; iRow < selection.length; iRow++) {
+ TableItem sel = selection[iRow];
+ for (int i = 0; i < columns.length; i++) {
+ data.addAt(columnNames[i], sel.getText(i), iRow );
+ }
+ }
+ } else {
+ // Create dummy values in case nothing selected
+ for (int i = 0; i < columns.length; i++) {
+ data.addAt(columnNames[i], "", 0); //$NON-NLS-1$
+ }
+ }
+ final TableRow row =
+ new TableRow(ta.getEntity(), ta.getBookmark(), ta.getTable(), data);
+ Action updateAction = new Action() {
+ public void run() {
+ UpdateRowPage page = new UpdateRowPage(""); //$NON-NLS-1$
+ SQLRowWizard wizard = new SQLRowWizard();
+ wizard.init(Messages.getString("TableView.UpdateRow"), page, row, ta); //$NON-NLS-1$
+ WizardDialog dialog =
+ new WizardDialog(
+ tableView.getSite().getShell(),
+ wizard);
+ dialog.open();
+ }
+ };
+ updateAction.setText(Messages.getString("tableview.update")); //$NON-NLS-1$
+ Action insertAction = new Action() {
+ public void run() {
+ InsertRowPage page = new InsertRowPage(""); //$NON-NLS-1$
+ SQLRowWizard wizard = new SQLRowWizard();
+ wizard.init(Messages.getString("TableView.InsertRow"), page, row, ta); //$NON-NLS-1$
+ WizardDialog dialog =
+ new WizardDialog(
+ tableView.getSite().getShell(),
+ wizard);
+ dialog.open();
+ }
+ };
+ insertAction.setText(Messages.getString("tableview.insert")); //$NON-NLS-1$
+ Action deleteAction = new Action() {
+ public void run() {
+ DeleteRowPage page = new DeleteRowPage(""); //$NON-NLS-1$
+ SQLRowWizard wizard = new SQLRowWizard();
+ wizard.init(Messages.getString("TableView.DeleteRow"), page, row, ta); //$NON-NLS-1$
+ WizardDialog dialog =
+ new WizardDialog(
+ tableView.getSite().getShell(),
+ wizard);
+ dialog.open();
+ }
+ };
+ deleteAction.setText(Messages.getString("tableview.delete")); //$NON-NLS-1$
+ mgr.add(insertAction);
+ mgr.add(updateAction);
+ mgr.add(deleteAction);
+
+ MenuManager subMenuExtension = new MenuManager("Extensions");
+ for (int i = 0; i < extensionVector.size(); i++) {
+ ExtensionAction extensionAction = (ExtensionAction) extensionVector.get(i);
+ extensionAction.addRowData(row);
+ subMenuExtension.add(extensionAction);
+ }
+ if (extensionVector.size() > 0) mgr.add(subMenuExtension);
+
+ }
+ mgr.add(defaultEncodingAction);
+ mgr.add(UTF8EncodingAction);
+ mgr.add(UTF16EncodingAction);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Created on 28-jul-2003
+ *
+ */
+package com.quantum.view.tableview;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.actions.CloseTableAction;
+import com.quantum.actions.RefreshTableAction;
+import com.quantum.model.NotConnectedException;
+import com.quantum.sql.TableRow;
+import com.quantum.util.StringMatrix;
+import com.quantum.view.CopyAction;
+import com.quantum.wizards.SQLRowWizard;
+import com.quantum.wizards.SortFilterPage;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.ToolItem;
+
+/**
+ * @author panic
+ *
+ */
+public class TableViewToolBar {
+
+ private ToolBar toolBar;
+ private RefreshTableAction refreshTableAction;
+ private CloseTableAction closeTableAction;
+ private ToolItem previous;
+ private ToolItem next;
+
+ ToolItem filter;
+
+ public TableViewToolBar(
+ final TableView view,
+ final ToolBar toolBar,
+ final Table table,
+ final TableAdapter ta,
+ final Label label) {
+
+ this.toolBar = toolBar;
+
+ refreshTableAction = new RefreshTableAction();
+ refreshTableAction.setText(Messages.getString("tableview.refresh")); //$NON-NLS-1$
+ refreshTableAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("refresh.gif")); //$NON-NLS-1$
+ refreshTableAction.init(view);
+ closeTableAction = new CloseTableAction();
+ closeTableAction.setText(Messages.getString("tableview.close")); //$NON-NLS-1$
+ closeTableAction.setImageDescriptor(
+ QuantumPlugin.getImageDescriptor("close.gif")); //$NON-NLS-1$
+ closeTableAction.init(view);
+
+ ToolItem toolItem = new ToolItem(toolBar, SWT.PUSH);
+ toolItem.setImage(QuantumPlugin.getImage("refresh.gif")); //$NON-NLS-1$
+ toolItem.setToolTipText(Messages.getString("tableview.refresh")); //$NON-NLS-1$
+ toolItem.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ refreshTableAction.run();
+ }
+ });
+
+ final Action copyAction = new CopyAction(view, table);
+ final Action selectAllAction = new Action() {
+ public void run() {
+ table.selectAll();
+ }
+ };
+ toolItem = new ToolItem(toolBar, SWT.PUSH);
+ toolItem.setImage(QuantumPlugin.getImage("copy.gif")); //$NON-NLS-1$
+ toolItem.setToolTipText(Messages.getString("tableview.copy")); //$NON-NLS-1$
+ toolItem.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ copyAction.run();
+ }
+ });
+ toolItem = new ToolItem(toolBar, SWT.PUSH);
+ toolItem.setImage(QuantumPlugin.getImage("table.gif")); //$NON-NLS-1$
+ toolItem.setToolTipText(Messages.getString("tableview.selectAll")); //$NON-NLS-1$
+ toolItem.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ selectAllAction.run();
+ }
+ });
+
+ filter = new ToolItem(toolBar, SWT.PUSH);
+ filter.setImage(QuantumPlugin.getImage("filter.gif")); //$NON-NLS-1$
+ filter.setToolTipText(Messages.getString("tableview.filterSort")); //$NON-NLS-1$
+
+ toolItem = new ToolItem(toolBar, SWT.SEPARATOR);
+
+ final ToolItem fullMode = new ToolItem(toolBar, SWT.PUSH | SWT.CHECK);
+
+ previous = new ToolItem(toolBar, SWT.PUSH);
+ next = new ToolItem(toolBar, SWT.PUSH);
+
+ fullMode.setImage(QuantumPlugin.getImage("fulldata.gif")); //$NON-NLS-1$
+ fullMode.setToolTipText(Messages.getString("tableview.showAll")); //$NON-NLS-1$
+ fullMode.setSelection(false);
+ fullMode.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent event) {
+ try {
+ if (ta.getPageSize() == Integer.MAX_VALUE) {
+ ta.resetMode();
+ } else {
+ ta.fullMode();
+ }
+ ta.loadData();
+ table.removeAll();
+ for (int i = table.getColumnCount() - 1; i >= 0; i--) {
+ table.getColumn(i).dispose();
+ }
+ ta.loadTable(table);
+ label.setText(ta.getStatusString());
+ previous.setEnabled(ta.hasPreviousPage());
+ next.setEnabled(ta.hasNextPage());
+ } catch (NotConnectedException e) {
+ view.handleException(e);
+ }
+ }
+ });
+ previous.setImage(QuantumPlugin.getImage("previous.gif")); //$NON-NLS-1$
+ previous.setToolTipText("Previous"); //$NON-NLS-1$
+ previous.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent event) {
+ try {
+ ta.previousPage();
+ ta.loadData();
+ table.removeAll();
+ for (int i = table.getColumnCount() - 1; i >= 0; i--) {
+ table.getColumn(i).dispose();
+ }
+ ta.loadTable(table);
+ label.setText(ta.getStatusString());
+ previous.setEnabled(ta.hasPreviousPage());
+ next.setEnabled(ta.hasNextPage());
+ } catch (NotConnectedException e) {
+ view.handleException(e);
+ }
+ }
+ });
+ next.setImage(QuantumPlugin.getImage("next.gif")); //$NON-NLS-1$
+ next.setToolTipText("Next"); //$NON-NLS-1$
+ next.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent event) {
+ try {
+ ta.nextPage();
+ ta.loadData();
+ table.removeAll();
+ for (int i = table.getColumnCount() - 1; i >= 0; i--) {
+ table.getColumn(i).dispose();
+ }
+ ta.loadTable(table);
+ label.setText(ta.getStatusString());
+ previous.setEnabled(ta.hasPreviousPage());
+ next.setEnabled(ta.hasNextPage());
+ } catch (NotConnectedException e) {
+ view.handleException(e);
+ }
+ }
+ });
+
+ toolItem = new ToolItem(toolBar, SWT.SEPARATOR);
+
+ toolItem = new ToolItem(toolBar, SWT.PUSH);
+ toolItem.setImage(QuantumPlugin.getImage("close.gif")); //$NON-NLS-1$
+ toolItem.setToolTipText(Messages.getString("tableview.close")); //$NON-NLS-1$
+ toolItem.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ closeTableAction.run();
+ }
+ });
+
+ }
+
+ public void setColumns( final TableView view, final TableAdapter ta, Table table) {
+
+ // We create a matrix of TableColumn (columns in the Table widget) with
+ // the columns in the table object
+ TableColumn[] columns = table.getColumns();
+ String columnNames[] = new String[columns.length];
+ for (int i = 0; i < columns.length; i++) {
+ columnNames[i] = columns[i].getText();
+ }
+ // Copy in data the values of the data columns of the selected rows
+ StringMatrix data = new StringMatrix();
+ data.addMatrixHeader(columnNames);
+ // Create dummy values in case nothing selected
+ for (int i = 0; i < columns.length; i++) {
+ data.addAt(columnNames[i], "", 0); //$NON-NLS-1$
+ }
+ final TableRow emptyRow = new TableRow(ta.getEntity(), ta.getBookmark(), ta.getTable(), data);
+
+ filter.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ SortFilterPage page = new SortFilterPage(""); //$NON-NLS-1$
+ SQLRowWizard wizard = new SQLRowWizard();
+ wizard.init(Messages.getString("TableView.FilterAndSort"), page, emptyRow, ta); //$NON-NLS-1$
+ WizardDialog dialog = new WizardDialog(view.getSite().getShell(), wizard);
+ dialog.open();
+ }
+ });
+ }
+
+
+
+ /**
+ * @return
+ */
+ public ToolItem getNext() {
+ return next;
+ }
+
+ /**
+ * @return
+ */
+ public ToolItem getPrevious() {
+ return previous;
+ }
+
+}
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Column;
+import com.quantum.model.ConnectionException;
+import com.quantum.model.Entity;
+import com.quantum.sql.TableRow;
+import com.quantum.view.ViewHelper;
+import com.quantum.view.tableview.TableAdapter;
+
+import org.eclipse.jface.wizard.WizardPage;
+
+/**
+ * @author BC
+ */
+public abstract class BaseSQLPage extends WizardPage implements SQLPage {
+
+ protected TableRow row;
+ protected TableAdapter adapter;
+
+ public BaseSQLPage(String pageName) {
+ super(pageName);
+ }
+ public boolean performFinish() {
+ try {
+ Bookmark bookmark = this.adapter.getBookmark();
+ bookmark.addQuery(getQueryText());
+ ViewHelper.tryGetResults(getShell(), bookmark.getConnection(), getQueryText());
+ } catch (ConnectionException e) {
+ e.printStackTrace();
+ }
+ return true;
+ }
+ protected abstract String getQueryText();
+ protected void appendColumn(StringBuffer whereClause, Entity entity, String columnName, DatabaseAdapter adapter, String value) {
+
+ if (adapter != null && entity != null && entity.getColumn(columnName) != null) {
+ Column column = entity.getColumn(columnName);
+ whereClause.append(adapter.quote(value, column.getType(), column.getTypeName()));
+ } else {
+ whereClause.append(value);
+ }
+ }
+ public void init(TableRow row, TableAdapter adapter) {
+ this.row = row;
+ this.adapter = adapter;
+ }
+}
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DriverInfo;
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkCollection;
+import com.quantum.view.bookmark.BookmarkNode;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class BookmarkWizard extends Wizard {
+ BookmarkPage mainPage;
+
+ private Bookmark current;
+
+ public void init(BookmarkNode selection) {
+ System.out.println("Initing workbench"); //$NON-NLS-1$
+ this.current = selection.getBookmark();
+ setWindowTitle(Messages.getString("BookmarkWizard.NewBookmark")); //$NON-NLS-1$
+ }
+ public void init() {
+ System.out.println("Initing workbench"); //$NON-NLS-1$
+ current = null;
+ setWindowTitle(Messages.getString("BookmarkWizard.NewBookmark")); //$NON-NLS-1$
+ }
+ public boolean performFinish() {
+ System.out.println("perform finish workbench"); //$NON-NLS-1$
+ String bookmarkName = mainPage.name.getText();
+ if ( BookmarkCollection.getInstance().find(bookmarkName) != null){
+ MessageDialog.openInformation(
+ this.getShell(),Messages.getString("BookmarkWizard.Error"),Messages.getString("BookmarkWizard.bookmarkAlreadyExists")); //$NON-NLS-1$ //$NON-NLS-2$
+ return false;
+ }
+
+ mainPage.performFinish();
+ return true;
+ }
+ public void addPages() {
+ System.out.println("adding pages"); //$NON-NLS-1$
+ if (current != null) {
+ mainPage = new BookmarkPage(Messages.getString("BookmarkWizard.Testing"), current); //$NON-NLS-1$
+ } else {
+ mainPage = new BookmarkPage(Messages.getString("BookmarkWizard.Testing")); //$NON-NLS-1$
+ }
+ addPage(mainPage);
+ System.out.println("adding pages"); //$NON-NLS-1$
+ }
+}
+
+class BookmarkPage extends WizardPage {
+ public static final String ADD = "ADD"; //$NON-NLS-1$
+ String action = ADD;
+ Text name;
+ Text username;
+ Text password;
+ Text schema;
+ Text connect;
+ Text driver;
+ //List driverList;
+ Combo type;
+ Text driverFile;
+ Button prompt;
+
+ Bookmark initialData = null;
+
+ FileDialog dialog;
+
+ DriverInfo[] drivers = AdapterFactory.getInstance().getDriverList();
+ /**
+ * Constructor for BookmarkPage.
+ * @param pageName
+ */
+ public BookmarkPage(String pageName) {
+ super(pageName);
+ initialData = null;
+ }
+ /**
+ * Constructor for BookmarkPage.
+ * @param pageName
+ */
+ public BookmarkPage(String pageName, Bookmark bookmark) {
+ super(pageName);
+ this.initialData = bookmark;
+ }
+
+ public void createControl(Composite parent) {
+ System.out.println("page create control"); //$NON-NLS-1$
+ dialog = new FileDialog(getContainer().getShell(), SWT.OPEN);
+ dialog.setFilterExtensions(new String[]{"*.jar", "*.zip","*.*"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ dialog.setFilterNames(new String[]{Messages.getString("BookmarkWizard.JarFiles"),Messages.getString("BookmarkWizard.ZipFiles"), Messages.getString("BookmarkWizard.AllFiles")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 2;
+ layout.verticalSpacing = 9;
+
+
+ Label label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.BookmarkNameAst")); //$NON-NLS-1$
+ name = new Text(container, SWT.BORDER | SWT.SINGLE);
+ GridData fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ name.setLayoutData(fullHorizontal);
+
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.UsernameAst")); //$NON-NLS-1$
+ username = new Text(container, SWT.BORDER | SWT.SINGLE);
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ username.setLayoutData(fullHorizontal);
+
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.PasswordAst")); //$NON-NLS-1$
+ password = new Text(container, SWT.BORDER | SWT.SINGLE);
+ password.setEchoChar('*');
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ password.setLayoutData(fullHorizontal);
+
+ this.prompt = new Button(container, SWT.CHECK);
+ this.prompt.setText(Messages.getString("BookmarkWizard.Prompt")); //$NON-NLS-1$
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ fullHorizontal.horizontalSpan = 2;
+ this.prompt.setLayoutData(fullHorizontal);
+
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.Schema")); //$NON-NLS-1$
+ schema = new Text(container, SWT.BORDER | SWT.SINGLE);
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ schema.setLayoutData(fullHorizontal);
+
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.ConnectAst")); //$NON-NLS-1$
+ connect = new Text(container, SWT.BORDER | SWT.SINGLE);
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ connect.setLayoutData(fullHorizontal);
+
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.DriverAst")); //$NON-NLS-1$
+ driver = new Text(container, SWT.BORDER | SWT.SINGLE);
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ driver.setLayoutData(fullHorizontal);
+
+ //label = new Label(container, SWT.NULL);
+ //fullHorizontal = new GridData();
+ //fullHorizontal.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ //fullHorizontal.verticalSpan = 3;
+ //label.setLayoutData(fullHorizontal);
+ //label.setText("(Drivers Found in File)");
+ /*driverList = new List(container, SWT.SINGLE);
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ fullHorizontal.verticalAlignment = GridData.FILL;
+ fullHorizontal.verticalSpan = 3;
+ driverList.setLayoutData(fullHorizontal);
+ driverList.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ String[] selection = driverList.getSelection();
+ if (selection != null && selection.length > 0) {
+ driver.setText(selection[0]);
+ }
+ }
+ });*/
+
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.TypeAst")); //$NON-NLS-1$
+ type = new Combo(container, SWT.SIMPLE | SWT.DROP_DOWN | SWT.READ_ONLY);
+ String driverNames[] = new String[drivers.length];
+ for (int i = 0; i < drivers.length; i++) {
+ driverNames[i] = drivers[i].getDisplayName();
+ }
+ type.setItems(driverNames);
+ type.select(0);
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ type.setLayoutData(fullHorizontal);
+
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.getString("BookmarkWizard.DriverFilenameAst")); //$NON-NLS-1$
+ driverFile = new Text(container, SWT.BORDER | SWT.SINGLE);
+ fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ driverFile.setLayoutData(fullHorizontal);
+
+ Button button = new Button(container, SWT.PUSH);
+ button.setText(Messages.getString("BookmarkWizard.Browse")); //$NON-NLS-1$
+
+ button.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ // We retrieve the last saved path
+ dialog.setFilterPath(QuantumPlugin.getDefault().getPreferenceStore().getString("quantum.dialogs.bookmarkwizard.path")); //$NON-NLS-1$
+ String filename = dialog.open();
+ if (filename != null) {
+ driverFile.setText(filename);
+ // We save the used path
+ QuantumPlugin.getDefault().getPreferenceStore().setValue("quantum.dialogs.bookmarkwizard.path", filename); //$NON-NLS-1$
+
+ }
+ }
+ });
+
+// if (initialData != null) {
+// name.setText(initialData.getName());
+// username.setText(initialData.getUsername());
+// if (initialData.getPromptForPassword()) {
+// this.password.setEditable(false);
+// } else {
+// password.setText(initialData.getPassword());
+// }
+// connect.setText(initialData.getConnect());
+// driver.setText(initialData.getDriver());
+// String typeData = initialData.getType();
+// this.prompt.setSelection(initialData.getPromptForPassword());
+// int selectedIndex = 0;
+// for (int i = 0; i < drivers.length; i++) {
+// if (typeData.equals(drivers[i].getDriverType())) {
+// selectedIndex = i;
+// }
+// }
+// type.select(selectedIndex);
+// driverFile.setText(initialData.getDriverFile());
+// updateDriverList();
+// }
+
+ prompt.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ BookmarkPage.this.password.setEditable(!prompt.getSelection());
+ }
+ });
+
+ setControl(container);
+
+ setPageComplete(true);
+ }
+ public void updateDriverList() {
+ /*try {
+ JarFile file = new JarFile(driverFile.getText());
+ Enumeration enum = file.entries();
+ while (enum.hasMoreElements()) {
+ JarEntry entry = (JarEntry) enum.nextElement();
+ String className = entry.getName().replace('/', '.');
+ if (className.endsWith("Driver.class")) {
+ className = className.substring(0, className.lastIndexOf('.'));
+ //driverList.add(className);
+ }
+ }
+ } catch (IOException ex) {
+ //driverList.removeAll();
+ }*/
+ }
+ public void performFinish() {
+ if (initialData == null) {
+ initialData = new Bookmark();
+ }
+ initialData.setName(name.getText());
+ initialData.setUsername(username.getText());
+ initialData.setPromptForPassword(this.prompt.getSelection());
+ if (initialData.getPromptForPassword()) {
+ initialData.setPassword(""); //$NON-NLS-1$
+ } else {
+ initialData.setPassword(password.getText());
+ }
+ initialData.addSchema(schema.getText());
+ initialData.setConnect(connect.getText());
+ initialData.setDriver(driver.getText());
+ int selection = type.getSelectionIndex();
+ if (selection >= 0) {
+ initialData.setType(drivers[selection].getDriverType());
+ }
+ initialData.setDriverFile(driverFile.getText());
+ BookmarkCollection.getInstance().addBookmark(initialData);
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.Messages;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class DeleteRowPage extends BaseSQLPage implements SQLPage {
+ String[] columnNames;
+ Text[] values;
+ Button[] whereValues;
+ Text query;
+
+ public DeleteRowPage(String pageName) {
+ super(pageName);
+ }
+
+ public void createControl(Composite parent) {
+ System.out.println("page create control"); //$NON-NLS-1$
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+
+ if (row == null) {
+ System.out.println("Row is null"); //$NON-NLS-1$
+ }
+ if (row.getColumnNames() == null) {
+ System.out.println("Columns are null"); //$NON-NLS-1$
+ }
+ if (row.getTableData() == null) {
+ System.out.println("Data is null"); //$NON-NLS-1$
+ }
+ Entity entity = row.getEntity();
+ columnNames = row.getColumnNames();
+ String[] data = row.getTableData();
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ System.out.println("data = " + i + "=" + data[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ System.out.println("column = " + i + "=" + columnNames[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ values = new Text[row.getColumnCount()];
+ whereValues = new Button[row.getColumnCount()];
+ new Label(container, SWT.NULL).setText(Messages.getString("DeleteRowPage.ColumnName")); //$NON-NLS-1$
+ new Label(container, SWT.NULL).setText(Messages.getString("DeleteRowPage.Value")); //$NON-NLS-1$
+ new Label(container, SWT.NULL).setText(Messages.getString("DeleteRowPage.IncludeIn")); //$NON-NLS-1$
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ Label label = new Label(container, SWT.NULL);
+ label.setText(columnNames[i]);
+ values[i] = new Text(container, SWT.BORDER | SWT.SINGLE);
+ GridData fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ values[i].setLayoutData(fullHorizontal);
+ values[i].setText(data[i]);
+
+ values[i].addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ updateQuery();
+ }
+ });
+
+ whereValues[i] = new Button(container, SWT.CHECK);
+ whereValues[i].setText(Messages.getString("DeleteRowPage.WhereClause")); //$NON-NLS-1$
+ // we check if it's a primary key to select it in the WHERE clause
+ if (entity != null && entity.getColumn(columnNames[i]).isPrimaryKey()) {
+ whereValues[i].setSelection(true);
+ } else {
+ whereValues[i].setSelection(false);
+ }
+ whereValues[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ updateQuery();
+ }
+ });
+ }
+ query = new Text(container, SWT.MULTI | SWT.READ_ONLY | SWT.WRAP);
+ GridData gridData = new GridData();
+ gridData.horizontalSpan = layout.numColumns;
+ gridData.verticalSpan = 3;
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ query.setLayoutData(gridData);
+
+ setControl(container);
+ updateQuery();
+
+ setPageComplete(true);
+ }
+ public void updateQuery() {
+ System.out.println(Messages.getString("DeleteRowPage.UpdatingQuery")); //$NON-NLS-1$
+ StringBuffer whereClause = new StringBuffer();
+ Bookmark bookmark = row.getBookmark();
+ Entity entity = row.getEntity();
+ DatabaseAdapter adapter = AdapterFactory.getInstance().getAdapter(bookmark.getType());
+
+ int numSelected = 0;
+ for (int i = 0; i < columnNames.length; i++) {
+ if (whereValues[i].getSelection()) {
+ if (numSelected > 0) whereClause.append(" AND "); //$NON-NLS-1$
+ numSelected++;
+ whereClause.append("("); //$NON-NLS-1$
+ whereClause.append(columnNames[i]);
+ whereClause.append(" = "); //$NON-NLS-1$
+ appendColumn(whereClause, entity, columnNames[i], adapter, values[i].getText());
+ whereClause.append(")"); //$NON-NLS-1$
+ }
+ }
+ String query = "DELETE FROM " + row.getTable(); //$NON-NLS-1$
+ if (numSelected > 0) {
+ query += " WHERE " + whereClause.toString(); //$NON-NLS-1$
+ }
+ if (numSelected > 0) {
+ setMessage(""); //$NON-NLS-1$
+ } else {
+ setMessage(Messages.getString("DeleteRowPage.WarningNoWhere")); //$NON-NLS-1$
+ }
+ this.query.setText(query);
+ }
+
+ protected String getQueryText() {
+ return query.getText();
+ }
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.wizards;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.ui.IExportWizard;
+import org.eclipse.ui.IWorkbench;
+
+/**
+ * @author BC
+ */
+public class ExportBookmarkWizard extends Wizard implements IExportWizard {
+
+ private ExportBookmarkWizardPage page = new ExportBookmarkWizardPage();
+
+ public ExportBookmarkWizard() {
+ setWindowTitle("Export Bookmarks");
+ }
+
+ public boolean performFinish() {
+ return this.page.finish();
+ }
+
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ }
+
+ /**
+ * @see org.eclipse.jface.wizard.IWizard#addPages()
+ */
+ public void addPages() {
+ super.addPages();
+ addPage(this.page);
+ }
+
+}
--- /dev/null
+package com.quantum.wizards;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.quantum.Messages;
+import com.quantum.QuantumPlugin;
+import com.quantum.model.Bookmark;
+import com.quantum.model.BookmarkCollection;
+import com.quantum.model.xml.ModelToXMLConverter;
+import com.quantum.ui.dialog.ExceptionDisplayDialog;
+import com.quantum.util.xml.XMLHelper;
+
+import org.eclipse.jface.viewers.CheckStateChangedEvent;
+import org.eclipse.jface.viewers.CheckboxTreeViewer;
+import org.eclipse.jface.viewers.ICheckStateListener;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+import org.w3c.dom.Document;
+
+/**
+ * @author BC
+ */
+public class ExportBookmarkWizardPage extends WizardPage {
+
+ public class ContentProvider implements ITreeContentProvider {
+
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof BookmarkCollection) {
+ return ((BookmarkCollection) parentElement).getBookmarks();
+ } else {
+ return new Object[0];
+ }
+ }
+ public Object getParent(Object element) {
+ if (element instanceof Bookmark) {
+ return BookmarkCollection.getInstance();
+ } else {
+ return null;
+ }
+ }
+ public boolean hasChildren(Object element) {
+ if (element instanceof BookmarkCollection) {
+ return ((BookmarkCollection) element).getBookmarks().length > 0;
+ } else {
+ return false;
+ }
+ }
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
+ public void dispose() {
+ }
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+ }
+
+ public class LabelProvider implements ILabelProvider {
+
+ public Image getImage(Object element) {
+ if (element instanceof Bookmark) {
+ return QuantumPlugin.getImage("bookmarks.gif");
+ } else {
+ return null;
+ }
+ }
+
+ public String getText(Object element) {
+
+ if (element instanceof Bookmark) {
+ return ((Bookmark) element).getName();
+ } else {
+ return element.toString();
+ }
+ }
+
+ public void addListener(ILabelProviderListener listener) {
+ }
+
+ public void dispose() {
+ }
+
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ public void removeListener(ILabelProviderListener listener) {
+ }
+ }
+
+ private CheckboxTreeViewer treeViewer;
+ private Text fileNameText;
+
+ private boolean sourceIsSelected = false;
+ private boolean destinationIsSelected = false;
+
+ /**
+ * @param pageName
+ */
+ protected ExportBookmarkWizardPage() {
+ super("page1");
+ setTitle(Messages.getString(getClass(), "title"));
+ }
+
+ public void createControl(Composite pageContainer) {
+ this.sourceIsSelected = false;
+ this.destinationIsSelected = false;
+
+ Composite composite = new Composite(pageContainer, SWT.NULL);
+ composite.setLayout(new GridLayout());
+ composite.setLayoutData(
+ new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+
+ this.treeViewer = new CheckboxTreeViewer(composite,
+ SWT.CHECK | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
+ this.treeViewer.setContentProvider(new ContentProvider());
+ this.treeViewer.setLabelProvider(new LabelProvider());
+ this.treeViewer.setInput(BookmarkCollection.getInstance());
+ selectAll();
+
+ this.treeViewer.addCheckStateListener(new ICheckStateListener() {
+ public void checkStateChanged(CheckStateChangedEvent event) {
+ setSourceIsSelected(
+ ExportBookmarkWizardPage.this.treeViewer.getCheckedElements().length > 0);
+ }
+ });
+
+ GridData data = new GridData();
+ data.horizontalAlignment = GridData.HORIZONTAL_ALIGN_FILL;
+ data.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
+ data.grabExcessHorizontalSpace = true;
+ data.heightHint = 200;
+ data.widthHint = 400;
+ this.treeViewer.getControl().setLayoutData(data);
+
+ Composite buttons = new Composite(composite, SWT.NULL);
+ buttons.setLayout(new GridLayout(2, false));
+ buttons.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
+
+ Button selectAll = new Button(buttons, SWT.NONE);
+ selectAll.setText(Messages.getString(getClass(), "selectAll"));
+ selectAll.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ selectAll();
+ }
+ });
+
+ Button deselectAll = new Button(buttons, SWT.NONE);
+ deselectAll.setText(Messages.getString(getClass(), "deselectAll"));
+ deselectAll.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ deselectAll();
+ }
+ });
+
+ createDestinationArea(composite);
+
+ setControl(composite);
+ }
+
+ private void createDestinationArea(Composite composite) {
+ GridData data;
+ Composite fileArea = new Composite(composite, SWT.NULL);
+ fileArea.setLayout(new GridLayout(3, false));
+ fileArea.setLayoutData(
+ new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
+ Label label = new Label(fileArea, SWT.NONE);
+ label.setText("File name:");
+
+ this.fileNameText = new Text(fileArea, SWT.BORDER);
+ data = new GridData();
+ data.horizontalAlignment = GridData.HORIZONTAL_ALIGN_FILL;
+ data.widthHint = 300;
+ this.fileNameText.setLayoutData(data);
+ this.fileNameText.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent event) {
+ String text = ((Text) event.getSource()).getText();
+ setDestinationIsSelected(text != null && text.trim().length() > 0);
+ }
+ });
+
+ Button button = new Button(fileArea, SWT.NONE);
+ button.setText("Browse");
+ button.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ promptForFile();
+ }
+ });
+ }
+
+ private void setSourceIsSelected(boolean selected) {
+ this.sourceIsSelected = selected;
+ setPageComplete(selected & this.destinationIsSelected);
+ }
+
+ private void setDestinationIsSelected(boolean selected) {
+ this.destinationIsSelected = selected;
+ setPageComplete(selected & this.sourceIsSelected);
+ }
+
+ protected void promptForFile() {
+
+ FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
+ dialog.setFilterExtensions(new String[] { "xml" });
+ dialog.setFilterNames(new String[] { "XML Files (*.xml)"});
+ String filename = dialog.open();
+ if (filename != null) {
+ this.fileNameText.setText(filename);
+ }
+ }
+ protected void deselectAll() {
+ this.treeViewer.setCheckedElements(new Object[0]);
+ setSourceIsSelected(false);
+ }
+
+ protected void selectAll() {
+ Bookmark[] bookmarks = BookmarkCollection.getInstance().getBookmarks();
+ this.treeViewer.setCheckedElements(bookmarks);
+ setSourceIsSelected(bookmarks.length > 0);
+ }
+
+ public boolean finish() {
+
+ String fileName = this.fileNameText.getText();
+ File file = new File(fileName);
+ if (file.exists()) {
+ // prompt for overwrite
+ } else if (!file.getParentFile().exists()) {
+ // do what?
+ }
+
+ try {
+ Object[] bookmarks = this.treeViewer.getCheckedElements();
+ Document document = XMLHelper.createEmptyDocument();
+ ModelToXMLConverter.getInstance().createRoot(document);
+
+ for (int i = 0, length = (bookmarks == null) ? 0 : bookmarks.length;
+ i < length;
+ i++) {
+ ModelToXMLConverter.getInstance().convert(
+ document.getDocumentElement(), (Bookmark) bookmarks[i]);
+ }
+
+ FileWriter writer = new FileWriter(file);
+ try {
+ XMLHelper.write(writer, document);
+ } finally {
+ writer.close();
+ }
+ } catch (IOException e) {
+ ExceptionDisplayDialog.openError(getShell(),
+ Messages.getString(getClass(), "error.IOException.title"),
+ Messages.getString(getClass(), "error.IOException.message",
+ new Object[] { fileName }), e);
+ } catch (ParserConfigurationException e) {
+ ExceptionDisplayDialog.openError(getShell(),
+ Messages.getString(getClass(), "error.IOException.title"),
+ Messages.getString(getClass(), "error.IOException.message",
+ new Object[] { fileName }), e);
+ }
+
+ return true;
+ }
+}
--- /dev/null
+package com.quantum.wizards;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.ui.IExportWizard;
+import org.eclipse.ui.IWorkbench;
+
+/**
+ * @author BC
+ */
+public class ExportTorqueWizard extends Wizard implements IExportWizard {
+
+ public boolean performFinish() {
+ return false;
+ }
+
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ }
+
+}
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.Messages;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class InsertRowPage extends BaseSQLPage implements SQLPage {
+ String[] columnNames;
+ Text[] values;
+ Label query;
+ int numColumns = 0;
+
+ public InsertRowPage(String pageName) {
+ super(pageName);
+ }
+
+ public void createControl(Composite parent) {
+ System.out.println("page create control"); //$NON-NLS-1$
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 2;
+
+ if (row == null) {
+ System.out.println("Row is null"); //$NON-NLS-1$
+ }
+ if (row.getColumnNames() == null) {
+ System.out.println("Columns are null"); //$NON-NLS-1$
+ }
+ if (row.getTableData() == null) {
+ System.out.println("Data is null"); //$NON-NLS-1$
+ }
+ columnNames = row.getColumnNames();
+ String[] data = row.getTableData();
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ System.out.println("data = " + i + "=" + data[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ System.out.println("column = " + i + "=" + columnNames[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ values = new Text[row.getColumnCount()];
+ new Label(container, SWT.NULL).setText(Messages.getString("InsertRowPage.ColumnName")); //$NON-NLS-1$
+ new Label(container, SWT.NULL).setText(Messages.getString("InsertRowPage.Value")); //$NON-NLS-1$
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ Label label = new Label(container, SWT.NULL);
+ label.setText(columnNames[i]);
+ values[i] = new Text(container, SWT.BORDER | SWT.SINGLE);
+ GridData fullHorizontal = new GridData();
+ fullHorizontal.horizontalAlignment = GridData.FILL;
+ values[i].setLayoutData(fullHorizontal);
+
+ //values[i].setText(data[i]);
+ values[i].addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ updateQuery();
+ }
+ });
+ }
+ query = new Label(container, SWT.WRAP);
+ GridData gridData = new GridData();
+ gridData.horizontalSpan = layout.numColumns;
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ query.setLayoutData(gridData);
+
+ setControl(container);
+ updateQuery();
+
+ setPageComplete(true);
+ }
+ public void updateQuery() {
+ System.out.println("Updating query"); //$NON-NLS-1$
+ StringBuffer valuesClause = new StringBuffer();
+ StringBuffer namesClause = new StringBuffer();
+ Bookmark bookmark = row.getBookmark();
+ Entity entity = row.getEntity();
+ DatabaseAdapter adapter = AdapterFactory.getInstance().getAdapter(bookmark.getType());
+
+ numColumns = 0;
+ for (int i = 0; i < columnNames.length; i++) {
+ String name = columnNames[i];
+ String value = values[i].getText();
+ if (value.length() > 0) {
+ if (numColumns > 0) {
+ valuesClause.append(", "); //$NON-NLS-1$
+ namesClause.append(", ");
+ }
+ appendColumn(valuesClause, entity, name, adapter, value);
+ namesClause.append(name);
+ numColumns++;
+ }
+ }
+
+ String query = "INSERT INTO " + row.getTable(); //$NON-NLS-1$
+ if (numColumns > 0) {
+ query += " (" + namesClause + ")";
+ query += " VALUES " + "(" + valuesClause; //$NON-NLS-1$
+ query += " )"; //$NON-NLS-1$
+ }
+ this.query.setText(query);
+ }
+ /* (non-Javadoc)
+ * @see com.quantum.wizards.BaseSQLPage#getQueryText()
+ */
+ protected String getQueryText() {
+ return this.query.getText();
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.sql.TableRow;
+import com.quantum.view.tableview.TableAdapter;
+
+import org.eclipse.jface.wizard.IWizardPage;
+
+public interface SQLPage extends IWizardPage {
+ public void init(TableRow row, TableAdapter adapter);
+ public boolean performFinish();
+}
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.sql.TableRow;
+import com.quantum.view.tableview.TableAdapter;
+
+import org.eclipse.jface.wizard.Wizard;
+
+public class SQLRowWizard extends Wizard {
+ SQLPage page;
+ TableRow row;
+ TableAdapter adapter;
+ public void init(String title, SQLPage page, TableRow row, TableAdapter adapter) {
+ System.out.println("Init SQL row wizard"); //$NON-NLS-1$
+ this.row = row;
+ this.adapter = adapter;
+ this.page = page;
+ setWindowTitle(title);
+ }
+ public boolean performFinish() {
+ System.out.println("Perform SQL row wizard finish"); //$NON-NLS-1$
+ return page.performFinish();
+ }
+ public void addPages() {
+ System.out.println("QL row wizard adding pages"); //$NON-NLS-1$
+ page.init(row, adapter);
+ addPage(page);
+ }
+}
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.sql.FilterSort;
+import com.quantum.sql.TableRow;
+import com.quantum.view.tableview.TableAdapter;
+import com.quantum.view.tableview.TableView;
+
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class SortFilterPage extends WizardPage implements SQLPage {
+ TableRow row;
+ TableAdapter adapter;
+ Button[] filter;
+ Combo[] operator;
+ Text[] filterValues;
+ Button[] stringFlags;
+ Button[] sort;
+ Combo[] ascDesc;
+
+ String columnNames[];
+ Label query;
+ FilterSort filterSort = new FilterSort();
+ public SortFilterPage(String pageName) {
+ super(pageName);
+ }
+
+ public void init(TableRow row, TableAdapter adapter) {
+ this.row = row;
+ this.adapter = adapter;
+ }
+
+ public void createControl(Composite parent) {
+ System.out.println("page create control"); //$NON-NLS-1$
+
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ int layoutColumns = 6;
+ layout.numColumns = layoutColumns;
+
+ if (row == null) {
+ System.out.println("Row is null"); //$NON-NLS-1$
+ }
+ if (row.getColumnNames() == null) {
+ System.out.println("Columns are null"); //$NON-NLS-1$
+ }
+ if (row.getTableData() == null) {
+ System.out.println("Data is null"); //$NON-NLS-1$
+ }
+
+ columnNames = row.getColumnNames();
+ String[] data = row.getTableData();
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ System.out.println("data = " + i + "=" + data[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ System.out.println("column = " + i + "=" + columnNames[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ int size = row.getColumnCount();
+ filter = new Button[size];
+ operator = new Combo[size];
+ filterValues = new Text[size];
+ stringFlags = new Button[size];
+ sort = new Button[size];
+ ascDesc = new Combo[size];
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ filter[i] = new Button(container, SWT.CHECK);
+ filter[i].setText(columnNames[i]);
+ filter[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ updateQuery();
+ }
+ });
+
+ operator[i] = new Combo(container, SWT.SINGLE | SWT.READ_ONLY);
+ operator[i].add("="); //$NON-NLS-1$
+ operator[i].add("<>"); //$NON-NLS-1$
+ operator[i].add("<"); //$NON-NLS-1$
+ operator[i].add(">"); //$NON-NLS-1$
+ operator[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ updateQuery();
+ }
+ });
+
+ filterValues[i] = new Text(container, SWT.BORDER);
+ filterValues[i].setText(data[i]);
+ filterValues[i].addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ updateQuery();
+ }
+ });
+
+ stringFlags[i] = new Button(container, SWT.CHECK);
+ stringFlags[i].setText("String"); //$NON-NLS-1$
+ stringFlags[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ updateQuery();
+ }
+ });
+
+ final int index = i;
+ sort[i] = new Button(container, SWT.CHECK);
+ sort[i].setText(columnNames[i]);
+ sort[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ if (sort[index].getSelection()) {
+ filterSort.addSort(columnNames[index], ascDesc[index].getText());
+ } else {
+ filterSort.removeSort(columnNames[index]);
+ }
+ updateQuery();
+ }
+ });
+
+ ascDesc[i] = new Combo(container, SWT.SINGLE | SWT.READ_ONLY);
+ ascDesc[i].add(""); //$NON-NLS-1$
+ ascDesc[i].add("ASC"); //$NON-NLS-1$
+ ascDesc[i].add("DESC"); //$NON-NLS-1$
+ ascDesc[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ if (sort[index].getSelection()) {
+ filterSort.addSort(columnNames[index], ascDesc[index].getText());
+ } else {
+ filterSort.removeSort(columnNames[index]);
+ }
+ updateQuery();
+ }
+ });
+ }
+ query = new Label(container, SWT.WRAP);
+ GridData gridData = new GridData();
+ gridData.horizontalSpan = layoutColumns;
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ query.setLayoutData(gridData);
+
+ setControl(container);
+
+ setPageComplete(true);
+ }
+
+ public void updateQuery() {
+ filterSort.clearFilters();
+ for (int i = 0; i < filter.length; i++) {
+ if (filter[i].getSelection()) {
+ filterSort.addFilter(filter[i].getText(), operator[i].getText(), filterValues[i].getText(), stringFlags[i].getSelection());
+ }
+ }
+ query.setText(filterSort.toString());
+ }
+
+ public boolean performFinish() {
+ adapter.setFilterSort(filterSort);
+ TableView.getInstance().refreshCurrent();
+ return true;
+ }
+}
--- /dev/null
+package com.quantum.wizards;
+
+import com.quantum.Messages;
+import com.quantum.adapters.AdapterFactory;
+import com.quantum.adapters.DatabaseAdapter;
+import com.quantum.model.Bookmark;
+import com.quantum.model.Entity;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class UpdateRowPage extends BaseSQLPage implements SQLPage {
+ String[] columnNames;
+ Text[] oldValues;
+ Text[] newValues;
+ Button[] primaryKeys;
+ Button[] setValues;
+ Label query;
+ public UpdateRowPage(String pageName) {
+ super(pageName);
+ }
+
+ public void createControl(Composite parent) {
+ System.out.println("page create control"); //$NON-NLS-1$
+ Composite container = new Composite(parent, SWT.V_SCROLL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ Entity entity = row.getEntity();
+
+ int layoutColumns = 5;
+ layout.numColumns = layoutColumns;
+
+ if (row == null) {
+ System.out.println("Row is null"); //$NON-NLS-1$
+ }
+ if (row.getColumnNames() == null) {
+ System.out.println("Columns are null"); //$NON-NLS-1$
+ }
+ if (row.getTableData() == null) {
+ System.out.println("Data is null"); //$NON-NLS-1$
+ }
+ columnNames = row.getColumnNames();
+ String[] data = row.getTableData();
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ System.out.println("data = " + i + "=" + data[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ System.out.println("column = " + i + "=" + columnNames[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ oldValues = new Text[row.getColumnCount()];
+ newValues = new Text[row.getColumnCount()];
+ primaryKeys = new Button[row.getColumnCount()];
+ setValues = new Button[row.getColumnCount()];
+ Label temp = new Label(container, SWT.NULL);
+ temp.setText(Messages.getString("UpdateRowPage.ColumnName")); //$NON-NLS-1$
+ temp = new Label(container, SWT.NULL);
+ temp.setText(Messages.getString("UpdateRowPage.OldValue")); //$NON-NLS-1$
+ temp = new Label(container, SWT.NULL);
+ temp.setText(""); //$NON-NLS-1$
+ temp = new Label(container, SWT.NULL);
+ temp.setText(Messages.getString("UpdateRowPage.NewValue")); //$NON-NLS-1$
+ temp = new Label(container, SWT.NULL);
+ temp.setText(Messages.getString("UpdateRowPage._13")); //$NON-NLS-1$
+ for (int i = 0; i < row.getColumnCount(); i++) {
+ Label label = new Label(container, SWT.NULL);
+ label.setText(columnNames[i]);
+ oldValues[i] = new Text(container, SWT.BORDER | SWT.SINGLE);
+ oldValues[i].setText(data[i]);
+ oldValues[i].addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ updateQuery();
+ }
+ });
+ primaryKeys[i] = new Button(container, SWT.CHECK);
+ primaryKeys[i].setText("Where"); //$NON-NLS-1$
+ if (entity != null && entity.getColumn(columnNames[i]).isPrimaryKey())
+ primaryKeys[i].setSelection(true);
+ primaryKeys[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ updateQuery();
+ }
+ });
+ newValues[i] = new Text(container, SWT.BORDER | SWT.SINGLE);
+ newValues[i].setText(data[i]);
+ newValues[i].addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ updateQuery();
+ }
+ });
+ setValues[i] = new Button(container, SWT.CHECK);
+ setValues[i].setText(Messages.getString("UpdateRowPage.SetValue")); //$NON-NLS-1$
+ setValues[i].addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ updateQuery();
+ }
+ });
+ }
+ query = new Label(container, SWT.WRAP | SWT.V_SCROLL);
+ GridData gridData = new GridData();
+ gridData.horizontalSpan = layoutColumns;
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.verticalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ gridData.grabExcessVerticalSpace = true;
+ query.setLayoutData(gridData);
+
+ setControl(container);
+ updateQuery();
+
+ setPageComplete(true);
+ }
+ public void updateQuery() {
+ System.out.println("Updating query"); //$NON-NLS-1$
+ StringBuffer setClause = new StringBuffer();
+ StringBuffer whereClause = new StringBuffer();
+ Bookmark bookmark = row.getBookmark();
+ Entity entity = row.getEntity();
+ DatabaseAdapter adapter = AdapterFactory.getInstance().getAdapter(bookmark.getType());
+
+ int numValuesSet = 0;
+ int numValuesWhere = 0;
+ for (int i = 0; i < columnNames.length; i++) {
+ if (primaryKeys[i].getSelection()) {
+ String value = oldValues[i].getText();
+ if (numValuesWhere > 0) whereClause.append(" AND "); //$NON-NLS-1$
+ whereClause.append("("); //$NON-NLS-1$
+ whereClause.append(columnNames[i]);
+ whereClause.append(" = "); //$NON-NLS-1$
+ appendColumn(whereClause, entity, columnNames[i], adapter, value);
+ whereClause.append(")"); //$NON-NLS-1$
+ numValuesWhere++;
+ }
+ if (setValues[i].getSelection()) {
+ String value = newValues[i].getText();
+ if (numValuesSet > 0) setClause.append(", "); //$NON-NLS-1$
+ setClause.append(columnNames[i]);
+ setClause.append(" = "); //$NON-NLS-1$
+ appendColumn(setClause, entity, columnNames[i], adapter, value);
+ numValuesSet++;
+ }
+ }
+ String query = "UPDATE " + row.getTable(); //$NON-NLS-1$
+ query += " SET " + setClause.toString(); //$NON-NLS-1$
+ query += " WHERE " + whereClause.toString(); //$NON-NLS-1$
+ this.query.setText(query);
+ }
+
+ /* (non-Javadoc)
+ * @see com.quantum.wizards.BaseSQLPage#getQueryText()
+ */
+ protected String getQueryText() {
+ return query.getText();
+ }
+
+}
\ No newline at end of file