Search in sources :

Example 1 with TableRenderer

use of henplus.view.TableRenderer in project henplus by neurolabs.

the class KeyBindCommand method showKeyBindings.

private void showKeyBindings() {
    DRV_META[0].resetWidth();
    DRV_META[1].resetWidth();
    final TableRenderer table = new TableRenderer(DRV_META, HenPlus.out());
    for (Entry<String, String> entry : _bindings.entrySet()) {
        final Column[] row = new Column[2];
        row[0] = new Column(entry.getKey());
        row[1] = new Column(entry.getValue());
        table.addRow(row);
    }
    table.closeTable();
}
Also used : TableRenderer(henplus.view.TableRenderer) Column(henplus.view.Column)

Example 2 with TableRenderer

use of henplus.view.TableRenderer in project henplus by neurolabs.

the class AbstractPropertyCommand method execute.

/**
     * execute the command given.
     */
@Override
public int execute(final SQLSession currentSession, final String cmd, final String param) {
    final StringTokenizer st = new StringTokenizer(param);
    final int argc = st.countTokens();
    if (cmd.startsWith("re")) {
        // 'reset-property'
        if (argc == 1) {
            final String name = st.nextToken();
            PropertyHolder holder;
            holder = getRegistry().getPropertyMap().get(name);
            if (holder == null) {
                return EXEC_FAILED;
            }
            final String defaultValue = holder.getDefaultValue();
            try {
                holder.setValue(defaultValue);
            } catch (final Exception e) {
                HenPlus.msg().println("setting to default '" + defaultValue + "' failed.");
                return EXEC_FAILED;
            }
            return SUCCESS;
        }
        return SYNTAX_ERROR;
    } else {
        /*
             * no args. show available properties
             */
        if (argc == 0) {
            PROP_META[0].resetWidth();
            PROP_META[1].resetWidth();
            final TableRenderer table = new TableRenderer(PROP_META, HenPlus.out());
            for (Map.Entry<String, PropertyHolder> entry : getRegistry().getPropertyMap().entrySet()) {
                final Column[] row = new Column[3];
                final PropertyHolder holder = entry.getValue();
                row[0] = new Column(entry.getKey());
                row[1] = new Column(holder.getValue());
                row[2] = new Column(holder.getShortDescription());
                table.addRow(row);
            }
            table.closeTable();
            return SUCCESS;
        } else if (argc == 1) {
            /*
                 * one arg: show help
                 */
            final String name = st.nextToken();
            PropertyHolder holder;
            holder = getRegistry().getPropertyMap().get(name);
            if (holder == null) {
                return EXEC_FAILED;
            }
            printDescription(name, holder);
            return SUCCESS;
        } else if (argc >= 2) {
            /*
                 * more than one arg
                 */
            final String varname = (String) st.nextElement();
            int pos = 0;
            final int paramLength = param.length();
            // skip whitespace after 'set'
            while (pos < paramLength && Character.isWhitespace(param.charAt(pos))) {
                ++pos;
            }
            // skip non-whitespace after 'set ': variable name
            while (pos < paramLength && !Character.isWhitespace(param.charAt(pos))) {
                ++pos;
            }
            // skip whitespace before vlue..
            while (pos < paramLength && Character.isWhitespace(param.charAt(pos))) {
                ++pos;
            }
            String value = param.substring(pos);
            if (value.startsWith("\"") && value.endsWith("\"")) {
                value = value.substring(1, value.length() - 1);
            } else if (value.startsWith("\'") && value.endsWith("\'")) {
                value = value.substring(1, value.length() - 1);
            }
            try {
                getRegistry().setProperty(varname, value);
            } catch (final Exception e) {
                HenPlus.msg().println(e.getMessage());
                return EXEC_FAILED;
            }
            return SUCCESS;
        }
    }
    return SUCCESS;
}
Also used : TableRenderer(henplus.view.TableRenderer) StringTokenizer(java.util.StringTokenizer) PropertyHolder(henplus.property.PropertyHolder) Column(henplus.view.Column) Map(java.util.Map)

Example 3 with TableRenderer

use of henplus.view.TableRenderer in project henplus by neurolabs.

the class PluginCommand method execute.

/**
     * execute the command given.
     */
