Esempio n. 1
0
 /** Gets the value for the given node at the given column. */
 public Object getValueAt(Object node, int col) {
   DefaultMutableTreeNode tree_node = (DefaultMutableTreeNode) node;
   Object value = tree_node.getUserObject();
   switch (col) {
       // Name
     case 0:
       return value;
       // Value
     case 1:
       if (value instanceof ConfigElement) {
         return null;
       } else if (value instanceof PropertyDefinition) {
         // Only provide comma delimited editing for simple types
         if (((PropertyDefinition) value).getType() != ConfigElement.class) {
           StringBuffer buffer = new StringBuffer();
           for (Enumeration e = tree_node.children(); e.hasMoreElements(); ) {
             DefaultMutableTreeNode child_node = (DefaultMutableTreeNode) e.nextElement();
             buffer.append(child_node.getUserObject());
             if (e.hasMoreElements()) {
               buffer.append(", ");
             }
           }
           return buffer.toString();
         }
         return null;
       }
       return value;
   }
   return null;
 }
    protected void writeAuditTrail(String strPath, String strUser, StringBuffer sbValues) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;
      ArrayList aListData = WUtil.strToAList(sbValues.toString(), false, "\n");
      StringBuffer sbData = sbValues;
      String strPnl = (this instanceof DisplayTemplate) ? "Data Template " : "Data Dir ";
      if (reader == null) {
        Messages.postDebug("Error opening file " + strPath);
        return;
      }

      try {
        while ((strLine = reader.readLine()) != null) {
          // if the line in the file is not in the arraylist,
          // then that line has been deleted
          if (!aListData.contains(strLine))
            WUserUtil.writeAuditTrail(new Date(), strUser, "Deleted " + strPnl + strLine);

          // remove the lines that are also in the file or those which
          // have been deleted.
          aListData.remove(strLine);
        }

        // Traverse through the remaining new lines in the arraylist,
        // and write it to the audit trail
        for (int i = 0; i < aListData.size(); i++) {
          strLine = (String) aListData.get(i);
          WUserUtil.writeAuditTrail(new Date(), strUser, "Added " + strPnl + strLine);
        }
        reader.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    /** Reads the file, and sets the label and the values in the hashmap. */
    protected void setHM(String strPath, HashMap hmPnl) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      boolean bFileEmpty = true;
      boolean bPart11Pnl = isPart11Pnl();
      boolean bDefaultFile = isDefaultFile();

      // if the file is empty, then create an empty set of textfields.
      if (reader == null) {
        // displayNewTxf("","");
        return;
      }

      String strLine = null;
      StringTokenizer strTok;

      try {
        // read the file, and create a new set of textfields,
        // with the values from the file.
        while ((strLine = reader.readLine()) != null) {
          String strLabel = "";
          String strValue = "";
          bFileEmpty = false;

          if (strLine.startsWith("#")
              || strLine.startsWith("@")
              || strLine.startsWith("%")
              || strLine.startsWith("\"@")) continue;

          if (strLine.startsWith("\"")) strTok = new StringTokenizer(strLine, "\"");
          else strTok = new StringTokenizer(strLine, File.pathSeparator + ",\n");

          if (!strTok.hasMoreTokens()) continue;

          strLabel = strTok.nextToken();

          // the format for the part11 Default file is a little different
          // only parse out the part11Dir, and don't display other defaults
          if (bPart11Pnl && bDefaultFile) {
            if (!strLabel.equalsIgnoreCase("part11Dir")) continue;
          }

          if (strTok.hasMoreTokens()) {
            while (strTok.hasMoreTokens()) {
              strValue += strTok.nextToken();
              if (strTok.hasMoreTokens()) strValue += " ";
            }
          }

          // append "/data/$name" to part11Dir
          if (bPart11Pnl && bDefaultFile && strLabel.equalsIgnoreCase("part11Dir")) {
            StringBuffer sbDir = new StringBuffer(strValue);
            if (sbDir.lastIndexOf(File.separator) < sbDir.length() - 1)
              sbDir.append(File.separator);
            sbDir.append("data" + File.separator + "$");
            sbDir.append(WGlobal.NAME);
            strValue = sbDir.toString();
          }

          // displayNewTxf(strLabel, strValue);
          if (strLabel != null && strLabel.trim().length() > 0) hmPnl.put(strLabel, strValue);
        }
        reader.close();
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
    /**
     * Write the file by writing the values from the labels, and the values list.
     *
     * @param strFile the file to be written.
     * @param aListLabels arraylist of texfields of labels.
     * @param aListValues arraylist of texfields of values.
     */
    protected void writeFile(
        String strUser, String strFile, ArrayList aListLabels, ArrayList aListValues) {
      String strPath = FileUtil.openPath(strFile);
      String strLabel = "";
      String strValue = "";
      StringBuffer sbValues = new StringBuffer();
      JTextField txfLabel = null;
      JTextField txfValue = null;
      boolean bNewFile = false;
      int nFDAMode = Util.getPart11Mode();

      // if it's the part11 pnl and the mode is nonFDA,
      // then don't write the file for this panel
      // the other way is not true.
      if (this instanceof DisplayParentDirectory) {
        if ((isPart11Pnl() && nFDAMode == Util.NONFDA)) {
          return;
        }
      }

      if (strPath == null) {
        strPath = FileUtil.savePath(strFile);
        bNewFile = true;
      }

      if (strPath == null || aListLabels == null) return;

      if (aListValues == null) aListValues = new ArrayList();

      // Get the list of the textfields for values and labels.
      int nLblSize = aListLabels.size();
      int nValueSize = aListValues.size();
      ArrayList<String> labelList = new ArrayList<String>();

      // Get the value from each textfield, and add it to the buffer.
      for (int i = 0; i < nLblSize; i++) {
        txfLabel = (JTextField) aListLabels.get(i);
        txfValue = (i < nValueSize) ? (JTextField) aListValues.get(i) : null;

        strLabel = (txfLabel != null) ? txfLabel.getText() : null;
        strValue = (txfValue != null) ? txfValue.getText() : "";

        // We need to be sure they don't have two data directories with
        // the same labels.  Save the label list if we are writing to
        // the "data" file.
        if (strFile.indexOf("data") != -1) {
          if (labelList.contains(strLabel)) {
            Messages.postError(
                "The Data Directory specifications "
                    + "must not have duplicate Label names. "
                    + "The Label \""
                    + strLabel
                    + "\" is duplicated.  "
                    + "Skipping the second instance.  Please "
                    + "specify a new Label.");
            continue;
          } else labelList.add(strLabel);
        }

        if (strLabel == null || strLabel.trim().length() <= 0 || strValue.equals(INFOSTR)) continue;

        // for user template tab, don't need to parse the value
        if (!(this instanceof DisplayTemplate)) strValue = getValue(strUser, strValue);
        strLabel = strLabel.trim();
        if (strValue != null) strValue = strValue.trim();

        // sbValues.append("\"");
        sbValues.append(strLabel);
        // sbValues.append("\"  ");

        sbValues.append(File.pathSeparator);
        sbValues.append(strValue);
        sbValues.append("\n");
      }

      if (Util.isPart11Sys()) writeAuditTrail(strPath, strUser, sbValues);

      // write the data to the file.
      BufferedWriter writer = WFileUtil.openWriteFile(strPath);
      WFileUtil.writeAndClose(writer, sbValues);

      // if it's a template file, then make it writable for everyone.
      if (bNewFile) {
        String strCmd = "chmod 755 ";
        if (this instanceof DisplayTemplate) strCmd = "chmod 777 ";
        if (Util.iswindows()) strPath = UtilB.windowsPathToUnix(strPath);
        String[] cmd = {WGlobal.SHTOOLCMD, WGlobal.SHTOOLOPTION, strCmd + strPath};
        WUtil.runScriptInThread(cmd);
      }
    }
  /** Method declaration */
  private void showResultInText() {

    String col[] = gResult.getHead();
    int width = col.length;
    int size[] = new int[width];
    Vector data = gResult.getData();
    String row[];
    int height = data.size();

    for (int i = 0; i < width; i++) {
      size[i] = col[i].length();
    }

    for (int i = 0; i < height; i++) {
      row = (String[]) data.elementAt(i);

      for (int j = 0; j < width; j++) {
        int l = row[j].length();

        if (l > size[j]) {
          size[j] = l;
        }
      }
    }

    StringBuffer b = new StringBuffer();

    for (int i = 0; i < width; i++) {
      b.append(col[i]);

      for (int l = col[i].length(); l <= size[i]; l++) {
        b.append(' ');
      }
    }

    b.append(NL);

    for (int i = 0; i < width; i++) {
      for (int l = 0; l < size[i]; l++) {
        b.append('-');
      }

      b.append(' ');
    }

    b.append(NL);

    for (int i = 0; i < height; i++) {
      row = (String[]) data.elementAt(i);

      for (int j = 0; j < width; j++) {
        b.append(row[j]);

        for (int l = row[j].length(); l <= size[j]; l++) {
          b.append(' ');
        }
      }

      b.append(NL);
    }

    b.append(NL + height + " row(s) in " + lTime + " ms");
    txtResult.setText(b.toString());
  }
  private void testPerformance() {

    String all = txtCommand.getText();
    StringBuffer b = new StringBuffer();
    long total = 0;

    for (int i = 0; i < all.length(); i++) {
      char c = all.charAt(i);

      if (c != '\n') {
        b.append(c);
      }
    }

    all = b.toString();

    String g[] = new String[4];

    g[0] = "ms";
    g[1] = "count";
    g[2] = "sql";
    g[3] = "error";

    gResult.setHead(g);

    int max = 1;

    lTime = System.currentTimeMillis() - lTime;

    while (!all.equals("")) {
      int i = all.indexOf(';');
      String sql;

      if (i != -1) {
        sql = all.substring(0, i);
        all = all.substring(i + 1);
      } else {
        sql = all;
        all = "";
      }

      if (sql.startsWith("--#")) {
        max = Integer.parseInt(sql.substring(3));

        continue;
      } else if (sql.startsWith("--")) {
        continue;
      }

      g[2] = sql;

      long l = 0;

      try {
        l = DatabaseManagerCommon.testStatement(sStatement, sql, max);
        total += l;
        g[0] = "" + l;
        g[1] = "" + max;
        g[3] = "";
      } catch (SQLException e) {
        g[0] = g[1] = "n/a";
        g[3] = e.toString();
      }

      gResult.addRow(g);
      System.out.println(l + " ms : " + sql);
    }

    g[0] = "" + total;
    g[1] = "total";
    g[2] = "";

    gResult.addRow(g);

    lTime = System.currentTimeMillis() - lTime;

    updateResult();
  }
  public void actionPerformed(ActionEvent ev) {

    String s = ev.getActionCommand();

    if (s == null) {
      if (ev.getSource() instanceof JMenuItem) {
        JMenuItem i;

        s = ((JMenuItem) ev.getSource()).getText();
      }
    }

    /*
    // button replace by toolbar
            if (s.equals("Execute")) {
                execute();
            } else
    */
    if (s.equals("Exit")) {
      windowClosing(null);
    } else if (s.equals("Transfer")) {
      Transfer.work(null);
    } else if (s.equals("Dump")) {
      Transfer.work(new String[] {"-d"});
    } else if (s.equals("Restore")) {
      Transfer.work(new String[] {"-r"});
    } else if (s.equals("Logging on")) {
      javaSystem.setLogToSystem(true);
    } else if (s.equals("Logging off")) {
      javaSystem.setLogToSystem(false);
    } else if (s.equals("Refresh Tree")) {
      refreshTree();
    } else if (s.startsWith("#")) {
      int i = Integer.parseInt(s.substring(1));

      txtCommand.setText(sRecent[i]);
    } else if (s.equals("Connect...")) {
      connect(ConnectionDialogSwing.createConnection(fMain, "Connect"));
      refreshTree();
    } else if (s.equals("Results in Grid")) {
      iResult = 0;

      pResult.removeAll();
      pResult.add(gScrollPane, BorderLayout.CENTER);
      pResult.doLayout();
      gResult.fireTableChanged(null);
      pResult.repaint();
    } else if (s.equals("Open Script...")) {
      JFileChooser f = new JFileChooser(".");

      f.setDialogTitle("Open Script...");

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setCurrentDirectory(new File(defDirectory));
      }

      int option = f.showOpenDialog(fMain);

      if (option == JFileChooser.APPROVE_OPTION) {
        File file = f.getSelectedFile();

        if (file != null) {
          StringBuffer buf = new StringBuffer();

          ifHuge = DatabaseManagerCommon.readFile(file.getAbsolutePath());

          if (4096 <= ifHuge.length()) {
            buf.append("This huge file cannot be edited. Please execute\n");
            txtCommand.setText(buf.toString());
          } else {
            txtCommand.setText(ifHuge);
          }
        }
      }
    } else if (s.equals("Save Script...")) {
      JFileChooser f = new JFileChooser(".");

      f.setDialogTitle("Save Script");

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setCurrentDirectory(new File(defDirectory));
      }

      int option = f.showSaveDialog(fMain);

      if (option == JFileChooser.APPROVE_OPTION) {
        File file = f.getSelectedFile();

        if (file != null) {
          DatabaseManagerCommon.writeFile(file.getAbsolutePath(), txtCommand.getText());
        }
      }
    } else if (s.equals("Save Result...")) {
      JFileChooser f = new JFileChooser(".");

      f.setDialogTitle("Save Result...");

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setCurrentDirectory(new File(defDirectory));
      }

      int option = f.showSaveDialog(fMain);

      if (option == JFileChooser.APPROVE_OPTION) {
        File file = f.getSelectedFile();

        if (file != null) {
          showResultInText();
          DatabaseManagerCommon.writeFile(file.getAbsolutePath(), txtResult.getText());
        }
      }
    } else if (s.equals("Results in Text")) {
      iResult = 1;

      pResult.removeAll();
      pResult.add(txtResultScroll, BorderLayout.CENTER);
      pResult.doLayout();
      showResultInText();
      pResult.repaint();
    } else if (s.equals("AutoCommit on")) {
      try {
        cConn.setAutoCommit(true);
      } catch (SQLException e) {
      }
    } else if (s.equals("AutoCommit off")) {
      try {
        cConn.setAutoCommit(false);
      } catch (SQLException e) {
      }
    } else if (s.equals("Commit")) {
      try {
        cConn.commit();
      } catch (SQLException e) {
      }
    } else if (s.equals("Insert test data")) {
      insertTestData();
    } else if (s.equals("Rollback")) {
      try {
        cConn.rollback();
      } catch (SQLException e) {
      }
    } else if (s.equals("Disable MaxRows")) {
      try {
        sStatement.setMaxRows(0);
      } catch (SQLException e) {
      }
    } else if (s.equals("Set MaxRows to 100")) {
      try {
        sStatement.setMaxRows(100);
      } catch (SQLException e) {
      }
    } else if (s.equals("SELECT")) {
      showHelp(DatabaseManagerCommon.selectHelp);
    } else if (s.equals("INSERT")) {
      showHelp(DatabaseManagerCommon.insertHelp);
    } else if (s.equals("UPDATE")) {
      showHelp(DatabaseManagerCommon.updateHelp);
    } else if (s.equals("DELETE")) {
      showHelp(DatabaseManagerCommon.deleteHelp);
    } else if (s.equals("CREATE TABLE")) {
      showHelp(DatabaseManagerCommon.createTableHelp);
    } else if (s.equals("DROP TABLE")) {
      showHelp(DatabaseManagerCommon.dropTableHelp);
    } else if (s.equals("CREATE INDEX")) {
      showHelp(DatabaseManagerCommon.createIndexHelp);
    } else if (s.equals("DROP INDEX")) {
      showHelp(DatabaseManagerCommon.dropIndexHelp);
    } else if (s.equals("CHECKPOINT")) {
      showHelp(DatabaseManagerCommon.checkpointHelp);
    } else if (s.equals("SCRIPT")) {
      showHelp(DatabaseManagerCommon.scriptHelp);
    } else if (s.equals("SHUTDOWN")) {
      showHelp(DatabaseManagerCommon.shutdownHelp);
    } else if (s.equals("SET")) {
      showHelp(DatabaseManagerCommon.setHelp);
    } else if (s.equals("Test Script")) {
      showHelp(DatabaseManagerCommon.testHelp);
    }
  }
  void main() {

    CommonSwing.setDefaultColor();

    fMain = new JFrame("HSQL Database Manager");

    // (ulrivo): An actual icon.
    fMain.getContentPane().add(createToolBar(), "North");
    fMain.setIconImage(CommonSwing.getIcon());
    fMain.addWindowListener(this);

    JMenuBar bar = new JMenuBar();

    // used shortcuts: CERGTSIUDOLM
    String fitems[] = {
      "-Connect...", "--", "-Open Script...", "-Save Script...", "-Save Result...", "--", "-Exit"
    };

    addMenu(bar, "File", fitems);

    String vitems[] = {"RRefresh Tree", "--", "GResults in Grid", "TResults in Text"};

    addMenu(bar, "View", vitems);

    String sitems[] = {
      "SSELECT",
      "IINSERT",
      "UUPDATE",
      "DDELETE",
      "---",
      "-CREATE TABLE",
      "-DROP TABLE",
      "-CREATE INDEX",
      "-DROP INDEX",
      "--",
      "-CHECKPOINT",
      "-SCRIPT",
      "-SET",
      "-SHUTDOWN",
      "--",
      "-Test Script"
    };

    addMenu(bar, "Command", sitems);

    mRecent = new JMenu("Recent");

    bar.add(mRecent);

    String soptions[] = {
      "-AutoCommit on",
      "-AutoCommit off",
      "OCommit",
      "LRollback",
      "--",
      "-Disable MaxRows",
      "-Set MaxRows to 100",
      "--",
      "-Logging on",
      "-Logging off",
      "--",
      "-Insert test data"
    };

    addMenu(bar, "Options", soptions);

    String stools[] = {"-Dump", "-Restore", "-Transfer"};

    addMenu(bar, "Tools", stools);
    fMain.setJMenuBar(bar);
    initGUI();

    sRecent = new String[iMaxRecent];

    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension size = fMain.getSize();

    // (ulrivo): full size on screen with less than 640 width
    if (d.width >= 640) {
      fMain.setLocation((d.width - size.width) / 2, (d.height - size.height) / 2);
    } else {
      fMain.setLocation(0, 0);
      fMain.setSize(d);
    }

    fMain.show();

    // (ulrivo): load query from command line
    if (defScript != null) {
      if (defDirectory != null) {
        defScript = defDirectory + File.separator + defScript;
      }

      // if insert stmet is thousands of records...skip showing it
      // as text.  Too huge.
      StringBuffer buf = new StringBuffer();

      ifHuge = DatabaseManagerCommon.readFile(defScript);

      if (4096 <= ifHuge.length()) {
        buf.append("This huge file cannot be edited. Please execute\n");
        txtCommand.setText(buf.toString());
      } else {
        txtCommand.setText(ifHuge);
      }
    }

    txtCommand.requestFocus();
  }