You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(8) |
Oct
(34) |
Nov
(7) |
Dec
(2) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(29) |
Feb
(10) |
Mar
(14) |
Apr
(4) |
May
(2) |
Jun
|
Jul
(14) |
Aug
(25) |
Sep
(6) |
Oct
(18) |
Nov
(4) |
Dec
(14) |
2009 |
Jan
(28) |
Feb
(15) |
Mar
(15) |
Apr
(8) |
May
|
Jun
|
Jul
(1) |
Aug
(4) |
Sep
(12) |
Oct
(1) |
Nov
|
Dec
(22) |
2010 |
Jan
(14) |
Feb
|
Mar
(2) |
Apr
|
May
(7) |
Jun
|
Jul
(3) |
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
From: SVN by r. <sv...@ca...> - 2008-08-29 09:52:05
|
Author: roy Date: 2008-08-29 11:51:53 +0200 (Fri, 29 Aug 2008) New Revision: 301 Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: small cleanup Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-28 08:08:11 UTC (rev 300) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-29 09:51:53 UTC (rev 301) @@ -19,8 +19,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; import jcurses.event.ActionEvent; import jcurses.event.ActionListener; import jcurses.system.CharColor; |
From: SVN by r. <sv...@ca...> - 2008-08-28 08:08:23
|
Author: roy Date: 2008-08-28 10:08:11 +0200 (Thu, 28 Aug 2008) New Revision: 300 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: output 'direct' commands as well Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-24 20:18:29 UTC (rev 299) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-28 08:08:11 UTC (rev 300) @@ -423,6 +423,7 @@ Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); } } + output(cmd.sql.getLines()); repaint(); if (/*direct ||*/ !cmd.cmd.backgroundProcessSupported()) { @@ -968,6 +969,8 @@ Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); } } + output(sqlCommand.getLines()); + //repaint(); output(command.execute(sqlCommand)); repaint(); return true; |
From: SVN by r. <sv...@ca...> - 2008-08-24 20:18:38
|
Author: roy Date: 2008-08-24 22:18:29 +0200 (Sun, 24 Aug 2008) New Revision: 299 Modified: ChangeLog Log: mention changes Modified: ChangeLog =================================================================== --- ChangeLog 2008-08-24 20:18:18 UTC (rev 298) +++ ChangeLog 2008-08-24 20:18:29 UTC (rev 299) @@ -8,6 +8,7 @@ * Added dump/read command to dump (a part of) a table * Tab completion case sensitive fix (For example jo<tab> -> Job) * Add tab completion to spool command + * Fix error message in @ command when file could not be read 0.5 (2008-03-14) * Allow for commands to start in the background, this will allow to continue |
From: SVN by r. <sv...@ca...> - 2008-08-24 20:18:30
|
Author: roy Date: 2008-08-24 22:18:18 +0200 (Sun, 24 Aug 2008) New Revision: 298 Modified: src/test/java/nl/improved/sqlclient/commands/ShowCommandTest.java Log: fix test compilation Modified: src/test/java/nl/improved/sqlclient/commands/ShowCommandTest.java =================================================================== --- src/test/java/nl/improved/sqlclient/commands/ShowCommandTest.java 2008-08-24 18:49:27 UTC (rev 297) +++ src/test/java/nl/improved/sqlclient/commands/ShowCommandTest.java 2008-08-24 20:18:18 UTC (rev 298) @@ -33,7 +33,7 @@ public void testGetTabCompletionInfo() { ShowCommand cmd = new ShowCommand(); SQLCommand sqlCommand = new SQLCommand(); - sqlCommand.getEditableLines().add(new StringBuilder("SHOW TABLES HAVING ")); + sqlCommand.getEditableLines().add(new StringBuffer("SHOW TABLES HAVING ")); Point cursorPos = new Point(sqlCommand.getLines().get(0).length(),0); TabCompletionInfo info = cmd.getTabCompletionInfo(sqlCommand, cursorPos); assertNotNull(info); |
From: SVN by r. <sv...@ca...> - 2008-08-24 18:49:41
|
Author: roy Date: 2008-08-24 20:49:27 +0200 (Sun, 24 Aug 2008) New Revision: 297 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: don't return 'succesfully' when failed to read file to be executed '@' Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-23 12:32:57 UTC (rev 296) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-24 18:49:27 UTC (rev 297) @@ -1961,14 +1961,15 @@ }.start(); } } + if (cancelled) { + return "Execution of file '" + toFileName(command.substring(1)) +"' aborted...."; + } + return "File '" + toFileName(command.substring(1)) +"' executed successfully."; } catch(IOException e) { error(e); + return "File '" + toFileName(command.substring(1)) +"' ended with errors."; } finally { if (fin != null) try { fin.close();}catch(Exception e) {/*ignore*/} - if (cancelled) { - return "Execution of file '" + toFileName(command.substring(1)) +"' aborted...."; - } - return "File '" + toFileName(command.substring(1)) +"' executed successfully."; } } |
From: SVN by r. <sv...@ca...> - 2008-08-23 12:33:07
|
Author: roy Date: 2008-08-23 14:32:57 +0200 (Sat, 23 Aug 2008) New Revision: 296 Modified: pom.xml Log: java 6-5 fixes Modified: pom.xml =================================================================== --- pom.xml 2008-08-23 12:32:42 UTC (rev 295) +++ pom.xml 2008-08-23 12:32:57 UTC (rev 296) @@ -28,8 +28,8 @@ <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> - <source>1.6</source> - <target>1.6</target> + <source>1.5</source> + <target>1.5</target> </configuration> </plugin> </plugins> |
From: SVN by r. <sv...@ca...> - 2008-08-23 12:32:53
|
Author: roy Date: 2008-08-23 14:32:42 +0200 (Sat, 23 Aug 2008) New Revision: 295 Modified: src/main/java/nl/improved/sqlclient/DBConnector.java Log: java 6-5 fixes Modified: src/main/java/nl/improved/sqlclient/DBConnector.java =================================================================== --- src/main/java/nl/improved/sqlclient/DBConnector.java 2008-08-23 12:32:22 UTC (rev 294) +++ src/main/java/nl/improved/sqlclient/DBConnector.java 2008-08-23 12:32:42 UTC (rev 295) @@ -162,7 +162,9 @@ try { Class.forName(settings.getDriver()); } catch (ClassNotFoundException e) { - throw new SQLException("Failed to connect: Could not initialize driver '"+settings.getDriver()+"'", e); + SQLException se = new SQLException("Failed to connect: Could not initialize driver '"+settings.getDriver()+"'"); + se.initCause(e); + throw se; } |
From: SVN by r. <sv...@ca...> - 2008-08-23 12:32:34
|
Author: roy Date: 2008-08-23 14:32:22 +0200 (Sat, 23 Aug 2008) New Revision: 294 Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: trim debug string to max size of screen width Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-22 07:51:14 UTC (rev 293) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-23 12:32:22 UTC (rev 294) @@ -285,6 +285,9 @@ } Toolkit.printString(cursorChar, Screen.PROMPT.length() +"> ".length() + cursorPosition.x, lineNr-(commandLines.getLines().size() -cursorPosition.y)-startLine, color); if (debugString != null) { + if (debugString.length() > Toolkit.getScreenWidth()) { + debugString = debugString.substring(0, Toolkit.getScreenWidth()-1); + } color = new CharColor(CharColor.BLUE, CharColor.YELLOW); Toolkit.printString(debugString, 1, getScreenHeight()-1, color); } |
From: SVN by r. <sv...@ca...> - 2008-08-22 07:51:26
|
Author: roy Date: 2008-08-22 09:51:14 +0200 (Fri, 22 Aug 2008) New Revision: 293 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: made login dialog cause less problems (direct commands where still being executed in an other thread) Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 20:32:51 UTC (rev 292) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-22 07:51:14 UTC (rev 293) @@ -959,6 +959,19 @@ if (command == null) { return false; } + if (direct || !command.backgroundProcessSupported()) { + while (commandQueue.size() != 0) { + debug("Waiting for command queue to be cleared"); + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); + } + } + output(command.execute(sqlCommand)); + repaint(); + return true; + } commandQueue.add(new CommandInfo(sqlCommand, command)); return true; } @@ -1636,10 +1649,10 @@ if (columnType == Types.BINARY || columnType == Types.BLOB || columnType == Types.CLOB || - columnType == Types.LONGNVARCHAR || + //columnType == Types.LONGNVARCHAR || // jdk 1.6 columnType == Types.LONGVARBINARY || columnType == Types.LONGVARCHAR || - columnType == Types.NCLOB || + //columnType == Types.NCLOB || // jdk 1.6 columnType == Types.OTHER) { return true; } |
From: SVN by r. <sv...@ca...> - 2008-08-19 20:32:59
|
Author: roy Date: 2008-08-19 22:32:51 +0200 (Tue, 19 Aug 2008) New Revision: 292 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: some code cleanups Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 20:30:37 UTC (rev 291) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 20:32:51 UTC (rev 292) @@ -1629,10 +1629,28 @@ return false; } } + private abstract class ReadDumpCommand implements Command { + public static final String DATE_FORMAT = "yyyyMMddHHmmss"; + + boolean isBinary(int columnType) { + if (columnType == Types.BINARY || + columnType == Types.BLOB || + columnType == Types.CLOB || + columnType == Types.LONGNVARCHAR || + columnType == Types.LONGVARBINARY || + columnType == Types.LONGVARCHAR || + columnType == Types.NCLOB || + columnType == Types.OTHER) { + return true; + } + return false; + + } + } /** * Writes the result of a query into a dump file so that it can be read back. */ - private class DumpCommand implements Command { + private class DumpCommand extends ReadDumpCommand { private String fileName; @Override @@ -1672,7 +1690,7 @@ Connection c = DBConnector.getInstance().getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery(query); - SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); + SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); while (rs.next()) { atts.clear(); hd.startElement("","","row",atts); @@ -1687,14 +1705,7 @@ String dateString = formatter.format(date); hd.characters(dateString.toCharArray(), 0, dateString.length()); } - } else if (metaData.getColumnType(col) == Types.BINARY || - metaData.getColumnType(col) == Types.BLOB || - metaData.getColumnType(col) == Types.CLOB || - metaData.getColumnType(col) == Types.LONGNVARCHAR || - metaData.getColumnType(col) == Types.LONGVARBINARY || - metaData.getColumnType(col) == Types.LONGVARCHAR || - metaData.getColumnType(col) == Types.NCLOB || - metaData.getColumnType(col) == Types.OTHER) { + } else if (isBinary(metaData.getColumnType(col))) { atts.addAttribute("","","type","","binary"); hd.startElement("","","col",atts); @@ -1786,7 +1797,7 @@ /** * Read the result of a dump file. */ - private class ReadCommand implements Command { + private class ReadCommand extends ReadDumpCommand { private String fileName; @Override @@ -1834,7 +1845,7 @@ query = query + values +")"; Connection c = DBConnector.getInstance().getConnection(); PreparedStatement pstmt = c.prepareStatement(query); - SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); + SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); for (int nodeNr = 0; nodeNr < nodeList.getLength(); nodeNr++) { Element row = (Element) nodeList.item(nodeNr); // row NodeList columns = row.getElementsByTagName("col"); |
From: SVN by r. <sv...@ca...> - 2008-08-19 20:30:47
|
Author: roy Date: 2008-08-19 22:30:37 +0200 (Tue, 19 Aug 2008) New Revision: 291 Added: src/main/java/nl/improved/sqlclient/history/ src/main/java/nl/improved/sqlclient/history/HistoryPersister.java src/main/java/nl/improved/sqlclient/history/exception/ src/main/java/nl/improved/sqlclient/history/exception/CouldNotLoadHistoryException.java src/main/java/nl/improved/sqlclient/history/exception/CouldNotSaveHistoryException.java src/main/java/nl/improved/sqlclient/history/scrapbook.jpage Log: history persister classes created by Alarc?\195?\179n Vladimir <vla...@ya...> small adjustments to make it compatible with the current svn version made by me (roy van der kuil) Added: src/main/java/nl/improved/sqlclient/history/HistoryPersister.java =================================================================== --- src/main/java/nl/improved/sqlclient/history/HistoryPersister.java 2008-08-19 11:23:25 UTC (rev 290) +++ src/main/java/nl/improved/sqlclient/history/HistoryPersister.java 2008-08-19 20:30:37 UTC (rev 291) @@ -0,0 +1,209 @@ +/* + * Copyright 2008 Alarcón Vladimir <vla...@ya...> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package nl.improved.sqlclient.history; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import nl.improved.sqlclient.AbstractSQLShellWindow; +import nl.improved.sqlclient.SQLCommand; +import nl.improved.sqlclient.SQLShell; +import nl.improved.sqlclient.history.exception.CouldNotLoadHistoryException; +import nl.improved.sqlclient.history.exception.CouldNotSaveHistoryException; + +/** + * Class for handling the persistance of the command history. + */ +public class HistoryPersister { + + /** + * Base path file name. + */ + private final static String BASE_PATH = "history"; + + /** + * Default empty command. + */ + private final static SQLCommand EMPTY_COMMAND = new SQLCommand(); + + /** + * I use "Half Width white circle" as an encoded new line. + */ + private static char ENCODED_NEW_LINE = '\u0009'; + + /** + * Load command history into the sqlshell. + * @param shell the shell to load the history into + * @param key the key to load the history for (connection identifier) + * @param firstLineWith + * @param nextLineWidth + */ + public static int loadHistory(final AbstractSQLShellWindow shell, final String key, + final int firstLineWidth, final int nextLineWidth) + throws CouldNotLoadHistoryException { + + List<SQLCommand> history = shell.getCommandHistory(); + history.clear(); + + log("loading history..."); + String fileName = buildHistoryFileName(key); + File f = new File(fileName); + log("loading history... file=" + f.getAbsolutePath()); + try { + BufferedReader r = new BufferedReader(new FileReader(fileName)); + log("ok 1"); + String line = null; + int tot = 0; + while ((line = r.readLine()) != null) { + if (line.trim().length() != 0) { + tot++; + log("ok tot=" + tot + " line=" + line); + SQLCommand sc = parseCommand(line, firstLineWidth, nextLineWidth); + history.add(sc); + } + } + log("ok 2"); + r.close(); + shell.setCommandIndex(history.size() - 1); + return tot; + } catch (IOException e) { + history.add(EMPTY_COMMAND); + shell.setCommandIndex(0); + throw new CouldNotLoadHistoryException(e); + } + } + + /** + * Save command history from sqlshell. + * @param shell the shell to save the history from + * @param key the key to store the history for (connection identifier) + * @param excludeLastCommand + */ + public static void saveHistory(final AbstractSQLShellWindow shell, final String key, + final boolean excludeLastCommand) throws CouldNotSaveHistoryException { + List<SQLCommand> history = shell.getCommandHistory(); + int commandIndex = shell.getCommandIndex(); + + log("saving history... (" + history.size() + " commands)"); + + File dir = new File(buildHistoryDir()); + if (!dir.exists()) { + dir.mkdirs(); + } + String fileName = buildHistoryFileName(key); + try { + File f = new File(fileName); + log("file=" + f.getAbsolutePath()); + BufferedWriter w = new BufferedWriter(new FileWriter(f)); + int tot = 0; + for (Iterator it = history.iterator(); it.hasNext();) { + SQLCommand c = (SQLCommand) it.next(); + if (excludeLastCommand && it.hasNext()) { + tot++; + w.write(renderCommand(c)); + w.write("\n"); + } + } + w.close(); + log("history size saved: " + tot); + } catch (IOException e) { + throw new CouldNotSaveHistoryException(e); + } + } + + + private static String renderCommand(final SQLCommand c) { + + // First, I filter: I only leave non-blank lines. + List<String> cleanLines = new ArrayList<String>(); + for (CharSequence line : c.getLines()) { + if (line != null) { + String tLine = line.toString().trim(); + if (tLine.length() > 0) { + cleanLines.add(tLine); + } + } + } + + // Then, I store the lines, adding an encoded newline. + StringBuffer sb = new StringBuffer(); + for (Iterator it = cleanLines.iterator(); it.hasNext();) { + String line = (String) it.next(); + sb.append(line); + if (it.hasNext()) { + sb.append(ENCODED_NEW_LINE); + } + } + + return sb.toString(); + } + + private static SQLCommand parseCommand(final String s, + final int firstLineWidth, final int nextLineWidth) { + SQLCommand c = new SQLCommand(); + List<StringBuffer> lines = c.getEditableLines(); // TODO change to not editable lines + + String[] chunks = s.split("" + ENCODED_NEW_LINE); + for (int i = 0; i < chunks.length; i++) { + log("chunk " + i + "='" + chunks[i] + "'"); + int width = (i == 0) ? firstLineWidth : nextLineWidth; + fit(chunks[i], lines, width); + } + return c; + } + + private static void fit(final String s, final List<StringBuffer> lines, + final int width) { + int pos = 0; + while ((s.length() - pos) > width) { + int sep = s.lastIndexOf(" ", pos + width); + if (sep > pos) { + log("*** SECTION adding chunk '" + s.substring(pos, sep) + "' pos=" + + pos + " sep=" + sep); + lines.add(new StringBuffer(s.substring(pos, sep))); + pos = sep + 1; + } else { + sep = pos + width; + log("*** NO-SEP adding chunk '" + s.substring(pos, sep) + "' pos=" + + pos + " sep=" + sep); + lines.add(new StringBuffer(s.substring(pos, sep))); + pos = sep; + } + } + log("*** END adding chunk '" + s.substring(pos) + "' pos=" + pos + + " length=" + s.length()); + lines.add(new StringBuffer(s.substring(pos))); + } + + private static String buildHistoryDir() { + return BASE_PATH; + } + + private static String buildHistoryFileName(final String key) { + return BASE_PATH + "/" + key + ".history"; + } + + private static void log(final String txt) { +// System.out.println(txt); + } +} Added: src/main/java/nl/improved/sqlclient/history/exception/CouldNotLoadHistoryException.java =================================================================== --- src/main/java/nl/improved/sqlclient/history/exception/CouldNotLoadHistoryException.java 2008-08-19 11:23:25 UTC (rev 290) +++ src/main/java/nl/improved/sqlclient/history/exception/CouldNotLoadHistoryException.java 2008-08-19 20:30:37 UTC (rev 291) @@ -0,0 +1,55 @@ +/* + * Copyright 2008 Alarcón Vladimir <vla...@ya...> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package nl.improved.sqlclient.history.exception; + +/** + * Exception thrown when the command history could not be loaded. + */ +public class CouldNotLoadHistoryException extends Exception { + + /** + * Default constructor. + */ + public CouldNotLoadHistoryException() { + super(); + } + + /** + * Constructor. + * @param message the reason this exception whas thrown + * @param cause the root cause of this exception + */ + public CouldNotLoadHistoryException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor. + * @param message the reason this exception whas thrown + */ + public CouldNotLoadHistoryException(String message) { + super(message); + } + + /** + * Constructor. + * @param cause the root cause of this exception + */ + public CouldNotLoadHistoryException(Throwable cause) { + super(cause); + } + +} Added: src/main/java/nl/improved/sqlclient/history/exception/CouldNotSaveHistoryException.java =================================================================== --- src/main/java/nl/improved/sqlclient/history/exception/CouldNotSaveHistoryException.java 2008-08-19 11:23:25 UTC (rev 290) +++ src/main/java/nl/improved/sqlclient/history/exception/CouldNotSaveHistoryException.java 2008-08-19 20:30:37 UTC (rev 291) @@ -0,0 +1,55 @@ +/* + * Copyright 2008 Alarcón Vladimir <vla...@ya...> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package nl.improved.sqlclient.history.exception; + +/** + * Exception thrown when the command history could not be saved. + */ +public class CouldNotSaveHistoryException extends Exception { + + /** + * Default constructor. + */ + public CouldNotSaveHistoryException() { + super(); + } + + /** + * Constructor. + * @param message the reason this exception whas thrown + * @param cause the root cause of this exception + */ + public CouldNotSaveHistoryException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor. + * @param message the reason this exception whas thrown + */ + public CouldNotSaveHistoryException(String message) { + super(message); + } + + /** + * Constructor. + * @param cause the root cause of this exception + */ + public CouldNotSaveHistoryException(Throwable cause) { + super(cause); + } + +} Added: src/main/java/nl/improved/sqlclient/history/scrapbook.jpage =================================================================== --- src/main/java/nl/improved/sqlclient/history/scrapbook.jpage 2008-08-19 11:23:25 UTC (rev 290) +++ src/main/java/nl/improved/sqlclient/history/scrapbook.jpage 2008-08-19 20:30:37 UTC (rev 291) @@ -0,0 +1,13 @@ + +java.io.BufferedReader r = new java.io.BufferedReader(new java.io.FileReader("history/one.properties")); + System.out.println("ok 1"); + String line = null; + int tot = 0; + while ((line = r.readLine()) != null) { + if (line.trim().length() != 0) { + tot++; + System.out.println("ok tot="+tot); + } + } + + \ No newline at end of file |
From: SVN by r. <sv...@ca...> - 2008-08-19 11:23:35
|
Author: roy Date: 2008-08-19 13:23:25 +0200 (Tue, 19 Aug 2008) New Revision: 290 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: some initial tab completion for dump Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 11:10:00 UTC (rev 289) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 11:23:25 UTC (rev 290) @@ -1760,8 +1760,14 @@ */ @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; + List<String> commandInfo = new ArrayList<String>(2); + commandInfo.add("SELECT * FROM"); + commandInfo.add(command.getCommandString().substring("dump ".length())); + debug(commandInfo.toString()); + Point point = new Point(commandPoint.x - "dump ".length(), commandPoint.y+1); + return SQLUtil.getTabCompletionInfo(commandInfo, point); } + @Override public CharSequence getHelp() { return "tablename [where clause]\n" + |
From: SVN by r. <sv...@ca...> - 2008-08-19 11:10:10
|
Author: roy Date: 2008-08-19 13:10:00 +0200 (Tue, 19 Aug 2008) New Revision: 289 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: add tab completion to read command Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 11:05:39 UTC (rev 288) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 11:10:00 UTC (rev 289) @@ -1873,8 +1873,10 @@ */ @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; // TODO + String fn = command.getCommandString().substring("read".length()).trim(); + return getFileNameTabCompletionInfo(fn); } + @Override public CharSequence getHelp() { return "filename: read dump file from filename\n"+ @@ -2119,11 +2121,18 @@ } + /** + * The key action interface. + * Implement this interface for handling key actions. + */ private interface KeyAction { void execute(); CharSequence getHelp(); } + /** + * Simple class that holds the SQLCommand and it's matching Command information. + */ private class CommandInfo { private SQLCommand sql; private Command cmd; |
From: SVN by r. <sv...@ca...> - 2008-08-19 11:05:50
|
Author: roy Date: 2008-08-19 13:05:39 +0200 (Tue, 19 Aug 2008) New Revision: 288 Modified: ChangeLog Log: mention changes Modified: ChangeLog =================================================================== --- ChangeLog 2008-08-19 11:00:11 UTC (rev 287) +++ ChangeLog 2008-08-19 11:05:39 UTC (rev 288) @@ -7,6 +7,7 @@ * Fix for quit on some systems (hardy heron for example) * Added dump/read command to dump (a part of) a table * Tab completion case sensitive fix (For example jo<tab> -> Job) + * Add tab completion to spool command 0.5 (2008-03-14) * Allow for commands to start in the background, this will allow to continue |
From: SVN by r. <sv...@ca...> - 2008-08-19 11:00:19
|
Author: roy Date: 2008-08-19 13:00:11 +0200 (Tue, 19 Aug 2008) New Revision: 287 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: add more comments add tabcompletion to spool command some code cleanups Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 10:59:06 UTC (rev 286) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 11:00:11 UTC (rev 287) @@ -1486,6 +1486,68 @@ } /** + * Returns tabcompletion information based on a filename prefix input string. + * @param fileNamePrefix the filename prefix to search for matches + * @param otherMatches an optional list of other matches that are not filenames + * @return the tabcompletion information found based on the filename prefix and other matches (optional) + */ + private static TabCompletionInfo getFileNameTabCompletionInfo(String fileNamePrefix, String... otherMatches) { + String dirName; + if (fileNamePrefix.equals("")) { + fileNamePrefix = "."; + dirName = "."; + } else { + fileNamePrefix = toFileName(fileNamePrefix); + if (fileNamePrefix.indexOf('/') >= 0) { + File file = new File(fileNamePrefix); + if (file.isDirectory()) { + fileNamePrefix = ""; + dirName = file.getAbsolutePath()+"/"; + } else { + fileNamePrefix = file.getName(); + dirName = file.getParent(); + } + } else { + dirName = "."; + } + } + List<String> matches = new ArrayList<String>(10); + for (String otherMatch : otherMatches) { + matches.add(otherMatch); + } + matches.addAll(Arrays.asList(new File(dirName).list())); + return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER, matches, fileNamePrefix); + } + + /** + * Join two lines. + */ + private void joinLine() { + Point cursorPosition = screen.getCursorPosition(); + StringBuffer line = getEditableCommand().getEditableLines().remove(cursorPosition.y); + cursorPosition.y--; + StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + cursorPosition.x = lineBuffer.length(); + lineBuffer.append(line); + } + + /** + * Return true if the programm is still running. + * @return true if the program is still running + */ + protected boolean isRunning() { + return run; + } + + /** + * Returns the screen implementation. + * @return the screen. + */ + protected Screen getScreen() { + return screen; + } + + /** * Writes in/output to a file. */ private class SpoolCommand implements Command { @@ -1506,6 +1568,17 @@ return "No spool to close."; } } else { + StringBuffer returnValue = new StringBuffer(100); + if (spoolWriter != null) { + returnValue.append("Closing previous spool to : "); + returnValue.append(fileName); + returnValue.append('\n'); + try { + spoolWriter.close(); + } catch (IOException ex) { + /* ignore */ + } + } try { File f = new File(toFileName(nextPart.trim())); fileName = f.getAbsolutePath(); @@ -1516,7 +1589,8 @@ } catch (IOException e) { throw new IllegalStateException("Failed to create spool ("+fileName+"): " + e.toString(), e); } - return "Spool to "+fileName+" created."; + returnValue.append("Spool to "+fileName+" created."); + return returnValue.toString(); } } @@ -1533,6 +1607,11 @@ */ @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { + String cmd = command.getCommandString(); + if (cmd.startsWith("spool")) { + String fn = command.getCommandString().substring("spool".length()).trim(); // cutoff 'spool' + return getFileNameTabCompletionInfo(fn, "off"); + } return null; } @Override @@ -1875,26 +1954,7 @@ @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { String fileName = command.getCommandString().substring(1).trim(); // cutoff '@' - String dirName; - if (fileName.equals("")) { - fileName = "."; - dirName = "."; - } else { - fileName = toFileName(fileName); - if (fileName.indexOf('/') >= 0) { - File file = new File(fileName); - if (file.isDirectory()) { - fileName = ""; - dirName = file.getAbsolutePath()+"/"; - } else { - fileName = file.getName(); - dirName = file.getParent(); - } - } else { - dirName = "."; - } - } - return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER,Arrays.asList(new File(dirName).list()) , fileName); + return getFileNameTabCompletionInfo(fileName); } @Override @@ -1950,12 +2010,23 @@ } } + /** + * Command thread responsible for executing commands in the background. + * It holds a reference to the current command that is being executed. + */ private abstract class CommandThread extends Thread { private Command cmd; + /** + * Constructor. + * @param cmd the command to be executed in the background + */ public CommandThread(Command cmd) { this.cmd = cmd; } + /** + * Execute the command and disable prompt. + */ @Override public final void run() { screen.setShowPrompt(false); @@ -1968,20 +2039,35 @@ } } + /** + * Override to implement the execution of the command. + */ abstract void execute(); + /** + * Returns the command that is being executed by this thread. + * @return the command that is being executed by this thread. + */ Command getCommand() { return cmd; } } + /** + * Query command responsible for executing a sql query. + */ private class QueryCommand implements Command { /** - * Executor for SQL Statements + * Executor for SQL Statements. */ private StatementExecutor statementExecutor; + /** + * Execute the sql query. + * @param cmd the sqlcommand containing the sql query + * @return the result of the sql query. + */ @Override public CharSequence execute(SQLCommand cmd) { try { @@ -2010,6 +2096,7 @@ @Override public TabCompletionInfo getTabCompletionInfo(SQLCommand commandInfo, Point commandPoint) { // TODO call SQLUTil.. + debug("GET TAB COMPLETION OF QUERY COMMAND"); return null; } @@ -2031,23 +2118,7 @@ } - private void joinLine() { - Point cursorPosition = screen.getCursorPosition(); - StringBuffer line = getEditableCommand().getEditableLines().remove(cursorPosition.y); - cursorPosition.y--; - StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); - cursorPosition.x = lineBuffer.length(); - lineBuffer.append(line); - } - protected boolean isRunning() { - return run; - } - - protected Screen getScreen() { - return screen; - } - private interface KeyAction { void execute(); CharSequence getHelp(); |
From: SVN by r. <sv...@ca...> - 2008-08-19 10:59:16
|
Author: roy Date: 2008-08-19 12:59:06 +0200 (Tue, 19 Aug 2008) New Revision: 286 Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java Log: add information when no connection is opened Modified: src/main/java/nl/improved/sqlclient/commands/InfoCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2008-08-19 08:01:34 UTC (rev 285) +++ src/main/java/nl/improved/sqlclient/commands/InfoCommand.java 2008-08-19 10:59:06 UTC (rev 286) @@ -35,9 +35,15 @@ */ @Override public CharSequence execute(SQLCommand cmd) { - java.sql.Connection conn = DBConnector.getInstance().getConnection(); - StringBuilder returnValue = new StringBuilder(); + java.sql.Connection conn; try { + conn = DBConnector.getInstance().getConnection(); + } catch(IllegalStateException e) { + return "This command shows information about the current connection.\nCurrently SQLShell is not connected to a database server.\n"+ + "Please use the connect command to create a connection"; + } + StringBuffer returnValue = new StringBuffer(); + try { DatabaseMetaData metaData = conn.getMetaData(); returnValue.append("URL : "+ metaData.getURL()+"\n"); returnValue.append("User : "+ metaData.getUserName()+"\n"); |
From: SVN by r. <sv...@ca...> - 2008-08-19 08:01:46
|
Author: roy Date: 2008-08-19 10:01:34 +0200 (Tue, 19 Aug 2008) New Revision: 285 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/SQLCommand.java Log: use stringbuffer instead of stringbuilder since commands are used in a multithreaded environment Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-06 20:32:52 UTC (rev 284) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-19 08:01:34 UTC (rev 285) @@ -55,6 +55,9 @@ import javax.xml.transform.stream.StreamResult; import nl.improved.sqlclient.DBConnector.ConnectionSettings; import nl.improved.sqlclient.commands.*; +import nl.improved.sqlclient.history.HistoryPersister; +import nl.improved.sqlclient.history.exception.CouldNotLoadHistoryException; +import nl.improved.sqlclient.history.exception.CouldNotSaveHistoryException; import nl.improved.sqlclient.util.LimitedArrayList; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -70,6 +73,7 @@ */ public abstract class AbstractSQLShellWindow { + private String ident; /** * The current command thread executing a SQLShell command. */ @@ -262,7 +266,7 @@ joinLine(); } } else { - StringBuilder tmp = getEditableCommand().getEditableLines().get(cursorPosition.y); + StringBuffer tmp = getEditableCommand().getEditableLines().get(cursorPosition.y); if (cursorPosition.x > 0) { tmp.deleteCharAt(cursorPosition.x-1); cursorPosition.x--; @@ -278,9 +282,9 @@ @Override public void execute() { Point cursorPosition = screen.getCursorPosition(); - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); if (cursorPosition.x < lineBuffer.length()) { - StringBuilder tmp = getEditableCommand().getEditableLines().get(cursorPosition.y); + StringBuffer tmp = getEditableCommand().getEditableLines().get(cursorPosition.y); tmp.deleteCharAt(cursorPosition.x); } } @@ -326,7 +330,7 @@ } return; } - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); int previousBreak = SQLUtil.getLastBreakIndex(lineBuffer.substring(0, cursorPosition.x-1)); if (lineBuffer.charAt(previousBreak) == ' ' || lineBuffer.charAt(previousBreak) == '\t') { previousBreak++; @@ -344,11 +348,11 @@ public void execute() { Point cursorPosition = screen.getCursorPosition(); if (cursorPosition.x > 0) { - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); lineBuffer.delete(0, cursorPosition.x); cursorPosition.x = 0; } else if (cursorPosition.y > 0) { - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); if (lineBuffer.length() == 0) { commandLines.getEditableLines().remove(cursorPosition.y); } @@ -446,8 +450,28 @@ t.start(); } + /** + * Returns the current command history. + * @return + */ + public List<SQLCommand> getCommandHistory() { + return commandHistory; + } + public int getCommandIndex() { + return commandIndex; + } + /** + * Change the current command index. + * @param i + */ + public void setCommandIndex(int i) { + this.commandIndex = i; + } + + + /** * Return the visible screen width. * @return the visible screen width. */ @@ -458,6 +482,7 @@ */ public abstract int getScreenHeight(); + /** * Repaint the screen. */ @@ -530,10 +555,10 @@ /** * Add a new line to the command lines buffer. */ - private StringBuilder newLine() { + private StringBuffer newLine() { Point cursorPosition = screen.getCursorPosition(); cursorPosition.x = 0; - StringBuilder newLine = new StringBuilder(); + StringBuffer newLine = new StringBuffer(); getEditableCommand().getEditableLines().add(newLine); cursorPosition.y = commandLines.getLines().size()-1; return newLine; @@ -597,6 +622,7 @@ commandHistory.add(tmpLines); commandLines = tmpLines; } + commandHistory.remove(commandIndex); } if (!commandLines.getCommandString().equals("")) { commandLines = new SQLCommand(); @@ -628,8 +654,8 @@ newLine(); // TODO Fix return in middle of an other line } else { Point cursorPosition = screen.getCursorPosition(); - List<StringBuilder> editableLines = getEditableCommand().getEditableLines(); - StringBuilder currentLine = editableLines.get(cursorPosition.y); + List<StringBuffer> editableLines = getEditableCommand().getEditableLines(); + StringBuffer currentLine = editableLines.get(cursorPosition.y); if (cursorPosition.x > currentLine.length()) { for (int i = currentLine.length(); i < cursorPosition.x; i++) { currentLine.append(' '); @@ -649,18 +675,18 @@ // check if there are enough 'next' lines // if not.. add one if (editableLines.size()-1 == cursorPosition.y) { - StringBuilder newLine = new StringBuilder(); + StringBuffer newLine = new StringBuffer(); editableLines.add(newLine); } // check if the nextline has enough room for the new word // if not.. add a new line if (editableLines.get(cursorPosition.y+1).length() + (currentLine.length()-lastSpace+1) > screen.MAX_LINE_LENGTH) { - StringBuilder newLine = new StringBuilder(); + StringBuffer newLine = new StringBuffer(); editableLines.add(cursorPosition.y+1, newLine); } // fetch the next line - StringBuilder nextLine = editableLines.get(cursorPosition.y+1); + StringBuffer nextLine = editableLines.get(cursorPosition.y+1); // if the nextline already has some text.. add a space in front of it // if there is not already a 'breaking character' there if (nextLine.length() > 0 && ! SQLUtil.isBreakCharacter(nextLine.charAt(0))) { @@ -706,7 +732,7 @@ commandHistory.add(commandLines); } for (int i = 0; i < tmp.size(); i++) { - commandLines.getEditableLines().add(new StringBuilder(tmp.get(i))); + commandLines.getEditableLines().add(new StringBuffer(tmp.get(i))); } commandIndex = commandHistory.size()-1; } @@ -754,7 +780,8 @@ e.printStackTrace(new PrintWriter(sw)); sw.flush(); lastExceptionDetails = sw.toString(); - //output(sw.toString()); + //output(lastExceptionDetails); + //repaint(); } /** @@ -838,7 +865,7 @@ match = DBConnector.getInstance().translateDbVar(match); if (sub.length() > 0 && !match.startsWith(sub)) { // case insensitive change Point cursorPosition = screen.getCursorPosition(); - List<StringBuilder> lines = getEditableCommand().getEditableLines(); + List<StringBuffer> lines = getEditableCommand().getEditableLines(); if (lines.get(cursorPosition.y).length() >=sub.length()) { cursorPosition.x-=sub.length(); lines.get(cursorPosition.y).delete(cursorPosition.x, cursorPosition.x + sub.length()); @@ -956,13 +983,13 @@ private List<CharSequence> getLines(CharSequence text) { int maxWidth = getScreenWidth(); List<CharSequence> list = new ArrayList<CharSequence>(); - StringBuilder buffer = new StringBuilder(); + StringBuffer buffer = new StringBuffer(); for (int i=0; i<text.length(); i++) { char c = text.charAt(i); if (c=='\n' || buffer.length() == maxWidth) { String line = buffer.toString(); list.add(line); - buffer = new StringBuilder(); + buffer = new StringBuffer(); if (c != '\n') { buffer.append(c); } @@ -981,7 +1008,7 @@ /** * Convert a list to a presentable text devided into multiple columns. */ - private StringBuilder toColumns(List<? extends CharSequence> values) { + private StringBuffer toColumns(List<? extends CharSequence> values) { int maxWidth = 0; Iterator<? extends CharSequence> iValues = values.iterator(); while (iValues.hasNext()) { @@ -989,7 +1016,7 @@ } maxWidth+=2;// add extra space int nrOfColumns = (getScreenWidth()) / maxWidth; - StringBuilder returnValue = new StringBuilder(); + StringBuffer returnValue = new StringBuffer(); for (int row = 0; row < values.size(); row+=nrOfColumns) { for (int col = 0; col < nrOfColumns && row + col < values.size(); col++) { returnValue.append(values.get(row+col) + screen.getEmptyLine().substring(0, maxWidth - values.get(row+col).length())); @@ -1016,14 +1043,21 @@ if (cmdString.length() > 0 && cmdString.charAt(cmdString.length()-1) == ';') { cmdString = cmdString.substring(0, cmdString.length()-1); } - if (connect(cmdString) != null) { - return "Connected.\n\n"; - } else { + if (connect(cmdString) == null) { return "Connect failed. Unknown reason\n\n"; } } catch(SQLException e) { throw new IllegalStateException("Failed to connect: " + e.getMessage(), e); } + try { + int tot = HistoryPersister.loadHistory(AbstractSQLShellWindow.this, ident, + getScreen().MAX_LINE_LENGTH, getScreen().MAX_LINE_LENGTH); + return "Connected and history loaded (" + tot + " command(s)).\n\n"; + } catch (CouldNotLoadHistoryException e) { + // this.shell.setCommandIndex(0); + return "Connected (no history loaded).\n\n"; + } + } @Override public CharSequence getCommandString() { @@ -1056,11 +1090,14 @@ Iterator<String> idents = DBConnector.getInstance().getPredefinedConnectionIdentifiers().iterator(); while (idents.hasNext()) { buf.append(' '); - String ident = idents.next(); - buf.append(ident); - if (ident.equals(DBConnector.getInstance().getDefaultIdentifier())) { + String availableIdent = idents.next(); + buf.append(availableIdent); + if (availableIdent.equals(DBConnector.getInstance().getDefaultIdentifier())) { buf.append(" *"); } + if (availableIdent.equals(ident)) { + buf.append(" (connected)"); + } if (idents.hasNext()) { buf.append('\n'); } @@ -1131,7 +1168,7 @@ public Connection connect(String connectString) throws SQLException { //Shortcut - no need to try and parse everything if we already know we're empty DBConnector dbConnector = DBConnector.getInstance(); - String ident = dbConnector.getDefaultIdentifier(); + ident = dbConnector.getDefaultIdentifier(); String username = null; String password = null; if (connectString != null && connectString.trim().length() > 0) { @@ -1170,12 +1207,23 @@ /** * Command that enables the user to close a connection. */ - private static class DisConnectCommand implements Command { + private class DisConnectCommand implements Command { + @Override public CharSequence execute(SQLCommand cmd) { try { DBConnector.getInstance().disconnect(); - return "Disconnected.\n\n"; + if (ident != null) { + try { + HistoryPersister.saveHistory(AbstractSQLShellWindow.this, ident, true); + ident = null; + return "Disconnected (history saved).\n\n"; + } catch (CouldNotSaveHistoryException e) { + return "Disconnected, could not save history: " + e.getMessage() + + "\n\n"; + } + } + return "Disconnected"; } catch(SQLException e) { throw new IllegalStateException("Failed to disconnect: " + e.getMessage(), e); } @@ -1215,11 +1263,19 @@ private class HistoryCommand implements Command { @Override public CharSequence execute(SQLCommand command) { - StringBuilder returnValue = new StringBuilder(); + StringBuffer returnValue = new StringBuffer(); Iterator<SQLCommand> iCommands = commandHistory.iterator(); + returnValue.append("\n**** History Overview ****\n"); + int index = 0; while (iCommands.hasNext()) { SQLCommand cmd = iCommands.next(); - returnValue.append(cmd.getCommandString()); + String cmdString = cmd.getCommandString(); + if (cmdString.trim().length() == 0) { + continue; + } + returnValue.append(++index); + returnValue.append("> "); + returnValue.append(cmdString); returnValue.append('\n'); } return returnValue; @@ -1266,6 +1322,7 @@ @Override public CharSequence execute(SQLCommand command) { run = false; + new DisConnectCommand().execute(null); close(); return "Application terminated."; } @@ -1315,7 +1372,7 @@ if (cmdString.length() > 0) { if (cmdString.startsWith("-k")) { String keyword = cmdString.subSequence(cmdString.indexOf(" "), cmdString.length()).toString().trim(); - StringBuilder returnValue = new StringBuilder(); + StringBuffer returnValue = new StringBuffer(); Iterator<Command> iCommands = commands.getCommands().iterator(); while (iCommands.hasNext()) { Command cmd= iCommands.next(); @@ -1348,7 +1405,7 @@ } // default print all commands // TODO iterate - StringBuilder returnValue = new StringBuilder(); + StringBuffer returnValue = new StringBuffer(); returnValue.append("Available key mappings:\n"); int max = 0; List<KeyAction> keys = new ArrayList<KeyAction>(actionKeys.values()); @@ -1768,7 +1825,7 @@ fin = new FileInputStream(toFileName(command.substring(1))); output("Reading file: "+ toFileName(command.substring(1))); BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); - StringBuilder cmd = new StringBuilder(); + StringBuffer cmd = new StringBuffer(); String line; while ( ((line = reader.readLine()) != null)) { if (cancelled) { @@ -1784,7 +1841,7 @@ currentCommand = createCommand(commandString); output(commandString); output(currentCommand.execute(new InputCommand(commandString))); - cmd=new StringBuilder(); + cmd=new StringBuffer(); new Thread() { @Override public void run() { @@ -1869,13 +1926,13 @@ * will eventually execute the Connect command. */ private static class InputCommand extends SQLCommand { - private StringBuilder command; + private StringBuffer command; public InputCommand(String command) { - this.command = new StringBuilder(command); + this.command = new StringBuffer(command); } - public InputCommand(StringBuilder command) { + public InputCommand(StringBuffer command) { this.command = command; } @@ -1884,12 +1941,12 @@ return command.toString(); } @Override - public List<StringBuilder> getEditableLines() { - return Arrays.asList(new StringBuilder[]{command}); + public List<StringBuffer> getEditableLines() { + return Arrays.asList(new StringBuffer[]{command}); } @Override public List<? extends CharSequence> getLines() { - return Arrays.asList(new StringBuilder[]{command}); + return Arrays.asList(new StringBuffer[]{command}); } } @@ -1976,9 +2033,9 @@ private void joinLine() { Point cursorPosition = screen.getCursorPosition(); - StringBuilder line = getEditableCommand().getEditableLines().remove(cursorPosition.y); + StringBuffer line = getEditableCommand().getEditableLines().remove(cursorPosition.y); cursorPosition.y--; - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); + StringBuffer lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); cursorPosition.x = lineBuffer.length(); lineBuffer.append(line); } Modified: src/main/java/nl/improved/sqlclient/SQLCommand.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLCommand.java 2008-08-06 20:32:52 UTC (rev 284) +++ src/main/java/nl/improved/sqlclient/SQLCommand.java 2008-08-19 08:01:34 UTC (rev 285) @@ -6,16 +6,16 @@ public class SQLCommand { - private List<StringBuilder> commandLines; + private List<StringBuffer> commandLines; /** * Constructor. */ public SQLCommand() { - commandLines = new ArrayList<StringBuilder>(); + commandLines = new ArrayList<StringBuffer>(); } - public List<StringBuilder> getEditableLines() { + public List<StringBuffer> getEditableLines() { return commandLines; } public List<? extends CharSequence> getLines() { @@ -28,7 +28,7 @@ * @return the part of the command that is before the cursor position. */ public CharSequence getSubCommand(Point cursorPosition) { - StringBuilder commandBuffer = new StringBuilder(); + StringBuffer commandBuffer = new StringBuffer(); for (int i = 0; i <= cursorPosition.y; i++) { if (i == cursorPosition.y) { commandBuffer.append(commandLines.get(i).substring(0, cursorPosition.x)); @@ -47,7 +47,7 @@ } public String getUntrimmedCommandString() { - StringBuilder returnValue = new StringBuilder(); + StringBuffer returnValue = new StringBuffer(); Iterator<? extends CharSequence> parts = getLines().iterator(); while (parts.hasNext()) { if (returnValue.length() > 0 && returnValue.charAt(returnValue.length()-1) != '\n') { |
From: SVN by r. <sv...@ca...> - 2008-08-06 20:33:01
|
Author: roy Date: 2008-08-06 22:32:52 +0200 (Wed, 06 Aug 2008) New Revision: 284 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: fixes show 'queries in progress' that will be executed once the current query is done Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-06 14:23:23 UTC (rev 283) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-06 20:32:52 UTC (rev 284) @@ -522,7 +522,7 @@ List<SQLCommand> returnValue = new ArrayList<SQLCommand>(); Iterator<CommandInfo> i = commandQueue.iterator(); while (i.hasNext()) { - returnValue.add(i.next().cmd); + returnValue.add(i.next().sql); } return returnValue; } Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-06 14:23:23 UTC (rev 283) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-06 20:32:52 UTC (rev 284) @@ -231,14 +231,18 @@ tmpList.addAll(screenBuffer); //add prompt - SQLCommand commandLines = getCommand(); - List<? extends CharSequence> currentLines = commandLines.getLines(); - for (int i = 0; i < currentLines.size(); i++) { - if (i == 0 && screen.getShowPrompt()) { - tmpList.add(Screen.PROMPT+"> "+currentLines.get(i)); - } else { - String nrI = Integer.toString(i+1); - tmpList.add(screen.getEmptyLine().substring(0,Screen.PROMPT.length() - nrI.length()) + nrI+"> "+currentLines.get(i)); + List<SQLCommand> commands = getUnprocessedCommands(); + commands.add(getCommand()); + for (SQLCommand commandLines : commands) { + //SQLCommand commandLines = getCommand(); + List<? extends CharSequence> currentLines = commandLines.getLines(); + for (int i = 0; i < currentLines.size(); i++) { + if (i == 0 && screen.getShowPrompt()) { + tmpList.add(Screen.PROMPT+"> "+currentLines.get(i)); + } else { + String nrI = Integer.toString(i+1); + tmpList.add(screen.getEmptyLine().substring(0,Screen.PROMPT.length() - nrI.length()) + nrI+"> "+currentLines.get(i)); + } } } int startLine; @@ -268,6 +272,7 @@ color = new CharColor(CharColor.BLACK, CharColor.WHITE, CharColor.REVERSE, CharColor.REVERSE); String cursorChar = " "; Point cursorPosition = screen.getCursorPosition(); + SQLCommand commandLines = getCommand(); if (commandLines.getLines().size() > 0) { String tmp = commandLines.getLines().get(cursorPosition.y).toString(); if (cursorPosition.x < 0) { |
From: SVN by r. <sv...@ca...> - 2008-08-06 14:23:37
|
Author: roy Date: 2008-08-06 16:23:23 +0200 (Wed, 06 Aug 2008) New Revision: 283 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: small code cleanup Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-05 12:16:24 UTC (rev 282) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-06 14:23:23 UTC (rev 283) @@ -77,7 +77,7 @@ /** * The current command lines. */ - protected SQLCommand commandLines; + private SQLCommand commandLines; /** * All commands in history. */ @@ -518,6 +518,15 @@ return commandLines; } + protected List<SQLCommand> getUnprocessedCommands() { + List<SQLCommand> returnValue = new ArrayList<SQLCommand>(); + Iterator<CommandInfo> i = commandQueue.iterator(); + while (i.hasNext()) { + returnValue.add(i.next().cmd); + } + return returnValue; + } + /** * Add a new line to the command lines buffer. */ Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-05 12:16:24 UTC (rev 282) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-06 14:23:23 UTC (rev 283) @@ -39,6 +39,7 @@ import nl.improved.sqlclient.InputKey; import nl.improved.sqlclient.Point; import nl.improved.sqlclient.Screen; +import nl.improved.sqlclient.SQLCommand; /** * SQLShell window based on the jcurses library. @@ -230,6 +231,7 @@ tmpList.addAll(screenBuffer); //add prompt + SQLCommand commandLines = getCommand(); List<? extends CharSequence> currentLines = commandLines.getLines(); for (int i = 0; i < currentLines.size(); i++) { if (i == 0 && screen.getShowPrompt()) { |
From: SVN by r. <sv...@ca...> - 2008-08-05 12:16:35
|
Author: roy Date: 2008-08-05 14:16:24 +0200 (Tue, 05 Aug 2008) New Revision: 282 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/commands/Command.java src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: some code cleanup added catch execption for executing commands improve close window Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-03 20:03:00 UTC (rev 281) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-05 12:16:24 UTC (rev 282) @@ -422,7 +422,11 @@ output(cmd.sql.getLines()); repaint(); if (/*direct ||*/ !cmd.cmd.backgroundProcessSupported()) { - output(cmd.cmd.execute(cmd.sql)); + try { + output(cmd.cmd.execute(cmd.sql)); + } catch(Exception e) { + error(e); + } repaint(); } else { commandThread = new CommandThread(cmd.cmd) { @@ -617,6 +621,12 @@ Point cursorPosition = screen.getCursorPosition(); List<StringBuilder> editableLines = getEditableCommand().getEditableLines(); StringBuilder currentLine = editableLines.get(cursorPosition.y); + if (cursorPosition.x > currentLine.length()) { + for (int i = currentLine.length(); i < cursorPosition.x; i++) { + currentLine.append(' '); + } + debug("WARNING: Fixing: cursorposition: "+ cursorPosition.x +" /" + currentLine.length()); + } currentLine.insert(cursorPosition.x, newText); cursorPosition.x += newText.length(); // check if the new line is becoming too long @@ -652,6 +662,7 @@ currentLine.delete(lastSpace, currentLine.length()); if (lastChar == ' ') { nextLine.deleteCharAt(0); + cursorPosition.x--; } // check if the cursor postition > the new line length // calculate new x and go to nextline Modified: src/main/java/nl/improved/sqlclient/commands/Command.java =================================================================== --- src/main/java/nl/improved/sqlclient/commands/Command.java 2008-08-03 20:03:00 UTC (rev 281) +++ src/main/java/nl/improved/sqlclient/commands/Command.java 2008-08-05 12:16:24 UTC (rev 282) @@ -15,10 +15,8 @@ */ package nl.improved.sqlclient.commands; -import java.util.List; import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.Point; -import nl.improved.sqlclient.SQLUtil; import nl.improved.sqlclient.TabCompletionInfo; /** * Implement this interface to add a specific command to the sql client. Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-03 20:03:00 UTC (rev 281) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-05 12:16:24 UTC (rev 282) @@ -19,6 +19,8 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import jcurses.event.ActionEvent; import jcurses.event.ActionListener; import jcurses.system.CharColor; @@ -47,7 +49,10 @@ private Window window; private boolean dontRepaint = false; private boolean repaint = true; + private String debugString; + private Object lockObject = new Object(); + /** * Default constructor. */ @@ -78,10 +83,8 @@ */ @Override public void debug(String debug) { - synchronized(this) { - CharColor color = new CharColor(CharColor.BLUE, CharColor.YELLOW); - Toolkit.printString(debug, 1, getScreenHeight()-1, color); - } + debugString = debug; + repaint = true; } @@ -148,16 +151,24 @@ if (!dontRepaint && repaint) { try { synchronized(this) { - paint(screen); + _paint(screen); } } catch(Throwable t) { error(t); } } try { - Thread.sleep(200); - } catch(Exception e) {} + synchronized(lockObject) { + lockObject.wait(1000); + } + } catch (InterruptedException ex) { + /* ignore */ + } } + super.close(); + //window.close(); + window.hide(); + window.close(); } /** @@ -165,8 +176,10 @@ */ @Override public void close() { - super.close(); + /* + super.close(); window.close(); + */ } @@ -197,7 +210,19 @@ */ @Override public void paint(Screen screen) { - synchronized(this) { + if (isRunning()) { + repaint = true; + synchronized(lockObject) { + lockObject.notify(); + } + } + } + + private void _paint(Screen screen) { + if (!isRunning()) { + return; + } + synchronized(lockObject) { CharColor color = new CharColor(CharColor.BLACK, CharColor.WHITE, CharColor.BOLD, CharColor.BOLD); List<CharSequence> tmpList = new ArrayList<CharSequence>(); @@ -252,6 +277,11 @@ } } Toolkit.printString(cursorChar, Screen.PROMPT.length() +"> ".length() + cursorPosition.x, lineNr-(commandLines.getLines().size() -cursorPosition.y)-startLine, color); + if (debugString != null) { + color = new CharColor(CharColor.BLUE, CharColor.YELLOW); + Toolkit.printString(debugString, 1, getScreenHeight()-1, color); + } + repaint = false; } } @@ -277,6 +307,9 @@ protected void repaint() { if (isRunning()) { repaint = true; + synchronized(lockObject) { + lockObject.notify(); + } } } |
From: SVN by r. <sv...@ca...> - 2008-08-03 20:03:09
|
Author: roy Date: 2008-08-03 22:03:00 +0200 (Sun, 03 Aug 2008) New Revision: 281 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/DBConnector.java src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: made connector not dependant on jcurses.. added initial implementation for dump binary data Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-03 20:01:43 UTC (rev 280) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-03 20:03:00 UTC (rev 281) @@ -53,6 +53,7 @@ import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; +import nl.improved.sqlclient.DBConnector.ConnectionSettings; import nl.improved.sqlclient.commands.*; import nl.improved.sqlclient.util.LimitedArrayList; import org.w3c.dom.Document; @@ -61,6 +62,7 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; +import sun.misc.BASE64Encoder; /** * The SQLShell abstract main class. @@ -481,6 +483,8 @@ * @param p the character x/y location to show the popupscreen on */ public abstract String select(List<String> items, Point p); + + protected abstract String[] getLoginCredentials(String username, String password) throws SQLException; /** * Returns the connection to the database * @return the connection to the database @@ -978,7 +982,7 @@ /** * Connect command for setting up a connection to a database. */ - private static class ConnectCommand implements Command { + private class ConnectCommand implements Command { /** * Execute the connection command and return a readable result. * @param command the command string for setting up a connection @@ -992,8 +996,11 @@ if (cmdString.length() > 0 && cmdString.charAt(cmdString.length()-1) == ';') { cmdString = cmdString.substring(0, cmdString.length()-1); } - DBConnector.getInstance().connect(cmdString); - return "Connected.\n\n"; + if (connect(cmdString) != null) { + return "Connected.\n\n"; + } else { + return "Connect failed. Unknown reason\n\n"; + } } catch(SQLException e) { throw new IllegalStateException("Failed to connect: " + e.getMessage(), e); } @@ -1057,6 +1064,88 @@ public boolean backgroundProcessSupported() { return false; } + + /** + * Connects to a database, using a connection string. + * + * Possible cases: + * <table> + * <tr> + * <td>"user/pass@ident"</td> + * <td>Connects to ident as user with password pass</td> + * </tr> + * <tr> + * <td>"user/@ident"</td> + * <td>Connects to ident connection as user with empty password</td> + * </tr> + * <tr> + * <td>"user@ident"</td> + * <td>Connects to ident connection as user, without specifying a password (will be prompted for pass)</td> + * </tr> + * <tr> + * <td>"@ident"</td> + * <td>Connects to ident connection, without specifying user or password. If default user is specified that will be used, if not: will be prompted for user/pass</td> + * </tr> + * <tr> + * <td>"user/pass"</td> + * <td>Connects to default connection as user, with password pass</td> + * </tr> + * <tr> + * <td>"user/"</td> + * <td>Connects to default connection as user, with empty password</td> + * </tr> + * <tr> + * <td>"user"</td> + * <td>Connects to default connection as user, without specifying a password (will be prompted for pass)</td> + * </tr> + * <tr> + * <td>""</td> + * <td>Connects to default connection, without specifying user or password. If default user is specified that will be used, if not: will be prompted for user/pass</td> + * </tr> + * <table> + * + * @param connectString the connect string, following the conditions as specified above. + * @return the opened Connection + * @throws SQLException if the connection could not be opened. + */ + public Connection connect(String connectString) throws SQLException { + //Shortcut - no need to try and parse everything if we already know we're empty + DBConnector dbConnector = DBConnector.getInstance(); + String ident = dbConnector.getDefaultIdentifier(); + String username = null; + String password = null; + if (connectString != null && connectString.trim().length() > 0) { + + String[] connectParts = connectString.split("@"); + if (connectParts.length > 1) { + ident = connectParts[1].trim(); + } + + if (connectParts[0].matches(".+/.*")) { + String[] loginDetails = connectParts[0].split("/"); + if (loginDetails.length > 1) { + password = loginDetails[1]; + } else { + password = ""; + } + username = loginDetails[0].trim(); + } else { + username = connectParts[0].trim(); + } + } + if (username == null || password == null) { + ConnectionSettings predefinedSettings = dbConnector.getPredefinedConnectionSettings(ident); + if (predefinedSettings != null) { + username = predefinedSettings.getUsername(); + password = predefinedSettings.getPassword(); + } + String[] credentials = getLoginCredentials(username, password); + username = credentials[0]; + password = credentials[1]; + } + + return dbConnector.connect(ident, username, password); + } } /** * Command that enables the user to close a connection. @@ -1415,7 +1504,7 @@ TransformerHandler hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); - serializer.setOutputProperty(OutputKeys.INDENT,"yes"); + //serializer.setOutputProperty(OutputKeys.INDENT,"no"); hd.setResult(streamResult); hd.startDocument(); AttributesImpl atts = new AttributesImpl(); @@ -1445,12 +1534,34 @@ } else if (metaData.getColumnType(col) == Types.BINARY || metaData.getColumnType(col) == Types.BLOB || metaData.getColumnType(col) == Types.CLOB || - metaData.getColumnType(col) == Types.LONGNVARCHAR) { - InputStream valueStream = rs.getBinaryStream(col); - //Base64 + metaData.getColumnType(col) == Types.LONGNVARCHAR || + metaData.getColumnType(col) == Types.LONGVARBINARY || + metaData.getColumnType(col) == Types.LONGVARCHAR || + metaData.getColumnType(col) == Types.NCLOB || + metaData.getColumnType(col) == Types.OTHER) { atts.addAttribute("","","type","","binary"); hd.startElement("","","col",atts); + + BASE64Encoder enc = new BASE64Encoder(); + int bytesSize = 128; + byte[] bytes = new byte[bytesSize]; + int read; + InputStream valueStream = rs.getBinaryStream(col); + while ( (read = valueStream.read(bytes)) != -1) { + if (read == 0) { + continue; + } + if (read != bytes.length) { + bytes = Arrays.copyOf(bytes, read); + } + String stringValue = enc.encode(bytes) +"\n"; + hd.characters(stringValue.toCharArray(), 0, stringValue.length()); + if (bytes.length != bytesSize) { + bytes = new byte[bytesSize]; + } + } } else { + atts.addAttribute("","","type","",metaData.getColumnTypeName(col)); hd.startElement("","","col",atts); String value= rs.getString(col); if (value != null) { Modified: src/main/java/nl/improved/sqlclient/DBConnector.java =================================================================== --- src/main/java/nl/improved/sqlclient/DBConnector.java 2008-08-03 20:01:43 UTC (rev 280) +++ src/main/java/nl/improved/sqlclient/DBConnector.java 2008-08-03 20:03:00 UTC (rev 281) @@ -27,20 +27,9 @@ import java.util.Set; import java.util.Map; import java.util.Properties; -import jcurses.system.InputChar; -import jcurses.event.ActionEvent; -import jcurses.event.ActionListener; -import jcurses.widgets.Button; -import jcurses.widgets.Dialog; -import jcurses.widgets.GridLayoutManager; -import jcurses.widgets.Label; -import jcurses.widgets.PasswordField; -import jcurses.widgets.TextField; -import jcurses.widgets.WidgetsConstants; public final class DBConnector { - /** * The default formatting pattern for Date or Date-like columns. */ @@ -119,79 +108,7 @@ return null; } - /** - * Connects to a database, using a connection string. - * - * Possible cases: - * <table> - * <tr> - * <td>"user/pass@ident"</td> - * <td>Connects to ident as user with password pass</td> - * </tr> - * <tr> - * <td>"user/@ident"</td> - * <td>Connects to ident connection as user with empty password</td> - * </tr> - * <tr> - * <td>"user@ident"</td> - * <td>Connects to ident connection as user, without specifying a password (will be prompted for pass)</td> - * </tr> - * <tr> - * <td>"@ident"</td> - * <td>Connects to ident connection, without specifying user or password. If default user is specified that will be used, if not: will be prompted for user/pass</td> - * </tr> - * <tr> - * <td>"user/pass"</td> - * <td>Connects to default connection as user, with password pass</td> - * </tr> - * <tr> - * <td>"user/"</td> - * <td>Connects to default connection as user, with empty password</td> - * </tr> - * <tr> - * <td>"user"</td> - * <td>Connects to default connection as user, without specifying a password (will be prompted for pass)</td> - * </tr> - * <tr> - * <td>""</td> - * <td>Connects to default connection, without specifying user or password. If default user is specified that will be used, if not: will be prompted for user/pass</td> - * </tr> - * <table> - * - * @param connectString the connect string, following the conditions as specified above. - * @return the opened Connection - * @throws SQLException if the connection could not be opened. - */ - public Connection connect(String connectString) throws SQLException { - //Shortcut - no need to try and parse everything if we already know we're empty - if (connectString == null || connectString.trim().length() == 0) { - return connect(defaultConnector, null, null); - } - String ident = defaultConnector; - String username = null; - String password = null; - - String[] connectParts = connectString.split("@"); - if (connectParts.length > 1) { - ident = connectParts[1].trim(); - } - - if (connectParts[0].matches(".+/.*")) { - String[] loginDetails = connectParts[0].split("/"); - if (loginDetails.length > 1) { - password = loginDetails[1]; - } else { - password = ""; - } - username = loginDetails[0].trim(); - } else { - username = connectParts[0].trim(); - } - - return connect(getPredefinedConnectionSettings(ident), username, password); - } - public QueryExecutor getQueryExecutor() { if (queryExecutor == null) { if (dateIsTimeStamp) { @@ -203,7 +120,7 @@ return queryExecutor; } - private ConnectionSettings getPredefinedConnectionSettings(String identifier) { + public ConnectionSettings getPredefinedConnectionSettings(String identifier) { if (predefinedConnections.containsKey(identifier)) { return predefinedConnections.get(identifier); } @@ -271,16 +188,6 @@ } } - if (username == null || password == null) { - LoginDialog ld = new LoginDialog(username, password); - ld.show(); - if (!ld.exitOk) { - throw new SQLException("Connect cancelled."); - } - username = ld.getUsername(); - password = ld.getPassword(); - } - activeConnection = DriverManager.getConnection(settings.getConnectionURL(), username, password); activeConnection.setAutoCommit(autoCommit); // INITIALIZE database settings @@ -342,7 +249,7 @@ return statement; } - private static class ConnectionSettings { + public static class ConnectionSettings { private String identifier; private String connectionURL; private String driver; @@ -386,100 +293,4 @@ return password; } } - - private static class LoginDialog extends Dialog { - private boolean exitOk = false; - private TextField userfield; - private PasswordField passfield; - - public LoginDialog(final String username, final String password) { - super(10,10, 50, 7, true,"Connect"); - userfield = new TextField(); - setUsername(username); - passfield = new PasswordField() { - - @Override - protected void focus() { - super.focus(); - } - - protected boolean handleInput(InputChar ch) { - if (!ch.isSpecialCode() && ch.getCharacter() == '\n') { - okButtonPressedSlot(); - return false; - } - return super.handleInput(ch); - } - }; - setPassword(password); - - Button okButton = new Button("Ok"); - okButton.addListener(new ActionListener() { - public void actionPerformed(ActionEvent event) { - okButtonPressedSlot(); - } - }); - Button cancelButton = new Button("Cancel"); - cancelButton.addListener(new ActionListener() { - public void actionPerformed(ActionEvent arg0) { - LoginDialog.this.exitOk = false; - LoginDialog.this.close(); - } - }); - - GridLayoutManager glm = new GridLayoutManager(4,3); - getRootPanel().setLayoutManager(glm); - - glm.addWidget(new Label("Username"), 0,0,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); - glm.addWidget(userfield, 1,0,3,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); - glm.addWidget(new Label("Password"), 0,1,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); - glm.addWidget(passfield, 1,1,3,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); - - glm.addWidget(okButton, 1,2,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_CENTER); - glm.addWidget(cancelButton, 2,2,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_CENTER); - - } - public void okButtonPressedSlot() { - exitOk = true; - close(); - } - - @Override - protected void activate() { - super.activate(); - - if (userfield.getText().length() == 0) { - userfield.getFocus(); - } else if (passfield.getText().length() == 0) { - passfield.getFocus(); - } else { - throw new IllegalStateException("We have login data, but get a login dailog anyway."); - } - } - - public void setUsername(String username) { - if (username == null) { - userfield.setText(""); - } else { - userfield.setText(username); - } - } - - public String getUsername() { - return userfield.getText(); - } - - public void setPassword(String password) { - if (password == null) { - passfield.setText(""); - } else { - passfield.setText(password); - } - } - - public String getPassword() { - return passfield.getText(); - } - } - } Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-03 20:01:43 UTC (rev 280) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-03 20:03:00 UTC (rev 281) @@ -15,13 +15,23 @@ */ package nl.improved.sqlclient.jcurses; +import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import jcurses.event.ActionEvent; +import jcurses.event.ActionListener; import jcurses.system.CharColor; import jcurses.system.InputChar; import jcurses.system.Toolkit; +import jcurses.widgets.Button; +import jcurses.widgets.Dialog; +import jcurses.widgets.GridLayoutManager; +import jcurses.widgets.Label; +import jcurses.widgets.PasswordField; import jcurses.widgets.PopUpMenu; +import jcurses.widgets.TextField; +import jcurses.widgets.WidgetsConstants; import jcurses.widgets.Window; import nl.improved.sqlclient.AbstractSQLShellWindow; import nl.improved.sqlclient.InputKey; @@ -245,6 +255,21 @@ } } + @Override + protected String[] getLoginCredentials(String username, String password) throws SQLException { + LoginDialog diag = new LoginDialog(username, password); + dontRepaint = true; + try { + diag.show(); + if (!diag.exitOk) { + throw new SQLException("Connect cancelled."); + } + return new String[] {diag.getUsername(), diag.getPassword() }; + } finally { + dontRepaint = false; + } + } + /** * Override to allow painting on the main thread to overcome painting errors. */ @@ -263,6 +288,104 @@ Toolkit.beep(); } + private static class LoginDialog extends Dialog { + private boolean exitOk = false; + private TextField userfield; + private PasswordField passfield; + + public LoginDialog(final String username, final String password) { + super(10,10, 50, 7, true,"Connect"); + userfield = new TextField(); + setUsername(username); + passfield = new PasswordField() { + + @Override + protected void focus() { + super.focus(); + } + + @Override + protected boolean handleInput(InputChar ch) { + if (!ch.isSpecialCode() && ch.getCharacter() == '\n') { + okButtonPressedSlot(); + return false; + } + return super.handleInput(ch); + } + }; + setPassword(password); + + Button okButton = new Button("Ok"); + okButton.addListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + okButtonPressedSlot(); + } + }); + Button cancelButton = new Button("Cancel"); + cancelButton.addListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + LoginDialog.this.exitOk = false; + LoginDialog.this.close(); + } + }); + + GridLayoutManager glm = new GridLayoutManager(4,3); + getRootPanel().setLayoutManager(glm); + + glm.addWidget(new Label("Username"), 0,0,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); + glm.addWidget(userfield, 1,0,3,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); + glm.addWidget(new Label("Password"), 0,1,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); + glm.addWidget(passfield, 1,1,3,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_LEFT); + + glm.addWidget(okButton, 1,2,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_CENTER); + glm.addWidget(cancelButton, 2,2,1,1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_CENTER); + + } + public void okButtonPressedSlot() { + exitOk = true; + close(); + } + + @Override + protected void activate() { + super.activate(); + + if (userfield.getText().length() == 0) { + userfield.getFocus(); + } else if (passfield.getText().length() == 0) { + passfield.getFocus(); + } else { + throw new IllegalStateException("We have login data, but get a login dailog anyway."); + } + } + + public void setUsername(String username) { + if (username == null) { + userfield.setText(""); + } else { + userfield.setText(username); + } + } + + public String getUsername() { + return userfield.getText(); + } + + public void setPassword(String password) { + if (password == null) { + passfield.setText(""); + } else { + passfield.setText(password); + } + } + + public String getPassword() { + return passfield.getText(); + } + } + public static void main(String[] args) { SQLShellWindow shell = new SQLShellWindow(); shell.show(); |
From: SVN by r. <sv...@ca...> - 2008-08-03 20:01:52
|
Author: roy Date: 2008-08-03 22:01:43 +0200 (Sun, 03 Aug 2008) New Revision: 280 Modified: src/main/java/nl/improved/sqlclient/SQLShell.java Log: made deprecated Modified: src/main/java/nl/improved/sqlclient/SQLShell.java =================================================================== --- src/main/java/nl/improved/sqlclient/SQLShell.java 2008-08-03 12:15:17 UTC (rev 279) +++ src/main/java/nl/improved/sqlclient/SQLShell.java 2008-08-03 20:01:43 UTC (rev 280) @@ -15,1617 +15,18 @@ */ package nl.improved.sqlclient; -import java.io.*; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.LinkedHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import jcurses.widgets.Window; -import jcurses.system.InputChar; -import jcurses.system.Toolkit; -import jcurses.system.CharColor; -import jcurses.widgets.PopUpMenu; -import nl.improved.sqlclient.commands.*; +import nl.improved.sqlclient.jcurses.SQLShellWindow; + /** * The SQLShell main class. * This class provides a (textbased) window for entering sql commands. */ -public class SQLShell extends Window { +public class SQLShell { - /** - * The current command thread executing a SQLShell command. - */ - private CommandThread commandThread; - /** - * True when the prompt should be visible. - * Normally it is not visible during the execution of a command - */ - private boolean showPrompt = true; - - /** - * The (default) maximum matches to show in a selection dialog. - */ - private static final int MAX_MATCH_SIZE = 15; - private int MAX_LINE_LENGTH; // not static and final.. since it can change on window resize - - /** - * Page up count 0 means were at the bottom of our screen. - * Increasement of the pageup count moves the visible part of the screen up. - */ - private int pageUpCount = 0; - /** - * All lines in a screen. - */ - private List<CharSequence> screenBuffer = new LimitedArrayList<CharSequence>(1000); - /** - * The current command lines. - */ - private SQLCommand commandLines; - /** - * All commands in history. - */ - private List<SQLCommand> commandHistory = new LimitedArrayList<SQLCommand>(50); - /** - * Index for browsing commands. - */ - private int commandIndex = 0; - /** - * An empty line for easy line completion (fill with spaces). - */ - private String emptyLine; - /** - * The cursor position in the command lines list. - * 0,0 means it is at the first line at the first character - * 10,5 means it is at the 11th character at the 6th line - */ - private Point cursorPosition = new Point(0,0); - /** - * The prompt to show when entering sql commands. - */ - private static final String PROMPT = "SQL"; - /** - * Some debug info holding the last trace of an exception. - */ - private String lastExceptionDetails; - - /** - * The output file when spool is on. - */ - private Writer spoolWriter; - /** - * A manager for available commands. - */ - private CommandManager commands = new CommandManager(); - - /** - * A map of string key representation to a action that should be executed when a specific key is pressed. - */ - private Map<String, KeyAction> actionKeys = new LinkedHashMap<String, KeyAction>(); - - /** - * Constructor. - */ - public SQLShell() { - super(Toolkit.getScreenWidth(),Toolkit.getScreenHeight(), true, "SQLShell"); - char[] emptyLineChar = new char[Toolkit.getScreenWidth()]; - Arrays.fill(emptyLineChar, ' '); - emptyLine = new String(emptyLineChar); - - // initialize the command shell - commandLines = new SQLCommand(); - commandHistory.add(commandLines); - newLine(); - - // Register all known commands - commands.register("CONNECT[\\s]*.*", new ConnectCommand()); - commands.register("DISCONNECT[\\s]*", new DisConnectCommand()); - commands.register("SHOW[\\s]+[A-Z]+(|[A-Z]|_|\\.)*(|[\\s]+HAVING[\\s][A-Z]*.*)", new ShowCommand()); - commands.register("DESC[\\s]+[A-Z]+(|[0-9]|[A-Z]|_|-|\\.)*", new DescCommand()); - commands.register("WINDOW[\\s]+[A-Z]+", new WindowCommand()); - commands.register("INFO[\\s]*", new InfoCommand()); - commands.register("HELP[\\s]*.*", new HelpCommand()); - commands.register("HISTORY[\\s]*.*", new HistoryCommand()); - commands.register("SPOOL[\\s]*.*", new SpoolCommand()); - commands.register("QUIT[\\s]*", new QuitCommand("quit")); - commands.register("EXIT[\\s]*", new QuitCommand("exit")); - //commands.register("\\\\Q[\\s]*", new QuitCommand("\\q")); - commands.register("@.*", new ExecuteBatchCommand()); - commands.register("(SELECT|UPDATE|ALTER|INSERT|DELETE).*;[\\s]*", new QueryCommand()); - - // keys - actionKeys.put(Integer.toString(InputChar.KEY_LEFT), new KeyAction() { - public void execute() { - if (cursorPosition.x > 0) { - cursorPosition.x--; - } else if (cursorPosition.y > 0) { - cursorPosition.y--; - cursorPosition.x = commandLines.getLines().get(cursorPosition.y).length(); - } - } - public CharSequence getHelp() { - return "Arrow Left:\tMove cursor to the left"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_RIGHT), new KeyAction() { - public void execute() { - CharSequence tmp = commandLines.getLines().get(cursorPosition.y); - if (cursorPosition.x < tmp.length()) { - cursorPosition.x++; - } else if (cursorPosition.y < commandLines.getLines().size()-1) { - cursorPosition.x = 0; - cursorPosition.y++; - } - } - public CharSequence getHelp() { - return "Arrow Right:\tMove cursor to the right"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_UP), new KeyAction() { - public void execute() { - if (commandIndex > 0) { - commandLines = commandHistory.get(--commandIndex); - cursorPosition.y = commandLines.getLines().size()-1; - CharSequence lineBuffer = commandLines.getLines().get(cursorPosition.y); - cursorPosition.x = lineBuffer.length(); - } - } - public CharSequence getHelp() { - return "Arrow Up:\tBrowse to previous command in the history"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_DOWN), new KeyAction() { - public void execute() { - if (commandIndex < commandHistory.size()-1) { - commandLines = commandHistory.get(++commandIndex); - cursorPosition.y = commandLines.getLines().size()-1; - CharSequence lineBuffer = commandLines.getLines().get(cursorPosition.y); - cursorPosition.x = lineBuffer.length(); - } - } - public CharSequence getHelp() { - return "Arrow Down:\tBrowse to next command in the history"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_END),new KeyAction() { - public void execute() { - int curLineEnd = commandLines.getLines().get(cursorPosition.y).length(); - if (cursorPosition.x == curLineEnd) { - cursorPosition.y = commandLines.getLines().size()-1; - CharSequence lineBuffer = commandLines.getLines().get(cursorPosition.y); - cursorPosition.x = lineBuffer.length(); - } else { - cursorPosition.x = curLineEnd; - } - } - public CharSequence getHelp() { - return "End:\tMove the cursor to the end of the line, of if already there to the end of the command"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_HOME), new KeyAction() { - public void execute() { - if (cursorPosition.x == 0) { - cursorPosition.y = 0; - } - cursorPosition.x = 0; - } - public CharSequence getHelp() { - return "Home:\tMove the cursor to the start of the line, of if already there to the start of the command"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_BACKSPACE), new KeyAction() { - public void execute() { - if (cursorPosition.x == 0) { - if (cursorPosition.y > 0) { - joinLine(); - } - } else { - StringBuilder tmp = getEditableCommand().getEditableLines().get(cursorPosition.y); - if (cursorPosition.x > 0) { - tmp.deleteCharAt(cursorPosition.x-1); - cursorPosition.x--; - } - } - } - public CharSequence getHelp() { - return "Backspace:\tRemove the character before the cursor position"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_DC), new KeyAction() { - public void execute() { - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); - if (cursorPosition.x < lineBuffer.length()) { - StringBuilder tmp = getEditableCommand().getEditableLines().get(cursorPosition.y); - tmp.deleteCharAt(cursorPosition.x); - } - } - public CharSequence getHelp() { - return "Del:\tDelete the charactor at the current cursor position"; - } - }); - actionKeys.put("", new KeyAction() { - public void execute() { // ctrl+w - if (cursorPosition.x == 0) { - if (cursorPosition.y > 0) { - joinLine(); - } - return; - } - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); - int previousBreak = SQLUtil.getLastBreakIndex(lineBuffer.substring(0, cursorPosition.x-1)); - if (lineBuffer.charAt(previousBreak) == ' ' || lineBuffer.charAt(previousBreak) == '\t') { - previousBreak++; - } - lineBuffer.delete(previousBreak, cursorPosition.x); - cursorPosition.x = previousBreak; - } - public CharSequence getHelp() { - return "Control-W:\tRemove word before cursor position"; - } - }); - actionKeys.put("", new KeyAction() { // ctrl+u - public void execute() { - if (cursorPosition.x > 0) { - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); - lineBuffer.delete(0, cursorPosition.x); - cursorPosition.x = 0; - } else if (cursorPosition.y > 0) { - StringBuilder lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); - if (lineBuffer.length() == 0) { - commandLines.getEditableLines().remove(cursorPosition.y); - } - cursorPosition.y--; - lineBuffer = commandLines.getEditableLines().get(cursorPosition.y); - lineBuffer.delete(0, lineBuffer.length()); - } - } - public CharSequence getHelp() { - return "Control-U:\tRemove all characters before the cursor position"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_PPAGE), new KeyAction() { - public void execute() { - if ((screenBuffer.size() + commandLines.getLines().size() - - (Toolkit.getScreenHeight()/2) * pageUpCount) > 0) { - pageUpCount++; - - } - } - public CharSequence getHelp() { - return "PageUp:\tMove back in screen history"; - } - }); - actionKeys.put(Integer.toString(InputChar.KEY_NPAGE), new KeyAction() { - public void execute() { - if (pageUpCount > 0) { - pageUpCount--; - } - } - public CharSequence getHelp() { - return "PageDown:\tMove forward in screen history"; - } - }); - actionKeys.put("", new KeyAction() { // ctrl+a - public void execute() { - output("Abort requested"); - if (commandThread.isAlive() && commandThread.getCommand().abort()) { - output("Abort done.."); - } - } - public CharSequence getHelp() { - return "Control-A:\tAbort current command (if it is supported by that command)"; - } - }); - actionKeys.put("", new KeyAction() { //Ctrl+D - public void execute() { - if (commandLines.getCommandString().length() == 0) { //Quit on empty commandline, ignore otherwise - executeCommand(new InputCommand("quit")); - } - } - public CharSequence getHelp() { - return "Control-D:\tExit sqlshell"; - } - }); - - MAX_LINE_LENGTH = Toolkit.getScreenWidth()-(PROMPT.length()+2+1); // prompt + "> " - - output("Welcome to the SQLShell client."); - output("Type 'help' to get a list of available commands other then the default sql input."); + public static void main(String[] args) throws InterruptedException { + System.out.println("This class is no longer used. Please start nl.improved.sqlclient.jcurses.SQLShellWindow"); + Thread.sleep(2000); + SQLShellWindow.main(args); } - - - /** - * Returns the connection to the database - * @return the connection to the database - */ - public Connection getConnection() { - return DBConnector.getInstance().getConnection(); - } - /** - * Shows this window. - * Override to make sure paint content is called. - */ - @Override - public void show() { - super.show(); - paint(); - } - - /** - * Hides this window. - * Override to make sure the spool writer is closed when it was open - */ - @Override - public void hide() { - try { - if (spoolWriter != null) { - try { - spoolWriter.close(); - spoolWriter = null; - } catch(Exception e) {/*ignore*/} - } - } finally { - super.hide(); - } - } - - /** - * Returns a string representation of the current command. - * @return a string representation of the current command. - */ - private SQLCommand getCommand() { - return commandLines; - } - - /** - * Add a new line to the command lines buffer. - */ - private StringBuilder newLine() { - cursorPosition.x = 0; - StringBuilder newLine = new StringBuilder(); - getEditableCommand().getEditableLines().add(newLine); - cursorPosition.y = commandLines.getLines().size()-1; - return newLine; - } - - /** - * Handle key input. - * @param inp the character that is being pressed by the user. - */ - protected void handleInput(InputChar inp) { - //debug("Input: " + inp.getCode()); - try { - if (inp.getCode() != InputChar.KEY_PPAGE && inp.getCode() != InputChar.KEY_NPAGE) { - pageUpCount = 0; // some character entered, so reset pageup count - } - if (inp.isSpecialCode()) { - KeyAction ke = actionKeys.get(Integer.toString(inp.getCode()));// || inp.toString().equals("") || inp.toString().equals("")) { - if (ke != null) { - ke.execute(); - } else { - debug("Unknown character: "+ inp.getCode()); - } - } else { - KeyAction ke = actionKeys.get(inp.toString()); - if (ke != null) { - ke.execute(); - } else { - if (inp.getCharacter() == '\n') { // newline... see if the command can be executed - // execute the command - SQLCommand sqlCommand = getCommand(); - String command = sqlCommand.getCommandString(); - // search command... - if (command.length() > 0 && command.charAt(0) == '/') { // search in history - String matchPattern=".*"+command.substring(1,command.length())+".*"; - for (int cIndex = commandHistory.size()-1; cIndex >=0; cIndex--) { - if (cIndex == commandIndex) { - continue; // skip current command - } - SQLCommand newSqlCommand = commandHistory.get(cIndex); - String commandString = newSqlCommand.getCommandString(); - if (commandString.matches(matchPattern)) { - commandHistory.remove(commandIndex); - commandIndex = commandHistory.indexOf(newSqlCommand); - commandLines = newSqlCommand; - cursorPosition.y = 0; - cursorPosition.x = 0; - paint(); // force repaint - return; - } - } - Toolkit.beep(); // TODO clear search?? - return; - } else if (executeCommand(sqlCommand)) { - // clear command history - if (commandIndex != commandHistory.size()-1) { - SQLCommand tmpLines = commandLines; - commandLines = commandHistory.get(commandHistory.size()-1); - if (commandLines.getCommandString().equals("")) { - commandHistory.add(commandHistory.size()-1, tmpLines); - } else { - commandHistory.add(tmpLines); - commandLines = tmpLines; - } - } - if (!commandLines.getCommandString().equals("")) { - commandLines = new SQLCommand(); - commandHistory.add(commandLines); - newLine(); - } - commandIndex = commandHistory.size()-1; - cursorPosition.y = commandLines.getLines().size()-1; - cursorPosition.x = commandLines.getLines().get(cursorPosition.y).length(); - paint(); // force repaint - return; - } - } - CharSequence newText; - if (inp.getCharacter() == '\t') { - try { - newText = getTabCompletion(commandLines, cursorPosition); - } catch(IllegalStateException e) { - output(getCommand().getCommandString()); // add command as well... - error(e); - return; - } - } else { - newText = Character.toString(inp.getCharacter()); - } - if (newText.equals("\n")) { - newLine(); // TODO Fix return in middle of an other line - } else { - List<StringBuilder> editableLines = getEditableCommand().getEditableLines(); - StringBuilder currentLine = editableLines.get(cursorPosition.y); - currentLine.insert(cursorPosition.x, newText); - cursorPosition.x += newText.length(); - // check if the new line is becoming too long - if (currentLine.length() > MAX_LINE_LENGTH) { - // TODO search for lastspace that is not between '' ?? - int lastSpace = SQLUtil.getLastBreakIndex(currentLine.toString());//currentLine.lastIndexOf(" "); - if (lastSpace == -1) { - lastSpace = currentLine.length(); - } - // check if there are enough 'next' lines - // if not.. add one - if (editableLines.size()-1 == cursorPosition.y) { - StringBuilder newLine = new StringBuilder(); - editableLines.add(newLine); - } - // check if the nextline has enough room for the new word - // if not.. add a new line - if (editableLines.get(cursorPosition.y+1).length() - + (currentLine.length()-lastSpace+1) > MAX_LINE_LENGTH) { - StringBuilder newLine = new StringBuilder(); - editableLines.add(cursorPosition.y+1, newLine); - } - // fetch the next line - StringBuilder nextLine = editableLines.get(cursorPosition.y+1); - // if the nextline already has some text.. add a space in front of it - if (nextLine.length() > 0) { - nextLine.insert(0, ' '); - } - // insert the new text at the beginning - nextLine.insert(0, currentLine.subSequence(lastSpace+1, currentLine.length())); - currentLine.delete(lastSpace, currentLine.length()); - // check if the cursor postition > the new line length - // calculate new x and go to nextline - if (cursorPosition.x >= lastSpace) { - cursorPosition.x = cursorPosition.x - (lastSpace+1); - cursorPosition.y++; - } - } - } - } - } - } catch(Throwable t) { - error(t); - } - paint(); - } - - /** - * Return the editable version of the commandlines. - * If editing a previous command clone it and return the clone - * @return the editable version of the commandlines. - */ - protected SQLCommand getEditableCommand() { - if (commandHistory.indexOf(commandLines) != commandHistory.size()-1) { - List<? extends CharSequence> tmp = commandLines.getLines(); - if (commandHistory.get(commandHistory.size()-1).getLines().size() == 1 - && commandHistory.get(commandHistory.size()-1).getLines().get(0).length() == 0) { - commandLines = commandHistory.get(commandHistory.size()-1); - commandLines.getEditableLines().remove(0); - } else { - commandLines = new SQLCommand(); - commandHistory.add(commandLines); - } - for (int i = 0; i < tmp.size(); i++) { - commandLines.getEditableLines().add(new StringBuilder(tmp.get(i))); - } - commandIndex = commandHistory.size()-1; - } - return commandLines; - } - - /** - * Output data to the screen. - * @param data the data to print to the screen. - */ - protected synchronized void output(CharSequence data) { - screenBuffer.addAll(getLines(data)); - if (spoolWriter != null) { - try { - spoolWriter.write(data.toString()); - spoolWriter.write("\n"); - } catch(IOException e) { - screenBuffer.add("WARNING: Could not write to spool file"); - error(e); - } - } - } - - /** - * Output error exception to the screen. - * @param e the error to print to the screen - */ - protected synchronized void error(Throwable e) { - output(e.getMessage() == null ? e.toString() : e.getMessage()); - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - sw.flush(); - lastExceptionDetails = sw.toString(); - //output(sw.toString()); - } - - /** - * Return a list of table names available for the current connection. - * @return a list of table names available for the current connection. - */ - protected List<String> getTableNames() { - List<String> returnValue = new ArrayList<String>(); - try { - ResultSet rs = getConnection().getMetaData().getTables(getConnection().getCatalog(), DBConnector.getInstance().getSchema(), null, new String[]{"TABLE"}); - while (rs.next()) { - if (!returnValue.contains(rs.getString("TABLE_NAME"))) { - returnValue.add(rs.getString("TABLE_NAME")); - } - } - return returnValue; - } catch (SQLException ex) { - ex.printStackTrace(); - Logger.getLogger(SQLShell.class.getName()).log(Level.SEVERE, null, ex); - return null; - } - } - - /** - * Return a list of column names for the specified list of table names. - * @param tableNames a list of tableNames - * @return a list of column names for the specified list of table names. - */ - protected List<String> getColumnNames(List<String> tableNames) { - List<String> returnValues = new ArrayList<String>(); - Iterator<String> iTableNames = tableNames.iterator(); - while (iTableNames.hasNext()) { - String tableName = DBConnector.getInstance().translateDbVar(iTableNames.next().trim()); - try { - ResultSet rs = getConnection().getMetaData().getColumns(getConnection().getCatalog(), DBConnector.getInstance().getSchema(), tableName, "%"); - while (rs.next()) { - if (!returnValues.contains(rs.getString("COLUMN_NAME"))) { - returnValues.add(rs.getString("COLUMN_NAME")); - } - } - } catch (SQLException ex) { - throw new IllegalStateException("Failed to find columnnames for table: "+ tableName, ex); - } - } - return returnValues; - } - - /** - * Try to find a match in the provided list starging with sub. - * If more matches apply show the user a dialog to choose a match or simply display all matches in the window - * @param values all possible values to choose from (not limited with the sub parameter) - * @param sub the start of the match - * @return the match starting with sub minus the sub itself in the correct casing - */ - protected CharSequence findMatch(List<String> values, String sub) { - List<String> matches = new ArrayList<String>(); - Iterator<String> iValues = values.iterator(); - while (iValues.hasNext()) { - String value = iValues.next(); - if (value.toUpperCase().startsWith(sub.toUpperCase())) { - matches.add(value); - } - } - //debug("Matches found: "+ matches.size() +" --> "+ sub +" / "+ values); - String match = null; - if (matches.size() == 1) { - match = matches.get(0); - } else if (matches.size() > 1 && matches.size() < MAX_MATCH_SIZE) { - int y; - if (screenBuffer.size() + cursorPosition.y > Toolkit.getScreenHeight()-3) { - y = Toolkit.getScreenHeight()-4; - } else { - y = screenBuffer.size() + cursorPosition.y; - } - PopUpMenu menu = new PopUpMenu(cursorPosition.x,Math.max(2, y-matches.size()), "Find match"); - Iterator<String> iMatches = matches.iterator(); - while (iMatches.hasNext()) { - menu.add(iMatches.next()); - } - menu.show(); - match = menu.getSelectedItem(); - } else if (matches.size() > 1) { - output("\n"+toColumns(matches)); - } - if (match != null) { - if (sub.length() > 0) { - /*if (Character.isUpperCase(sub.charAt(0))) { - match = match.toUpperCase(); - } else { - match = match.toLowerCase(); - }*/ - match = DBConnector.getInstance().translateDbVar(match); - } - return match.substring(sub.length()); - } - return null; - } - - /** - * Simple method to change a null value to an empty charsequence. - * @param s the charsequence to convert to empty if it is null - * @return empty when s was null or return s when s is not null - */ - protected CharSequence nullToEmpty(CharSequence s) { - if (s == null) { - return ""; - } - return s; - } - /** - * return the tab completion value. - * @param commandLines the current command - * @param cursorPosition the position where the tab completion was invocated - * @return the tab completion value. - */ - protected CharSequence getTabCompletion(SQLCommand commandLines, Point cursorPosition) { - TabCompletionInfo info = null; - String cmd = commandLines.getCommandString(); - if (cmd.length() > 0) { - if (cmd.indexOf(' ') > 0) { - cmd = cmd.substring(0, cmd.indexOf(' ')).trim(); - } - Command tmpCommand = commands.findCommand(cmd); - if (tmpCommand == null) { - for (Command c : commands.getCommands()) { - if (cmd.equalsIgnoreCase(c.getCommandString().toString())) { - tmpCommand = c; - break; - } - } - } - if (tmpCommand != null) { - info = tmpCommand.getTabCompletionInfo(commandLines, cursorPosition); - } - } - if (info == null) { - info = SQLUtil.getTabCompletionInfo(commandLines, cursorPosition); - } - if (info.getMatchType() == TabCompletionInfo.MatchType.SQL_KEYWORD) { - return nullToEmpty(findMatch(info.getPossibleMatches(), info.getStart())); - } - if (info.getMatchType() == TabCompletionInfo.MatchType.TABLE_NAMES) { - //debug("table completion for \""+info.getStart()+"\""); - return nullToEmpty(findMatch(getTableNames(), info.getStart())); - } - if (info.getMatchType() == TabCompletionInfo.MatchType.COLUMN_NAMES) { - return nullToEmpty(findMatch(getColumnNames(info.getPossibleMatches()), info.getStart())); - } - if (info.getMatchType() == TabCompletionInfo.MatchType.OTHER) { - return nullToEmpty(findMatch(info.getPossibleMatches(), info.getStart())); - } - Toolkit.beep(); - return ""; - } - - /** - * (Try) to execute a command) and return true if it succeeded. - * @param command the command to try and execute - * @return true if it succeeded. - */ - protected boolean executeCommand(SQLCommand sqlCommand) { - return executeCommand(sqlCommand, false); - } - - private boolean executeCommand(final SQLCommand sqlCommand, boolean direct) { - final String commandString = sqlCommand.getCommandString(); - if (commandString.equalsIgnoreCase("printStackTrace")) { - if (lastExceptionDetails == null) { - output("No known last exception to print"); - } else { - output(lastExceptionDetails); - } - return true; - } - Command command = createCommand(commandString); // first try to find a match without ; - if (command == null) { - command = createCommand(sqlCommand.getUntrimmedCommandString()); // then with ; for sql statements... - } - if (command == null) { - return false; - } - // make sure only one command is run at once - if (commandThread != null && commandThread.isAlive()) { - try { - commandThread.join(); - } catch (InterruptedException ex) { - Logger.getLogger(SQLShell.class.getName()).log(Level.SEVERE, null, ex); - } - } - output(commandString); - if (direct || !command.backgroundProcessSupported()) { - output(command.execute(sqlCommand)); - } else { - commandThread = new CommandThread(command) { - @Override - void execute() { - output(getCommand().execute(sqlCommand)); - } - }; - commandThread.start(); - } - return true; - } - private Command createCommand(String commandString) { - Command command = commands.findCommand(commandString); - if (command != null) { - return command; - } - if (commandString.matches(".*;[\\s]*")) { - return new QueryCommand(); // TODO is this ever reached??? - } - return null; - } - - - /** - * Paint the screen. - */ - @Override - protected synchronized void paint() { - CharColor color = new CharColor(CharColor.BLACK, CharColor.WHITE, CharColor.BOLD, CharColor.BOLD); - - List<CharSequence> tmpList = new ArrayList<CharSequence>(); - tmpList.addAll(screenBuffer); - - //add prompt - List<? extends CharSequence> currentLines = commandLines.getLines(); - for (int i = 0; i < currentLines.size(); i++) { - if (i == 0 && showPrompt) { - tmpList.add(PROMPT+"> "+currentLines.get(i)); - } else { - String nrI = Integer.toString(i+1); - tmpList.add(emptyLine.substring(0,PROMPT.length() - nrI.length()) + nrI+"> "+currentLines.get(i)); - } - } - int startLine; - if (tmpList.size() > Toolkit.getScreenHeight()-1) { - startLine = tmpList.size() - (Toolkit.getScreenHeight()-1); - if (pageUpCount > 0) { - startLine -= (pageUpCount * Toolkit.getScreenHeight()/2); - if (startLine < 0) { - startLine = 0; - } - } - } else { - startLine = 0; - } - int lineNr; - for (lineNr = startLine;lineNr < tmpList.size() && lineNr - startLine < Toolkit.getScreenHeight()-1; lineNr++) { - CharSequence linePart = tmpList.get(lineNr); - String line = linePart.length() >= emptyLine.length() ? linePart.toString() : linePart + emptyLine.substring(linePart.length()); - Toolkit.printString(line - , 0, lineNr-startLine, color); - } - for (int lNr = lineNr; lNr < Toolkit.getScreenHeight(); lNr++) { - Toolkit.printString(emptyLine, 0, lNr, color); - } - - // paint cursor - color = new CharColor(CharColor.BLACK, CharColor.WHITE, CharColor.REVERSE, CharColor.REVERSE); - String cursorChar = " "; - if (commandLines.getLines().size() > 0) { - String tmp = commandLines.getLines().get(cursorPosition.y).toString(); - if (cursorPosition.x < 0) { - debug("Cursor position was: "+ cursorPosition +" fixing"); - cursorPosition.x = 0; - } - if (cursorPosition.x < tmp.length()) { - cursorChar = tmp.substring(cursorPosition.x, cursorPosition.x+1); - } - } - Toolkit.printString(cursorChar, PROMPT.length() +"> ".length() + cursorPosition.x, lineNr-(commandLines.getLines().size() -cursorPosition.y)-startLine, color); - } - - private void debug(String debug) { - CharColor color = new CharColor(CharColor.BLUE, CharColor.YELLOW); - Toolkit.printString(debug, 1, Toolkit.getScreenHeight()-1, color); - } - - /** - * Method to convert a long string to a displayable list of strings with a max with of the screen width. - * @param text a (long) string - * @return the text devided into multiple lines to match the screen width - */ - private static List<CharSequence> getLines(CharSequence text) { - int maxWidth = Toolkit.getScreenWidth(); - List<CharSequence> list = new ArrayList<CharSequence>(); - StringBuilder buffer = new StringBuilder(); - for (int i=0; i<text.length(); i++) { - char c = text.charAt(i); - if (c=='\n' || buffer.length() == maxWidth) { - String line = buffer.toString(); - list.add(line); - buffer = new StringBuilder(); - if (c != '\n') { - buffer.append(c); - } - } else if (c == '\r') { - //ignore - } else { - buffer.append(c); - } - } - if (buffer.length() > 0) { - list.add(buffer.toString()); - } - return list; - } - - /** - * Convert a list to a presentable text devided into multiple columns. - */ - private StringBuilder toColumns(List<? extends CharSequence> values) { - int maxWidth = 0; - Iterator<? extends CharSequence> iValues = values.iterator(); - while (iValues.hasNext()) { - maxWidth = Math.max(maxWidth, iValues.next().length()); - } - maxWidth+=2;// add extra space - int nrOfColumns = (Toolkit.getScreenWidth()) / maxWidth; - StringBuilder returnValue = new StringBuilder(); - for (int row = 0; row < values.size(); row+=nrOfColumns) { - for (int col = 0; col < nrOfColumns && row + col < values.size(); col++) { - returnValue.append(values.get(row+col) + emptyLine.substring(0, maxWidth - values.get(row+col).length())); - } - returnValue.append('\n'); - } - return returnValue; - } - - /** - * A list which contains a limited number of lines. - */ - private class LimitedArrayList<E> extends ArrayList<E> { - private int maxSize; - /** - * Constructor. - * @param maxSize the maximum number of lines the list may contain - */ - public LimitedArrayList(int maxSize) { - super(maxSize); // some sane default - this.maxSize = maxSize; - } - - @Override - public boolean add(E object) { - if (size() == maxSize) { - remove(0); - } - return super.add(object); - } - @Override - public void add(int index, E object) { - if (size() == maxSize) { - remove(0); - } - super.add(index, object); - } - } - - /** - * Connect command for setting up a connection to a database. - */ - private static class ConnectCommand implements Command { - /** - * Execute the connection command and return a readable result. - * @param command the command string for setting up a connection - * @return a readable result of the execution of this command. - */ - @Override - public CharSequence execute(SQLCommand cmd) { - String command = cmd.getCommandString(); - try { - String cmdString = command.substring("connect".length()).trim(); - if (cmdString.length() > 0 && cmdString.charAt(cmdString.length()-1) == ';') { - cmdString = cmdString.substring(0, cmdString.length()-1); - } - DBConnector.getInstance().connect(cmdString); - return "Connected.\n\n"; - } catch(SQLException e) { - throw new IllegalStateException("Failed to connect: " + e.getMessage(), e); - } - } - @Override - public CharSequence getCommandString() { - return "connect"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - List commandInfo = command.getLines(); - - String startOfCommand = SQLUtil.getStartOfCommand(commandInfo, commandPoint); - if (startOfCommand.indexOf('@') >= 0) { - String end = startOfCommand.substring(startOfCommand.lastIndexOf('@')+1); - List<String> identifiers = new ArrayList<String>(DBConnector.getInstance().getPredefinedConnectionIdentifiers()); - Collections.sort(identifiers); - return new TabCompletionInfo(TabCompletionInfo.MatchType.OTHER, identifiers, end); - } - return null; - } - - @Override - public CharSequence getHelp() { - StringBuffer buf = new StringBuffer(); - Iterator<String> idents = DBConnector.getInstance().getPredefinedConnectionIdentifiers().iterator(); - while (idents.hasNext()) { - buf.append(' '); - String ident = idents.next(); - buf.append(ident); - if (ident.equals(DBConnector.getInstance().getDefaultIdentifier())) { - buf.append(" *"); - } - if (idents.hasNext()) { - buf.append('\n'); - } - } - return "Create a conection to the database\n" + - " user/pass@ident -> connect the user with password pass to the ident\n" + - " user/@ident -> connect the user with an empty password pass to the ident\n"+ - " user@ident -> connect the user to the ident and prompt for password\n"+ - " @ident -> connect to the ident connection.\n"+ - " If default user and/or password are specified these will be used, \n"+ - " otherwise you will be prompted for a username and/or password.\n" + - "Currently configured connection identifiers:\n"+ - buf.toString(); - } - - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - /** - * Command that enables the user to close a connection. - */ - private static class DisConnectCommand implements Command { - @Override - public CharSequence execute(SQLCommand cmd) { - try { - DBConnector.getInstance().disconnect(); - return "Disconnected.\n\n"; - } catch(SQLException e) { - throw new IllegalStateException("Failed to disconnect: " + e.getMessage(), e); - } - } - @Override - public CharSequence getCommandString() { - return "disconnect"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; - } - @Override - public CharSequence getHelp() { - return "Close the current conection to the database"; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - - /** - * Some basic window settings like resize. - */ - private class WindowCommand implements Command { - @Override - public CharSequence execute(SQLCommand cmd) { - String command = cmd.getCommandString(); - String argument = command.trim().substring("window".length()).trim(); - if (argument.equalsIgnoreCase("resize")) { - resize(Toolkit.getScreenWidth(),Toolkit.getScreenHeight()); - return "Window resized to " + Toolkit.getScreenWidth() +"x"+Toolkit.getScreenHeight(); - } - return "Uknown command '"+ argument+"'"; - } - - @Override - public CharSequence getCommandString() { - return "window"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; - } - @Override - public CharSequence getHelp() { - return "window resize: notify the sql client of a screen resize"; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - - /** - * Provide a list of commands executed. - */ - private class HistoryCommand implements Command { - @Override - public CharSequence execute(SQLCommand command) { - StringBuilder returnValue = new StringBuilder(); - Iterator<SQLCommand> iCommands = commandHistory.iterator(); - while (iCommands.hasNext()) { - SQLCommand cmd = iCommands.next(); - returnValue.append(cmd.getCommandString()); - returnValue.append('\n'); - } - return returnValue; - } - @Override - public CharSequence getCommandString() { - return "history"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; - } - @Override - public CharSequence getHelp() { - return "Show history of executed statements\n" + - "By using '/<search>' you can search the command history" ; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - - /** - * Exit the client. - */ - private class QuitCommand implements Command { - private String cmd; - - public QuitCommand(String cmd) { - this.cmd = cmd; - } - @Override - public CharSequence execute(SQLCommand command) { - hide(); - return "Application terminated."; - } - @Override - public CharSequence getHelp() { - return "Quit(exit) the application."; - } - @Override - public CharSequence getCommandString() { - return cmd; - } - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - /** - * Provide help to the user. - */ - private class HelpCommand implements Command { - @Override - public CharSequence execute(SQLCommand sqlCommand) { - // the execution of help consists of: - // 1. is general help.. - // 2. is detailed help about a specific command - // 3. help -k something --> search help for a specific keyword - String command = sqlCommand.getCommandString().trim(); - String cmdString = command.substring("help".length()).trim(); - if (cmdString.endsWith(";")) { - cmdString = cmdString.substring(0, cmdString.length()-1); - } - List<CharSequence> availableCommands = new ArrayList<CharSequence>(); - if (cmdString.length() > 0) { - if (cmdString.startsWith("-k")) { - String keyword = cmdString.subSequence(cmdString.indexOf(" "), cmdString.length()).toString().trim(); - StringBuilder returnValue = new StringBuilder(); - Iterator<Command> iCommands = commands.getCommands().iterator(); - while (iCommands.hasNext()) { - Command cmd= iCommands.next(); - if (cmd.getHelp().toString().indexOf(keyword) >=0 - || cmd.getCommandString().toString().indexOf(keyword) >=0) { - if (returnValue.length() == 0) { - returnValue.append("See the following commands for more details:\n"); - } - returnValue.append(" "); - returnValue.append(cmd.getCommandString()); - returnValue.append("\n"); - } - } - if (returnValue.length() == 0) { - return "Don't know what you mean by '"+ keyword+"'"; - } - return returnValue; - } else { - Iterator<Command> iCommands = commands.getCommands().iterator(); - while (iCommands.hasNext()) { - Command cmd= iCommands.next(); - if (cmd.getCommandString().equals(cmdString)) { - return cmd.getCommandString()+": " - + cmd.getHelp().toString().replaceAll("\n" - , "\n"+emptyLine.substring(0, cmd.getCommandString().length()+3)); - } - } - } - return "Unkown command '"+ cmdString+"'"; - } - // default print all commands - // TODO iterate - StringBuilder returnValue = new StringBuilder(); - returnValue.append("Available key mappings:\n"); - int max = 0; - Iterator<KeyAction> iKeyActions = actionKeys.values().iterator(); - while (iKeyActions.hasNext()) { - max = Math.max(max, iKeyActions.next().getHelp().toString().indexOf('\t')); - } - iKeyActions = actionKeys.values().iterator(); - while (iKeyActions.hasNext()) { - returnValue.append(" "); - //returnValue.append(iKeyActions.next().getHelp()); - String help = iKeyActions.next().getHelp().toString(); - int index = help.indexOf('\t'); - returnValue.append(help.substring(0, index)); - for (int i = index; i < max; i++) { - returnValue.append(' '); - } - returnValue.append(help.substring(index)); - returnValue.append('\n'); - } - returnValue.append("\n\nAvailable commands:\n"); - Iterator<Command> iCommands = commands.getCommands().iterator(); - while (iCommands.hasNext()) { - Command cmd = iCommands.next(); - availableCommands.add(cmd.getCommandString()); - } - returnValue.append(toColumns(availableCommands)); - String helpHeader = "\nHelp for SQLShell client "+SQLProperties.getProperty(SQLProperties.PropertyName.VERSION, "SVN Snapshot")+"\n"+ - "Here you find a list of available commands. "+ - "To get more information about a specific command enter:\n"+ - " help command (for example 'help help')\n\n"+ - "If the list is not sufficient enough you could try searching help using:\n"+ - " help -k searchstring (for example help -k column)\n"+ - "This results in a list of commands matching the searchstring\n\n"; - returnValue.insert(0, helpHeader); - return returnValue; - } - @Override - public CharSequence getCommandString() { - return "help"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; - } - @Override - public CharSequence getHelp() { - return "this command. Please use 'help' to get a list of available commands you can use."; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - - /** - * Convert '~/' to the username dir. - * @param fileName the filename to convert - * @return the converted filename - */ - private static String toFileName(String fileName) { - if (fileName.startsWith("~/")) { - return System.getProperty("user.home")+fileName.substring(1); - } - return fileName; - } - - /** - * Writes in/output to a file. - */ - private class SpoolCommand implements Command { - private String fileName; - - @Override - public CharSequence execute(SQLCommand cmd) { - String command = cmd.getCommandString(); - String nextPart = command.substring("spool".length()).trim(); - if (nextPart.equalsIgnoreCase("off")) { - if (spoolWriter != null) { - try { - spoolWriter.close(); - } catch(Exception e) {/*ignore*/} - spoolWriter = null; - return "Spool closed."; - } else { - return "No spool to close."; - } - } else { - try { - File f = new File(toFileName(nextPart.trim())); - fileName = f.getAbsolutePath(); - if ((f.exists() && !f.canWrite()) || (!f.exists() && !f.createNewFile())) { - throw new IllegalStateException("Failed to create spool to file: '"+fileName+"'"); - } - spoolWriter = new FileWriter(fileName); - } catch (IOException e) { - throw new IllegalStateException("Failed to create spool ("+fileName+"): " + e.toString(), e); - } - return "Spool to "+fileName+" created."; - } - } - - @Override - public CharSequence getCommandString() { - return "spool"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; - } - @Override - public CharSequence getHelp() { - return "filename: Spool all output and queries to the specified file\n"+ - "off : Stop spooling data to the file.\n" + - "Current status:"+(spoolWriter != null ? "on, writing to '"+fileName+"'" : "off"); - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - - private class ExecuteBatchCommand implements Command { - private boolean cancelled; - private Command currentCommand; - @Override - public CharSequence execute(SQLCommand sqlCommand) { - cancelled = false; - currentCommand = null; - String command = sqlCommand.getCommandString(); - // read file from file system and execute - FileInputStream fin = null; - try { - fin = new FileInputStream(toFileName(command.substring(1))); - output("Reading file: "+ toFileName(command.substring(1))); - BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); - StringBuilder cmd = new StringBuilder(); - String line; - while ( ((line = reader.readLine()) != null)) { - if (cancelled) { - return "Aborted"; - } - if (line.startsWith("--")) { - continue; - } - cmd.append(line); - if (line.endsWith(";")) { - // Exec cmd - String commandString = cmd.toString(); - currentCommand = createCommand(commandString); - output(commandString); - output(currentCommand.execute(new InputCommand(commandString))); - cmd=new StringBuilder(); - new Thread() { public void run() { paint();}}.start(); - } - ... [truncated message content] |
From: SVN by r. <sv...@ca...> - 2008-08-03 12:15:28
|
Author: roy Date: 2008-08-03 14:15:17 +0200 (Sun, 03 Aug 2008) New Revision: 279 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java Log: added support for encoding.. TODO add support for 'blob' binaries Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-03 11:37:34 UTC (rev 278) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-03 12:15:17 UTC (rev 279) @@ -20,6 +20,7 @@ import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; @@ -46,12 +47,20 @@ import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; import nl.improved.sqlclient.commands.*; import nl.improved.sqlclient.util.LimitedArrayList; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; /** * The SQLShell abstract main class. @@ -1380,7 +1389,6 @@ */ private class DumpCommand implements Command { private String fileName; - private FileWriter dumpWriter; @Override public CharSequence execute(SQLCommand cmd) { @@ -1393,51 +1401,80 @@ dumpFileName = nextPart; } int rowCount = 0; + PrintWriter out = null; try { File f = new File(toFileName(dumpFileName +".dmp")); fileName = f.getAbsolutePath(); if ((f.exists() && !f.canWrite()) || (!f.exists() && !f.createNewFile())) { throw new IllegalStateException("Failed to create spool to file: '"+fileName+"'"); } - dumpWriter = new FileWriter(fileName); - dumpWriter.write("<dump tablename=\"" + dumpFileName+"\">\n"); + out = new PrintWriter(new FileWriter(fileName)); + StreamResult streamResult = new StreamResult(out); + SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + // SAX2.0 ContentHandler. + TransformerHandler hd = tf.newTransformerHandler(); + Transformer serializer = hd.getTransformer(); + serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); + serializer.setOutputProperty(OutputKeys.INDENT,"yes"); + hd.setResult(streamResult); + hd.startDocument(); + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute("", "", "tablename", "", dumpFileName); + // USERS tag. + hd.startElement("","","dump",atts); + String query = "select * from " + nextPart; Connection c = DBConnector.getInstance().getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery(query); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); while (rs.next()) { - dumpWriter.write(" <row>\n"); + atts.clear(); + hd.startElement("","","row",atts); ResultSetMetaData metaData = rs.getMetaData(); for (int col = 1; col <= metaData.getColumnCount(); col++) { - dumpWriter.write(" <col name=\""+metaData.getColumnName(col)+"\""); + atts.addAttribute("","","name","",metaData.getColumnName(col)); if (metaData.getColumnType(col) == Types.DATE) { - dumpWriter.write(" type=\"date\">"); + atts.addAttribute("","","type","","date"); + hd.startElement("","","col",atts); Date date = rs.getDate(col); if (date != null) { - dumpWriter.write(formatter.format(date)); + String dateString = formatter.format(date); + hd.characters(dateString.toCharArray(), 0, dateString.length()); } + } else if (metaData.getColumnType(col) == Types.BINARY || + metaData.getColumnType(col) == Types.BLOB || + metaData.getColumnType(col) == Types.CLOB || + metaData.getColumnType(col) == Types.LONGNVARCHAR) { + InputStream valueStream = rs.getBinaryStream(col); + //Base64 + atts.addAttribute("","","type","","binary"); + hd.startElement("","","col",atts); } else { - dumpWriter.write(">"); - if (rs.getString(col) != null) { - dumpWriter.write(rs.getString(col)); // TODO fix xml + hd.startElement("","","col",atts); + String value= rs.getString(col); + if (value != null) { + hd.characters(value.toCharArray(), 0, value.length()); } } - dumpWriter.write("</col>\n"); + hd.endElement("","","col"); } - dumpWriter.write(" </row>\n"); + hd.endElement("","","row"); rowCount++; } - dumpWriter.write("</dump>"); + hd.endElement("","","dump"); + hd.endDocument(); + } catch (SAXException ex) { + Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); + } catch (TransformerConfigurationException e) { + throw new IllegalStateException("Failed to create xml handler: " + e.toString(), e); } catch (SQLException e) { throw new IllegalStateException("Failed to execute query for dump("+fileName+"): " + e.toString(), e); } catch (IOException e) { throw new IllegalStateException("Failed to create dump ("+fileName+"): " + e.toString(), e); } finally { - try { - dumpWriter.close(); - } catch (IOException ex) { - Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); + if (out != null) { + out.close(); } } return "Dump to "+fileName+" done. ("+ rowCount+" rows written)"; |
From: SVN by r. <sv...@ca...> - 2008-08-03 11:37:46
|
Author: roy Date: 2008-08-03 13:37:34 +0200 (Sun, 03 Aug 2008) New Revision: 278 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: improved help of dump/read commands code cleanup Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-02 10:11:20 UTC (rev 277) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-03 11:37:34 UTC (rev 278) @@ -1233,11 +1233,13 @@ StringBuilder returnValue = new StringBuilder(); returnValue.append("Available key mappings:\n"); int max = 0; - Iterator<KeyAction> iKeyActions = actionKeys.values().iterator(); + List<KeyAction> keys = new ArrayList<KeyAction>(actionKeys.values()); + keys.addAll(0, specialActionKeys.values()); + Iterator<KeyAction> iKeyActions = keys.iterator(); while (iKeyActions.hasNext()) { max = Math.max(max, iKeyActions.next().getHelp().toString().indexOf('\t')); } - iKeyActions = actionKeys.values().iterator(); + iKeyActions = keys.iterator(); while (iKeyActions.hasNext()) { returnValue.append(" "); //returnValue.append(iKeyActions.next().getHelp()); @@ -1390,6 +1392,7 @@ } else { dumpFileName = nextPart; } + int rowCount = 0; try { File f = new File(toFileName(dumpFileName +".dmp")); fileName = f.getAbsolutePath(); @@ -1423,6 +1426,7 @@ dumpWriter.write("</col>\n"); } dumpWriter.write(" </row>\n"); + rowCount++; } dumpWriter.write("</dump>"); } catch (SQLException e) { @@ -1436,7 +1440,7 @@ Logger.getLogger(AbstractSQLShellWindow.class.getName()).log(Level.SEVERE, null, ex); } } - return "Dump to "+fileName+" done."; + return "Dump to "+fileName+" done. ("+ rowCount+" rows written)"; } @Override @@ -1456,7 +1460,9 @@ } @Override public CharSequence getHelp() { - return "tablename [where clause]"; + return "tablename [where clause]\n" + + "For example: dump users where role='manager';\n\n" + + "See 'read' for options to read the dump file back into the table"; } @Override public boolean abort() { @@ -1483,6 +1489,7 @@ } else { dumpFileName = nextPart; } + int rowCount = 0; try { File f = new File(toFileName(dumpFileName +".dmp")); fileName = f.getAbsolutePath(); @@ -1506,7 +1513,6 @@ String values = ") values ("; Element n = (Element) nodeList.item(0); // row NodeList cols = n.getElementsByTagName("col"); - output("LENGTH : "+ n.getNodeName() +"/ "+ cols.getLength()); for (int colNr = 0; colNr < cols.getLength(); colNr++) { query += cols.item(colNr).getAttributes().getNamedItem("name").getNodeValue(); values += "?"; @@ -1538,6 +1544,7 @@ } } pstmt.executeUpdate(); + rowCount++; } } catch (SQLException e) { throw new IllegalStateException("Failed to execute update query for dump("+fileName+"): " + e.toString(), e); @@ -1546,7 +1553,7 @@ } catch (Exception e) { throw new IllegalStateException("Failed to read dump ("+fileName+"): " + e.toString(), e); } - return "Read from "+fileName+" done."; + return "Read from "+fileName+" done. (" + rowCount+" rows imported)"; } @Override @@ -1566,7 +1573,8 @@ } @Override public CharSequence getHelp() { - return "filename: read dump file from filename\n"; + return "filename: read dump file from filename\n"+ + "See 'dump' for options to create a dump file"; } @Override public boolean abort() { Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-02 10:11:20 UTC (rev 277) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-03 11:37:34 UTC (rev 278) @@ -26,10 +26,7 @@ import nl.improved.sqlclient.AbstractSQLShellWindow; import nl.improved.sqlclient.InputKey; import nl.improved.sqlclient.Point; -import nl.improved.sqlclient.SQLCommand; import nl.improved.sqlclient.Screen; -import nl.improved.sqlclient.TabCompletionInfo; -import nl.improved.sqlclient.commands.Command; /** * SQLShell window based on the jcurses library. @@ -135,6 +132,7 @@ }; } window.setVisible(true); + // repaint loop while (isRunning()) { Screen screen = getScreen(); if (!dontRepaint && repaint) { @@ -157,7 +155,6 @@ */ @Override public void close() { - debug("CLOSE CALLED"); super.close(); window.close(); } |
From: SVN by r. <sv...@ca...> - 2008-08-02 10:11:31
|
Author: roy Date: 2008-08-02 12:11:20 +0200 (Sat, 02 Aug 2008) New Revision: 277 Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java src/main/java/nl/improved/sqlclient/Screen.java src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java Log: finally (really??) fix paint issues added some comments code cleanup Modified: src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-07-31 07:59:52 UTC (rev 276) +++ src/main/java/nl/improved/sqlclient/AbstractSQLShellWindow.java 2008-08-02 10:11:20 UTC (rev 277) @@ -54,8 +54,8 @@ import org.w3c.dom.NodeList; /** - * The SQLShell main class. - * This class provides a (textbased) window for entering sql commands. + * The SQLShell abstract main class. + * This class provides a the basic implementation for entering sql commands. A super implementation is required to show the actual data. */ public abstract class AbstractSQLShellWindow { @@ -89,16 +89,28 @@ */ protected CommandManager commands = new CommandManager(); - private ArrayBlockingQueue<CommandInfo> commandQueue = new ArrayBlockingQueue<CommandInfo>(10, true); // true means fair + /** + * The command list of commands to execute. + */ + private ArrayBlockingQueue<CommandInfo> commandQueue = new ArrayBlockingQueue<CommandInfo>(99, true); // true means fair + /** + * The screen information. + */ private Screen screen; /** * A map of string key representation to a action that should be executed when a specific key is pressed. */ private Map<String, KeyAction> actionKeys = new LinkedHashMap<String, KeyAction>(); + /** + * The special (home, end, up, down, etc) key actions. + */ private Map<InputKey.SpecialKey, KeyAction> specialActionKeys = new LinkedHashMap<InputKey.SpecialKey, KeyAction>(); - private boolean paint = true; + /** + * The programm runs while this var is set to true. + * All threads should stop when this is set to false + */ private boolean run = true; // set to false on quit /** @@ -370,10 +382,13 @@ output("Welcome to the SQLShell client."); output("Type 'help' to get a list of available commands other then the default sql input."); + // + // Thread for executing the sql commands in the background + // Runnable r = new Runnable() { @Override public void run() { - while ( run ) { + while ( isRunning() ) { final CommandInfo cmd; try { cmd = commandQueue.poll(5, TimeUnit.SECONDS); @@ -408,7 +423,6 @@ }; commandThread.start(); } - } } }; @@ -418,24 +432,45 @@ } - // TODO move to Screen??? + /** + * Return the visible screen width. + * @return the visible screen width. + */ public abstract int getScreenWidth(); + /** + * Return the visible screen height. + * @return the visible screen height. + */ public abstract int getScreenHeight(); + /** + * Repaint the screen. + */ protected void repaint() { - if (paint) { - try { - synchronized(this) { - paint(screen); - } - } catch(Throwable t) { - error(t); - } + if (isRunning()) { + paint(getScreen()); } } + + /** + * Paints the screen. + * @param screen the screen to be painted + */ public abstract void paint(Screen screen); + /** + * Make a beep sound. + */ public abstract void beep(); + /** + * Print a debug string. + * @param debug the string to print in the debug line + */ public abstract void debug(String debug); + /** + * Shows a popupwindow to allow the user to make a selection from the list of possible matches. + * @param items the list of possible matches + * @param p the character x/y location to show the popupscreen on + */ public abstract String select(List<String> items, Point p); /** * Returns the connection to the database @@ -445,9 +480,10 @@ return DBConnector.getInstance().getConnection(); } - public void close() { - debug("CLOSE HERE"); - System.out.println("CLOSE HERE"); + /** + * Close all writers. + */ + public void close() { // TODO move to someplace else where it's less likely to forget if (spoolWriter != null) { try { spoolWriter.close(); @@ -1111,7 +1147,6 @@ } @Override public CharSequence execute(SQLCommand command) { - paint = false; run = false; close(); return "Application terminated."; @@ -1771,6 +1806,15 @@ cursorPosition.x = lineBuffer.length(); lineBuffer.append(line); } + + protected boolean isRunning() { + return run; + } + + protected Screen getScreen() { + return screen; + } + private interface KeyAction { void execute(); CharSequence getHelp(); Modified: src/main/java/nl/improved/sqlclient/Screen.java =================================================================== --- src/main/java/nl/improved/sqlclient/Screen.java 2008-07-31 07:59:52 UTC (rev 276) +++ src/main/java/nl/improved/sqlclient/Screen.java 2008-08-02 10:11:20 UTC (rev 277) @@ -19,7 +19,7 @@ import nl.improved.sqlclient.util.LimitedArrayList; /** - * + * Screen class holding information that needs to be painted in the sql window. * @author roy */ public class Screen { @@ -28,6 +28,9 @@ * The (default) maximum matches to show in a selection dialog. */ public static final int MAX_MATCH_SIZE = 15; + /** + * The maximum line length. + */ public int MAX_LINE_LENGTH; // not static and final.. since it can change on window resize /** * The prompt to show when entering sql commands. @@ -60,35 +63,63 @@ */ private Point cursorPosition = new Point(0,0); + /** + * Returns the position of the blinking cursor. + * @return the position of the blinking cursor. + */ public Point getCursorPosition() { return cursorPosition; } + /** + * Returns the screen buffer. + * @return the screen buffer. + */ public List<CharSequence> getScreenBuffer() { return screenBuffer; } + /** + * Returns the pageup count used for viewing history. + * @return the pageup count used for viewing history. + */ public int getPageUpCount() { return pageUpCount; } + /** + * Changes the pageup count used for viewing history. + * @param pageUpCount the pageup count used for viewing history. + */ public void setPageUpCount(int pageUpCount) { this.pageUpCount = pageUpCount; } + /** + * Returns true if the prompt should be visible. + * @return true if the prompt should be visible. + */ public boolean getShowPrompt() { return showPrompt; } + /** + * Set to true if the prompt should be visible. + * @param showPrompt true if the prompt should be visible. + */ public void setShowPrompt(boolean showPrompt) { this.showPrompt = showPrompt; } + /** + * Returns a full empty line string. + * @return a full empty line string. + */ public String getEmptyLine() { return emptyLine; } - public void setEmptyLine(String emptyLine) { + void setEmptyLine(String emptyLine) { this.emptyLine = emptyLine; } } Modified: src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java =================================================================== --- src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-07-31 07:59:52 UTC (rev 276) +++ src/main/java/nl/improved/sqlclient/jcurses/SQLShellWindow.java 2008-08-02 10:11:20 UTC (rev 277) @@ -32,27 +32,43 @@ import nl.improved.sqlclient.commands.Command; /** - * + * SQLShell window based on the jcurses library. + * @see http://jcurses.sourceforge.net/ * @author roy */ public class SQLShellWindow extends AbstractSQLShellWindow { private Window window; + private boolean dontRepaint = false; + private boolean repaint = true; + /** + * Default constructor. + */ public SQLShellWindow() { - //commands.register("WINDOW[\\s]+[A-Z]+", new WindowCommand()); } - + /** + * Return the screen width. + * @return the screen width. + */ @Override public int getScreenWidth() { return Toolkit.getScreenWidth(); } + /** + * Return the screen height. + * @return the screen height. + */ @Override public int getScreenHeight() { return Toolkit.getScreenHeight(); } + /** + * Write a debug string. + * @param debug the debug to output + */ @Override public void debug(String debug) { synchronized(this) { @@ -62,6 +78,9 @@ } + /** + * Set the window to be visible. + */ public void show() { if (window == null) { window = new Window(getScreenWidth(), getScreenHeight(), true, "SQLShell") { @@ -116,8 +135,26 @@ }; } window.setVisible(true); + while (isRunning()) { + Screen screen = getScreen(); + if (!dontRepaint && repaint) { + try { + synchronized(this) { + paint(screen); + } + } catch(Throwable t) { + error(t); + } + } + try { + Thread.sleep(200); + } catch(Exception e) {} + } } + /** + * Close the window. + */ @Override public void close() { debug("CLOSE CALLED"); @@ -125,61 +162,32 @@ window.close(); } + /** - * Some basic window settings like resize. + * Shows a popupwindow to allow the user to make a selection from the list of possible matches. + * @param items the list of possible matches + * @param p the character x/y location to show the popupscreen on */ - private class WindowCommand implements Command { - @Override - public CharSequence execute(SQLCommand cmd) { - String command = cmd.getCommandString(); - String argument = command.trim().substring("window".length()).trim(); - if (argument.equalsIgnoreCase("resize")) { - //window.resize(getScreenWidth(),getScreenHeight()); // TODO - return "Window resized to " + getScreenWidth() +"x"+getScreenHeight(); - } - return "Uknown command '"+ argument+"'"; - } - - @Override - public CharSequence getCommandString() { - return "window"; - } - - /** - * Returns some tab completion info for the specified command. - * @param commandInfo the command lines - * @param commandPoint the cursor position - * @return some tab completion info for the specified command. - */ - @Override - public TabCompletionInfo getTabCompletionInfo(SQLCommand command, Point commandPoint) { - return null; - } - @Override - public CharSequence getHelp() { - return "window resize: notify the sql client of a screen resize"; - } - @Override - public boolean abort() { - return false;// not implemented - } - @Override - public boolean backgroundProcessSupported() { - return false; - } - } - @Override public String select(List<String> items, Point p) { - PopUpMenu menu = new PopUpMenu(p.x,Math.max(2, p.y-items.size()), "Find match"); - Iterator<String> iMatches = items.iterator(); - while (iMatches.hasNext()) { - menu.add(iMatches.next()); + try { + PopUpMenu menu = new PopUpMenu(p.x,Math.max(2, p.y-items.size()), "Find match"); + Iterator<String> iMatches = items.iterator(); + while (iMatches.hasNext()) { + menu.add(iMatches.next()); + } + dontRepaint = true; + menu.show(); + return menu.getSelectedItem(); + } finally { + dontRepaint = false; } - menu.show(); - return menu.getSelectedItem(); } + /** + * Paint the screen. + * @param screen the screen information to be painted + */ @Override public void paint(Screen screen) { synchronized(this) { @@ -240,6 +248,24 @@ } } + /** + * Override to allow painting on the main thread to overcome painting errors. + */ + @Override + protected void repaint() { + if (isRunning()) { + repaint = true; + } + } + + /** + * Beep. + */ + @Override + public void beep() { + Toolkit.beep(); + } + public static void main(String[] args) { SQLShellWindow shell = new SQLShellWindow(); shell.show(); @@ -250,9 +276,4 @@ } */ } - - @Override - public void beep() { - Toolkit.beep(); - } } |