@Override
public int execute(final SQLSession currentSession, final String cmd, final String param) {
    final StringTokenizer st = new StringTokenizer(param);
    final int argc = st.countTokens();
    if ("list-plugins".equals(cmd)) {
        if (argc != 0) {
            return SYNTAX_ERROR;
        }
        HenPlus.msg().println("loaded plugins are marked with '*'");
        DRV_META[0].resetWidth();
        DRV_META[1].resetWidth();
        final TableRenderer table = new TableRenderer(DRV_META, HenPlus.out());
        for (Entry<String, Command> entry : _plugins.entrySet()) {
            final Column[] row = new Column[2];
            final Command c = entry.getValue();
            final String clsName = entry.getKey();
            row[0] = new Column((c != null ? "* " : "  ") + clsName);
            if (c != null) {
                final StringBuilder cmds = new StringBuilder();
                final String[] cmdList = c.getCommandList();
                for (int i = 0; i < cmdList.length; ++i) {
                    cmds.append(cmdList[i]).append("\n");
                }
                row[1] = new Column(cmds.toString().trim());
            } else {
                row[1] = new Column(null);
            }
            table.addRow(row);
        }
        table.closeTable();
        return SUCCESS;
    } else if ("plug-in".equals(cmd)) {
        if (argc != 1) {
            return SYNTAX_ERROR;
        }
        final String pluginClass = (String) st.nextElement();
        if (_plugins.containsKey(pluginClass)) {
            HenPlus.msg().println("plugin '" + pluginClass + "' already loaded");
            return EXEC_FAILED;
        }
        Command plugin = null;
        try {
            plugin = loadPlugin(pluginClass);
        } catch (final Exception e) {
            HenPlus.msg().println("couldn't load plugin: " + e.getMessage());
            return EXEC_FAILED;
        }
        if (plugin != null) {
            _plugins.put(pluginClass, plugin);
            final String[] cmds = plugin.getCommandList();
            HenPlus.out().print("adding commands: ");
            for (int i = 0; i < cmds.length; ++i) {
                if (i != 0) {
                    HenPlus.out().print(", ");
                }
                HenPlus.out().print(cmds[i]);
            }
            HenPlus.out().println();
        }
    } else if ("plug-out".equals(cmd)) {
        if (argc != 1) {
            return SYNTAX_ERROR;
        }
        final String pluginClass = (String) st.nextElement();
        if (!_plugins.containsKey(pluginClass)) {
            HenPlus.msg().println("unknown plugin '" + pluginClass + "'");
            return EXEC_FAILED;
        } else {
            final Command c = _plugins.remove(pluginClass);
            _henplus.getDispatcher().unregister(c);
        }
    }
    return SUCCESS;
}
Also used : TableRenderer(henplus.view.TableRenderer) StringTokenizer(java.util.StringTokenizer) AbstractCommand(henplus.AbstractCommand) Command(henplus.Command) Column(henplus.view.Column)

Example 4 with TableRenderer

use of henplus.view.TableRenderer in project henplus by neurolabs.

the class DescribeCommand method execute.

/**
     * execute the command given.
     */
@Override
public int execute(final SQLSession session, final String cmd, final String param) {
    // make use of properties for these properties?
    // (since the options just toggle, this may be convenient)
    boolean showDescriptions = true;
    boolean showIndex = "idescribe".equals(cmd);
    boolean showTime = true;
    final StringTokenizer st = new StringTokenizer(param);
    if (st.countTokens() < 1) {
        return SYNTAX_ERROR;
    }
    // this was a flag to ensure that all options come before the tablenames
    // can probably be removed...
    final boolean moreOptions = true;
    while (st.hasMoreTokens()) {
        String tabName = st.nextToken();
        if (moreOptions && tabName.startsWith("-")) {
            if (tabName.indexOf('i') > -1) {
                showIndex = !showIndex;
            }
            if (tabName.indexOf('v') > -1) {
                showDescriptions = !showDescriptions;
            }
            if (tabName.indexOf('t') > -1) {
                showTime = !showTime;
            }
        } else {
            // more_options = false; // options can stand at every position
            // --> toggle
            boolean correctName = true;
            if (tabName.startsWith("\"")) {
                tabName = stripQuotes(tabName);
                correctName = false;
            }
            // separate schama and table.
            String schema = null;
            final int schemaDelim = tabName.indexOf('.');
            if (schemaDelim > 0) {
                schema = tabName.substring(0, schemaDelim);
                tabName = tabName.substring(schemaDelim + 1);
            }
            // FIXME: provide correct name as well for schema!
            if (correctName) {
                final String alternative = _tableCompleter.correctTableName(tabName);
                if (alternative != null && !alternative.equals(tabName)) {
                    tabName = alternative;
                    HenPlus.out().println("describing table: '" + tabName + "' (corrected name)");
                }
            }
            ResultSet rset = null;
            final Set<String> doubleCheck = new HashSet<String>();
            try {
                _interrupted = false;
                SigIntHandler.getInstance().pushInterruptable(this);
                boolean anyLeftArrow = false;
                boolean anyRightArrow = false;
                final long startTime = System.currentTimeMillis();
                final String catalog = session.getConnection().getCatalog();
                String description = null;
                String tableType = null;
                if (_interrupted) {
                    return SUCCESS;
                }
                final DatabaseMetaData meta = session.getConnection().getMetaData();
                for (int i = 0; i < DESC_META.length; ++i) {
                    DESC_META[i].resetWidth();
                }
                rset = meta.getTables(catalog, schema, tabName, LIST_TABLES);
                if (rset != null && rset.next()) {
                    tableType = rset.getString(4);
                    // remark
                    description = rset.getString(5);
                }
                rset.close();
                /*
                     * get primary keys.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                final Map<String, String> pks = new HashMap<String, String>();
                rset = meta.getPrimaryKeys(null, schema, tabName);
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        final String col = rset.getString(4);
                        final int pkseq = rset.getInt(5);
                        final String pkname = rset.getString(6);
                        String desc = pkname != null ? pkname : "*";
                        if (pkseq > 1) {
                            desc = new StringBuilder().append(desc).append("{").append(pkseq).append("}").toString();
                        }
                        pks.put(col, desc);
                    }
                    rset.close();
                }
                /*
                     * get referenced primary keys.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                rset = meta.getExportedKeys(null, schema, tabName);
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        final String col = rset.getString(4);
                        String fktable = rset.getString(7);
                        final String fkcolumn = rset.getString(8);
                        fktable = new StringBuilder().append(fktable).append("(").append(fkcolumn).append(")").toString();
                        String desc = pks.get(col);
                        desc = desc == null ? new StringBuilder().append(" <- ").append(fktable).toString() : new StringBuilder().append(desc).append("\n <- ").append(fktable).toString();
                        anyLeftArrow = true;
                        pks.put(col, desc);
                    }
                    rset.close();
                }
                /*
                     * get foreign keys.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                final Map<String, String> fks = new HashMap<String, String>();
                // with foreign keys...
                try {
                    rset = meta.getImportedKeys(null, schema, tabName);
                } catch (final NoSuchElementException e) {
                    Logger.debug("Database problem reading meta data: ", e);
                }
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        String table = rset.getString(3);
                        final String pkcolumn = rset.getString(4);
                        table = table + "(" + pkcolumn + ")";
                        final String col = rset.getString(8);
                        final String fkname = rset.getString(12);
                        String desc = fkname != null ? new StringBuilder().append(fkname).append("\n -> ").toString() : " -> ";
                        desc += table;
                        anyRightArrow = true;
                        fks.put(col, desc);
                    }
                    rset.close();
                }
                HenPlus.out().println(("VIEW".equals(tableType) ? "View: " : "Table: ") + tabName);
                if (description != null) {
                    HenPlus.out().println(description);
                }
                if (catalog != null) {
                    HenPlus.msg().println("catalog: " + catalog);
                }
                if (anyLeftArrow) {
                    HenPlus.msg().println(" '<-' : referenced by");
                }
                if (anyRightArrow) {
                    HenPlus.msg().println(" '->' : referencing");
                }
                /*
                     * if all columns belong to the same table name, then don't
                     * report it. A different table name may only occur in rare
                     * circumstance like object oriented databases.
                     */
                boolean allSameTableName = true;
                /*
                     * build up actual describe table.
                     */
                if (_interrupted) {
                    return SUCCESS;
                }
                rset = meta.getColumns(catalog, schema, tabName, null);
                final List<Column[]> rows = new ArrayList<Column[]>();
                int colNum = 0;
                boolean anyDescription = false;
                if (rset != null) {
                    while (!_interrupted && rset.next()) {
                        final Column[] row = new Column[9];
                        row[0] = new Column(++colNum);
                        final String thisTabName = rset.getString(3);
                        row[1] = new Column(thisTabName);
                        allSameTableName &= tabName.equals(thisTabName);
                        final String colname = rset.getString(4);
                        if (doubleCheck.contains(colname)) {
                            continue;
                        }
                        doubleCheck.add(colname);
                        row[2] = new Column(colname);
                        String type = rset.getString(6);
                        final int colSize = rset.getInt(7);
                        final int colDp = rset.getInt(9);
                        if (colSize > 0) {
                            if (colDp == 0) {
                                type = type + "(" + colSize + ")";
                            } else {
                                type = type + "(" + colSize + "," + colDp + ")";
                            }
                        }
                        row[3] = new Column(type);
                        final String defaultVal = rset.getString(13);
                        row[4] = new Column(rset.getString(18));
                        // oracle appends newline to default values for some
                        // reason.
                        row[5] = new Column((defaultVal != null ? defaultVal.trim() : null));
                        final String pkdesc = pks.get(colname);
                        row[6] = new Column(pkdesc != null ? pkdesc : "");
                        final String fkdesc = fks.get(colname);
                        row[7] = new Column(fkdesc != null ? fkdesc : "");
                        final String colDesc = showDescriptions ? rset.getString(12) : null;
                        row[8] = new Column(colDesc);
                        anyDescription |= colDesc != null;
                        rows.add(row);
                    }
                }
                rset.close();
                /*
                     * we render the table now, since we only know now, whether
                     * we will show the first column and the description column
                     * or not.
                     */
                DESC_META[1].setDisplay(!allSameTableName);
                DESC_META[8].setDisplay(anyDescription);
                final TableRenderer table = new TableRenderer(DESC_META, HenPlus.out());
                final Iterator<Column[]> it = rows.iterator();
                while (it.hasNext()) {
                    table.addRow(it.next());
                }
                table.closeTable();
                if (_interrupted) {
                    return SUCCESS;
                }
                if (showIndex) {
                    showIndexInformation(tabName, schema, meta);
                }
                if (showTime) {
                    TimeRenderer.printTime(System.currentTimeMillis() - startTime, HenPlus.out());
                    HenPlus.out().println();
                }
            } catch (final Exception e) {
                final String ex = e.getMessage() != null ? e.getMessage().trim() : e.toString();
                Logger.error("Database problem reading meta data: ", ex);
                return EXEC_FAILED;
            } finally {
                if (rset != null) {
                    try {
                        rset.close();
                    } catch (final Exception e) {
                    }
                }
            }
        }
    }
    return SUCCESS;
}
Also used : TableRenderer(henplus.view.TableRenderer) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DatabaseMetaData(java.sql.DatabaseMetaData) SQLException(java.sql.SQLException) NoSuchElementException(java.util.NoSuchElementException) StringTokenizer(java.util.StringTokenizer) Column(henplus.view.Column) ResultSet(java.sql.ResultSet) NoSuchElementException(java.util.NoSuchElementException) HashSet(java.util.HashSet)

Example 5 with TableRenderer

use of henplus.view.TableRenderer in project henplus by neurolabs.

the class AliasCommand method showAliases.

private void showAliases() {
    DRV_META[0].resetWidth();
    DRV_META[1].resetWidth();
    final TableRenderer table = new TableRenderer(DRV_META, HenPlus.out());
    for (Map.Entry<String, String> entry : _aliases.entrySet()) {
        final Column[] row = new Column[2];
        row[0] = new Column(entry.getKey());
        row[1] = new Column(entry.getValue());
        table.addRow(row);
    }
    table.closeTable();
}
Also used : TableRenderer(henplus.view.TableRenderer) Column(henplus.view.Column) TreeMap(java.util.TreeMap) Map(java.util.Map) SortedMap(java.util.SortedMap)

Aggregations

Column (henplus.view.Column)10 TableRenderer (henplus.view.TableRenderer)10 StringTokenizer (java.util.StringTokenizer)5 Map (java.util.Map)2 AbstractCommand (henplus.AbstractCommand)1 Command (henplus.Command)1 SQLSession (henplus.SQLSession)1 PropertyHolder (henplus.property.PropertyHolder)1 DatabaseMetaData (java.sql.DatabaseMetaData)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 NoSuchElementException (java.util.NoSuchElementException)1 SortedMap (java.util.SortedMap)1 TreeMap (java.util.TreeMap)1