private void logDatabaseInfo() throws ServletException {
   SessionHelper helper = RetsServer.createHelper();
   try {
     Session session = helper.beginSession();
     Connection connection = session.connection();
     DatabaseMetaData metaData = connection.getMetaData();
     LOGGER.info(
         "JDBC Driver info: "
             + metaData.getDriverName()
             + " version "
             + metaData.getDriverVersion());
     LOGGER.info(
         "JDBC DB info: "
             + metaData.getDatabaseProductName()
             + " version "
             + metaData.getDatabaseProductVersion());
   } catch (SQLException e) {
     throw new ServletException("Caught", e);
   } catch (HibernateException e) {
     throw new ServletException("Caught", e);
   } finally {
     try {
       helper.close();
     } catch (HibernateException e) {
       throw new ServletException(e);
     }
   }
 }
  public static void main(String[] args) {
    Connection con = null;
    DatabaseMetaData dbmd = null;

    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url);
      System.out.println(con.toString());
      // Use the database connection somehow.

      dbmd = con.getMetaData();

      System.out.println("\n----------------------------------------------------");
      System.out.println("Database Name    = " + dbmd.getDatabaseProductName());
      System.out.println("Database Version = " + dbmd.getDatabaseProductVersion());
      System.out.println("Driver Name      = " + dbmd.getDriverName());
      System.out.println("Driver Version   = " + dbmd.getDriverVersion());
      System.out.println("Database URL     = " + dbmd.getURL());
      System.out.println("----------------------------------------------------");

    } catch (SQLException se) {
      printSQLException(se);
    } catch (ClassNotFoundException e) {
      System.out.println("JDBC Driver " + driver + " not found in CLASSPATH");
    } finally {
      if (con != null) {
        try {
          con.close();
        } catch (SQLException se) {
          printSQLException(se);
        }
      }
    }
  }
 private void populateMetaData(DataSource dataSource) {
   Connection connection = null;
   try {
     try {
       connection = dataSource.getConnection();
       DatabaseMetaData metaData = connection.getMetaData();
       CommonParameters.set(
           CommonParameters.DATABASE_PRODUCT_NAME, metaData.getDatabaseProductName());
       CommonParameters.set(
           CommonParameters.DATABASE_PRODUCT_VERSION, metaData.getDatabaseProductVersion());
       CommonParameters.set(
           CommonParameters.DATABASE_MINOR_VERSION, metaData.getDatabaseMinorVersion() + EMPTY);
       CommonParameters.set(
           CommonParameters.DATABASE_MAJOR_VERSION, metaData.getDatabaseMajorVersion() + EMPTY);
       CommonParameters.set(CommonParameters.DATABASE_DRIVER_NAME, metaData.getDriverName());
       CommonParameters.set(
           CommonParameters.DATABASE_DRIVER_MINOR_VERSION,
           metaData.getDriverMinorVersion() + EMPTY);
       CommonParameters.set(
           CommonParameters.DATABASE_DRIVER_MAJOR_VERSION,
           metaData.getDriverMajorVersion() + EMPTY);
       CommonParameters.set(
           CommonParameters.DATABASE_CONNECTION_CLASS_NAME,
           connection.getClass().getCanonicalName());
     } finally {
       if (connection != null) {
         connection.close();
       }
     }
   } catch (SQLException e) {
     logger.error(e.getMessage(), e);
   }
 }
 public String getDriverName() throws SQLException {
   {
     try {
       return _meta.getDriverName();
     } catch (SQLException e) {
       handleException(e);
       throw new AssertionError();
     }
   }
 }
Example #5
0
  @Signature
  public Memory getMetaData() throws SQLException {
    ArrayMemory r = new ArrayMemory();
    r.refOfIndex("userName").assign(metaData.getUserName());

    r.refOfIndex("driverName").assign(metaData.getDriverName());
    r.refOfIndex("driverVersion").assign(metaData.getDriverVersion());
    r.refOfIndex("databaseName").assign(metaData.getDatabaseProductName());
    r.refOfIndex("databaseVersion").assign(metaData.getDatabaseProductVersion());

    r.refOfIndex("catalogSeparator").assign(metaData.getCatalogSeparator());
    r.refOfIndex("catalogTerm").assign(metaData.getCatalogTerm());
    r.refOfIndex("schemaTerm").assign(metaData.getSchemaTerm());
    r.refOfIndex("procedureTerm").assign(metaData.getProcedureTerm());
    r.refOfIndex("searchStringEscape").assign(metaData.getSearchStringEscape());

    r.refOfIndex("numericFunctions").assign(metaData.getNumericFunctions());
    r.refOfIndex("stringFunctions").assign(metaData.getStringFunctions());
    r.refOfIndex("timeDateFunctions").assign(metaData.getTimeDateFunctions());
    r.refOfIndex("systemFunctions").assign(metaData.getSystemFunctions());

    r.refOfIndex("defaultTransactionIsolation").assign(metaData.getDefaultTransactionIsolation());
    r.refOfIndex("identifierQuoteString").assign(metaData.getIdentifierQuoteString());

    r.refOfIndex("maxBinaryLiteralLength").assign(metaData.getMaxBinaryLiteralLength());
    r.refOfIndex("maxCatalogNameLength").assign(metaData.getMaxCatalogNameLength());
    r.refOfIndex("maxCharLiteralLength").assign(metaData.getMaxCharLiteralLength());
    r.refOfIndex("maxConnections").assign(metaData.getMaxConnections());

    r.refOfIndex("maxColumnNameLength").assign(metaData.getMaxColumnNameLength());
    r.refOfIndex("maxColumnsInGroupBy").assign(metaData.getMaxColumnsInGroupBy());
    r.refOfIndex("maxColumnsInIndex").assign(metaData.getMaxColumnsInIndex());
    r.refOfIndex("maxColumnsInOrderBy").assign(metaData.getMaxColumnsInOrderBy());
    r.refOfIndex("maxColumnsInSelect").assign(metaData.getMaxColumnsInSelect());
    r.refOfIndex("maxColumnsInTable").assign(metaData.getMaxColumnsInTable());

    r.refOfIndex("maxCursorNameLength").assign(metaData.getMaxCursorNameLength());
    r.refOfIndex("maxIndexLength").assign(metaData.getMaxIndexLength());
    r.refOfIndex("maxProcedureNameLength").assign(metaData.getMaxProcedureNameLength());
    r.refOfIndex("maxRowSize").assign(metaData.getMaxRowSize());
    r.refOfIndex("maxSchemaNameLength").assign(metaData.getMaxSchemaNameLength());
    r.refOfIndex("maxStatementLength").assign(metaData.getMaxStatementLength());

    r.refOfIndex("maxTableNameLength").assign(metaData.getMaxTableNameLength());
    r.refOfIndex("maxTablesInSelect").assign(metaData.getMaxTablesInSelect());

    return r.toConstant();
  }
  /**
   * This method creates the real connection to database.
   *
   * @param connInfo connection information like url, username and password
   * @return a connection to the database
   * @throws DatabaseConnectionException if the connection cannot be established.
   */
  protected Connection createConnection(Properties connInfo) throws DatabaseConnectionException {
    try {
      // instantiate the Driver class
      try {
        if (connInfo.get("jdbc_class") != null) {
          Class.forName((String) connInfo.get("jdbc_class")).newInstance();
        }
      } catch (Exception e) {
        throw new DatabaseConnectionException(
            "Cannot load driver class " + connInfo.get("jdbc_class"), e);
      }

      Properties connectionInfo = new Properties();
      if (connInfo.get("jdbc_user") != null) {
        connectionInfo.put("user", connInfo.get("jdbc_user"));
      }
      if (connInfo.get("jdbc_pwd") != null) {
        connectionInfo.put("password", connInfo.get("jdbc_pwd"));
      }
      connectionInfo.put("charSet", "UTF-8");

      Connection conn =
          DriverManager.getConnection((String) connInfo.get("jdbc_url"), connectionInfo);

      // enable transaction support
      conn.setAutoCommit(false);
      conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

      DatabaseMetaData meta = conn.getMetaData();
      logger.info(
          "Connected to "
              + connInfo.get("jdbc_url")
              + ": "
              + meta.getDatabaseProductName()
              + " "
              + meta.getDatabaseProductVersion()
              + " with driver "
              + meta.getDriverName()
              + " "
              + meta.getDriverVersion());

      return conn;
    } catch (SQLException e) {
      throw new DatabaseConnectionException(
          "Unable to create a connection to: " + connInfo.get("jdbc_url"), e);
    }
  }
  private void set(DatasourceConnection dc) {
    if (dc != null) {
      datasource = dc.getDatasource();
      try {
        DatabaseMetaData md = dc.getConnection().getMetaData();
        md.getDatabaseProductName();
        setAdditional(KeyImpl.init("DatabaseName"), md.getDatabaseProductName());
        setAdditional(KeyImpl.init("DatabaseVersion"), md.getDatabaseProductVersion());
        setAdditional(KeyImpl.init("DriverName"), md.getDriverName());
        setAdditional(KeyImpl.init("DriverVersion"), md.getDriverVersion());
        // setAdditional("url",md.getURL());

        setAdditional(KeyConstants._Datasource, dc.getDatasource().getName());

      } catch (SQLException e) {
      }
    }
  }
Example #8
0
 public void init(ConnectionFactory cf) throws DAOException {
   Connection conn = cf.getConnection();
   try {
     DatabaseMetaData dbmd = conn.getMetaData();
     this.setDatabaseProductName(dbmd.getDatabaseProductName());
     this.setDatabaseProductVersion(dbmd.getDatabaseProductVersion());
     this.setDriverName(dbmd.getDriverName());
     this.setDriverVersion(dbmd.getDriverVersion());
   } catch (SQLException e) {
     throw (new DAOException(e));
   } finally {
     try {
       conn.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  @Override
  public IDatabaseConnection createConnection(
      final Connection con, final DatabaseMetaData databaseMetaData)
      throws SQLException, DatabaseUnitException {

    logger.warn(
        String.format(
            ">>>>> %s invoked to create a connection!\n", this.getClass().getSimpleName()));

    IDatabaseConnection connection = null;

    // FIXME not nice I found not a fast possibility to generate inside H2
    // the tables inside a
    // schema as oracle do.
    final String driverName = databaseMetaData.getDriverName();

    if (driverName.toLowerCase().contains("oracle")) {
      // oracle schema name is the user name
      connection = new DatabaseConnection(con, databaseMetaData.getUserName().toUpperCase());
    } else {
      if (driverName.contains("H2")) {
        // H2
        connection = new DatabaseConnection(con);
      } else if (driverName.contains("postgresql")) {
        // postgresql
        connection = new DatabaseConnection(con, "public");
      } else {
        // all other
        connection = new DatabaseConnection(con);
      }
    }

    logger.warn(
        String.format(
            "<<<<<  %s returns connection %s!\n", this.getClass().getSimpleName(), connection));

    // final DatabaseConfig config = connection.getConfig();
    // // oracle 10g
    // // FIXME at the moment we have a hard coded oracle notation
    // config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new
    // Oracle10DataTypeFactory());

    return connection;
  }
Example #10
0
  /**
   * Get the RdbmsSpecifics object for a given Connection.
   *
   * @param conn JDBC connection to get RdbmsSpecifics for.
   * @return RdbmsSpecifics for the given connection.
   */
  static RdbmsSpecifics getRdbmsSpecifics(Connection conn) {
    String driverName = "";
    try {
      DatabaseMetaData dbm = conn.getMetaData();
      driverName = dbm.getDriverName();
    } catch (SQLException s) {
      // silently fail
    }

    log.debug("driver name is " + driverName);

    RdbmsSpecifics r = (RdbmsSpecifics) rdbmsSpecifics.get(driverName);

    if (r == null) {
      return defaultRdbmsSpecifics;
    } else {
      return r;
    }
  }
 protected void setupConnectionMetaInfo(Connection conn) throws SQLException {
   try {
     final DfConnectionMetaInfo metaInfo = new DfConnectionMetaInfo();
     final DatabaseMetaData metaData = conn.getMetaData();
     metaInfo.setProductName(metaData.getDatabaseProductName());
     metaInfo.setProductVersion(metaData.getDatabaseProductVersion());
     metaInfo.setDriverName(metaData.getDriverName());
     metaInfo.setDriverVersion(metaData.getDriverVersion());
     final int majorVersion = metaData.getJDBCMajorVersion();
     final int minorVersion = metaData.getJDBCMinorVersion();
     metaInfo.setJdbcVersion(majorVersion + "." + minorVersion);
     _log.info("  product = " + metaInfo.getProductDisp());
     _log.info("  driver  = " + metaInfo.getDriverDisp());
     _connectionMetaInfo = metaInfo;
   } catch (SQLException continued) {
     _log.info("*Failed to get connection meta: " + continued.getMessage());
     _connectionMetaInfo = null;
   }
 }
  @RequestMapping(method = RequestMethod.GET)
  public String showInformations(Model model) {
    List<Informations> info = new ArrayList<>();
    info.add(new Informations("Versão", repInfo.getProperty("repository.version")));
    info.add(new Informations("Número de documentos", Long.toString(docService.count())));

    info.add(
        new Informations(
            "Domínio",
            config.getProperty("Repositorio.hostname"),
            "Este dominio será utilizado para criar a localização dos documentos. Editar no arquivo: 'config.properties'."));
    info.add(
        new Informations(
            "Raiz do projeto", config.getProperty("Repositorio.rootPath", "/repositorio")));
    info.add(
        new Informations(
            "Porta",
            config.getProperty("Repositorio.port", "8080"),
            "Porta informada no arquivo '/WEB-INF/classes/config.properties'"));
    info.add(
        new Informations(
            "URL dos objetos",
            Config.getUrl(config) + "{id}",
            "URL que será utilizada para criar o location dos objetos. Pode ser editada em: '/WEB-INF/classes/config.properties'"));
    try {
      DatabaseMetaData databaseInfo = dataSource.getConnection().getMetaData();
      info.add(new Informations("Base de dados utilizada", databaseInfo.getDatabaseProductName()));
      info.add(
          new Informations("Versão da base de dados", databaseInfo.getDatabaseProductVersion()));
      info.add(new Informations("JDBC driver", databaseInfo.getDriverName()));
      info.add(new Informations("Versão do JDBC driver", databaseInfo.getDriverVersion()));
      info.add(new Informations("URL da base de dados", databaseInfo.getURL()));
      info.add(new Informations("Usuário da base de dados", databaseInfo.getUserName()));

    } catch (SQLException s) {
      log.error("Error getting information about database.", s);
      info.add(new Informations("Erro", "Não foi possível carregar os dados da base de dados"));
    }
    model.addAttribute("info", info);
    return "panel/show";
  }
Example #13
0
 private static Map<PwmAboutProperty, String> getConnectionDebugProperties(
     final Connection connection) {
   if (connection != null) {
     try {
       final Map<PwmAboutProperty, String> returnObj = new LinkedHashMap<>();
       final DatabaseMetaData databaseMetaData = connection.getMetaData();
       returnObj.put(PwmAboutProperty.database_driverName, databaseMetaData.getDriverName());
       returnObj.put(PwmAboutProperty.database_driverVersion, databaseMetaData.getDriverVersion());
       returnObj.put(
           PwmAboutProperty.database_databaseProductName,
           databaseMetaData.getDatabaseProductName());
       returnObj.put(
           PwmAboutProperty.database_databaseProductVersion,
           databaseMetaData.getDatabaseProductVersion());
       return Collections.unmodifiableMap(returnObj);
     } catch (SQLException e) {
       LOGGER.error("error rading jdbc meta data: " + e.getMessage());
     }
   }
   return Collections.emptyMap();
 }
  /** Learn relevant information about this connection source. */
  public void discoverConnectionProperties() {
    Connection connection = null;
    try {
      connection = getConnection();
      if (connection == null) {
        addWarn("Could not get a connection");
        return;
      }
      DatabaseMetaData meta = connection.getMetaData();
      DBUtil util = new DBUtil();
      util.setContext(getContext());
      supportsGetGeneratedKeys = util.supportsGetGeneratedKeys(meta);
      supportsBatchUpdates = util.supportsBatchUpdates(meta);
      dialectCode = DBUtil.discoverSQLDialect(meta);
      addInfo("Driver name=" + meta.getDriverName());
      addInfo("Driver version=" + meta.getDriverVersion());
      addInfo("supportsGetGeneratedKeys=" + supportsGetGeneratedKeys);

    } catch (SQLException se) {
      addWarn("Could not discover the dialect to use.", se);
    } finally {
      DBHelper.closeConnection(connection);
    }
  }
  /** Method declaration */
  private void refreshTree() {

    tTree.removeAll();

    try {
      int color_table = Color.yellow.getRGB();
      int color_column = Color.orange.getRGB();
      int color_index = Color.red.getRGB();

      tTree.addRow("", dMeta.getURL(), "-", 0);

      String usertables[] = {"TABLE"};
      ResultSet result = dMeta.getTables(null, null, null, usertables);
      Vector tables = new Vector();

      // sqlbob@users Added remarks.
      Vector remarks = new Vector();

      while (result.next()) {
        tables.addElement(result.getString(3));
        remarks.addElement(result.getString(5));
      }

      result.close();

      for (int i = 0; i < tables.size(); i++) {
        String name = (String) tables.elementAt(i);
        String key = "tab-" + name + "-";

        tTree.addRow(key, name, "+", color_table);

        // sqlbob@users Added remarks.
        String remark = (String) remarks.elementAt(i);

        if ((remark != null) && !remark.trim().equals("")) {
          tTree.addRow(key + "r", " " + remark);
        }

        ResultSet col = dMeta.getColumns(null, null, name, null);

        while (col.next()) {
          String c = col.getString(4);
          String k1 = key + "col-" + c + "-";

          tTree.addRow(k1, c, "+", color_column);

          String type = col.getString(6);

          tTree.addRow(k1 + "t", "Type: " + type);

          boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls;

          tTree.addRow(k1 + "n", "Nullable: " + nullable);
        }

        col.close();
        tTree.addRow(key + "ind", "Indices", "+", 0);

        ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false);
        String oldiname = null;

        while (ind.next()) {
          boolean nonunique = ind.getBoolean(4);
          String iname = ind.getString(6);
          String k2 = key + "ind-" + iname + "-";

          if ((oldiname == null || !oldiname.equals(iname))) {
            tTree.addRow(k2, iname, "+", color_index);
            tTree.addRow(k2 + "u", "Unique: " + !nonunique);

            oldiname = iname;
          }

          String c = ind.getString(9);

          tTree.addRow(k2 + "c-" + c + "-", c);
        }

        ind.close();
      }

      tTree.addRow("p", "Properties", "+", 0);
      tTree.addRow("pu", "User: "******"pr", "ReadOnly: " + cConn.isReadOnly());
      tTree.addRow("pa", "AutoCommit: " + cConn.getAutoCommit());
      tTree.addRow("pd", "Driver: " + dMeta.getDriverName());
      tTree.addRow("pp", "Product: " + dMeta.getDatabaseProductName());
      tTree.addRow("pv", "Version: " + dMeta.getDatabaseProductVersion());
    } catch (SQLException e) {
      tTree.addRow("", "Error getting metadata:", "-", 0);
      tTree.addRow("-", e.getMessage());
      tTree.addRow("-", e.getSQLState());
    }

    tTree.update();
  }
Example #16
0
  public void init() throws ServletException {
    super.init();

    ARE.getLog()
        .info(
            "**********************************InitDataServlet Start*********************************");
    try {
      ARE.getLog()
          .info(
              "**============System  Property Begin==============================================**");
      Properties ps = System.getProperties();
      Iterator ir = ps.keySet().iterator();
      for (int i = 1; ir.hasNext(); i++) {
        String sKey = (String) ir.next();
        ARE.getLog().info("(" + i + ")" + sKey + " = [" + ps.getProperty(sKey) + "]");
      }
      ARE.getLog()
          .info(
              "**============System  Property End=================================================**");

      Transaction Sqlca = null;
      try {
        String sConfigFile = getInitParameter("ConfigFile");
        if ((sConfigFile != null) && (!"".equals(sConfigFile))) {
          ASConfigure.setXMLFile(sConfigFile);
          ARE.getLog().info("ConfigFile       = [" + sConfigFile + "]");
        }

        ASConfigure asc = ASConfigure.getASConfigure(getServletContext());
        Sqlca = getSqlca(asc);
        ARE.getLog()
            .info(
                "**============DataBase And JDBC Property Begin=====================================**");
        DatabaseMetaData dbmd = Sqlca.conn.getMetaData();
        ARE.getLog()
            .info(
                "DatabaseName["
                    + dbmd.getDatabaseProductName()
                    + "]  Version["
                    + dbmd.getDatabaseProductVersion()
                    + "]");
        ARE.getLog()
            .info(
                "Driver Name["
                    + dbmd.getDriverName()
                    + "]  Version["
                    + dbmd.getDriverVersion()
                    + "]");
        ARE.getLog()
            .info(
                "JDBC MajorVersion["
                    + dbmd.getJDBCMajorVersion()
                    + "] MinorVersion["
                    + dbmd.getJDBCMinorVersion()
                    + "]");
        ARE.getLog().info("URL[" + dbmd.getURL() + "] UserName[" + dbmd.getUserName() + "]");
        ARE.getLog()
            .info(
                "DatabaseState IsAutoCommit["
                    + Sqlca.conn.getAutoCommit()
                    + "] TransactionIsolation["
                    + Sqlca.conn.getTransactionIsolation()
                    + "]");
        ARE.getLog()
            .info(
                "**============DataBase And JDBC Property End=======================================**");

        ARE.getLog()
            .info("Init Cache Data[ALL]            .......... Starting" + StringFunction.getNow());
        ASConfigure.getSysConfig("ASCodeSet", Sqlca);
        ARE.getLog()
            .info("Init Cache Data[SYSCONFIG_CODE] .......... Success!" + StringFunction.getNow());
        ASConfigure.getSysConfig("ASCompSet", Sqlca);
        ARE.getLog()
            .info("Init Cache Data[SYSCONFIG_COMP] .......... Success!" + StringFunction.getNow());
        ASConfigure.getSysConfig("ASFuncSet", Sqlca);
        ARE.getLog()
            .info("Init Cache Data[SYSCONFIG_FUNC] .......... Success!" + StringFunction.getNow());
        ASConfigure.getSysConfig("ASRoleSet", Sqlca);
        ARE.getLog()
            .info("Init Cache Data[SYSCONFIG_ROLE] .......... Success!" + StringFunction.getNow());
        ARE.getLog()
            .info("Init Cache Data[ALL]            .......... Success!" + StringFunction.getNow());
      } catch (Exception e) {
        ARE.getLog().info("InitDataServerlet :error", e);
        e.printStackTrace();
        throw new RuntimeException("构造系统配置时出错:" + e);
      } finally {
        try {
          if (Sqlca != null) {
            Sqlca.conn.commit();
            Sqlca.disConnect();
            Sqlca = null;
          }
        } catch (Exception e1) {
        }
      }
    } catch (Exception e) {
      ARE.getLog().info("InitDataServerlet :error", e);
      e.printStackTrace();
    }
    ARE.getLog()
        .info(
            "**********************************InitDataServlet Success*********************************");
    ARE.getLog().info("");
  }
Example #17
0
  public void actionPerformed(ActionEvent e) {
    switch (pos) {
      case 0:
        try {
          btnNext.setEnabled(false);
          btnPrev.setEnabled(true);

          Class.forName(pnlDStarget.getDriver());
          dbConnTarget =
              DriverManager.getConnection(
                  pnlDStarget.getUrl(), pnlDStarget.getUser(), pnlDStarget.getPasswd());

          cardL.show(pnlContent, "DS_TARGET_MSG");
          DatabaseMetaData dbMeta = dbConnTarget.getMetaData();

          jtaMsgTarget.setText(null);
          jtaMsgTarget.append(
              "Connected to "
                  + dbMeta.getDatabaseProductName()
                  + " version "
                  + dbMeta.getDatabaseProductVersion()
                  + "\r\n");
          jtaMsgTarget.append(
              "Using driver "
                  + dbMeta.getDriverName()
                  + " version "
                  + dbMeta.getDriverVersion()
                  + "\r\n");
          jtaMsgTarget.append("Catalog term is " + dbMeta.getCatalogTerm() + "\r\n");
          jtaMsgTarget.append("Schema term is " + dbMeta.getSchemaTerm() + "\r\n");
          jtaMsgTarget.append("Connection to datasource successfully!");
          btnNext.setEnabled(true);
          btnPrev.setEnabled(true);
        } catch (SQLException ex) {
          ex.printStackTrace();
          return;
        } catch (ClassNotFoundException ex) {
          ex.printStackTrace();
          return;
        }
        pos++;
        break;

      case 1:
        if (e.getActionCommand().equals("NEXT")) {
          cardL.show(pnlContent, "DB_OPEN_FILE");
          pos++;
        } else {

        }
        break;

      case 2:
        if (e.getActionCommand().equals("NEXT")) {
          backupDiffLoader = new BackupLoaderPanel(rlp.getFileName());
          pnlContent.add(backupDiffLoader, "DB_BACKUP_LOADER");
          cardL.show(pnlContent, "DB_BACKUP_LOADER");
          pos++;
          backupDiffLoader.actionPerformed(null);
        } else {

        }
        break;

      case 3:
        if (e.getActionCommand().equals("NEXT")) {
          structDiffWriter =
              new StructDiffWriterPanel(dbConnTarget, backupDiffLoader.getDiffStmtList());
          pnlContent.add(structDiffWriter, "DB_STRUCT_DIFF");
          cardL.show(pnlContent, "DB_STRUCT_DIFF");
          pos++;
          structDiffWriter.actionPerformed(null);
        } else {

        }
        break;

      case 4:
        if (e.getActionCommand().equals("NEXT")) {
          dbPanelTarget = new DBTreeBuilderPanel(dbConnTarget, null, "public");
          pnlContent.add(dbPanelTarget, "DB_BUILDER_TARGET");
          cardL.show(pnlContent, "DB_BUILDER_TARGET");
          pos++;
          dbPanelTarget.actionPerformed(null);
        } else {

        }
        break;

      case 5:
        if (e.getActionCommand().equals("NEXT")) {
          DataDiffWriterPanel dataDiffWriter =
              new DataDiffWriterPanel(
                  dbConnTarget,
                  dbPanelTarget.getTableList(),
                  backupDiffLoader.getDbIncrementalData());
          pnlContent.add(dataDiffWriter, "DB_DATA_DIFF");
          cardL.show(pnlContent, "DB_DATA_DIFF");
          pos++;
          dataDiffWriter.actionPerformed(null);
        } else {

        }
        dbPanelTarget.getTableList();
        break;
    }
  }
  public void testMetaData() {

    String ddl0 =
        "DROP TABLE ADDRESSBOOK IF EXISTS; DROP TABLE ADDRESSBOOK_CATEGORY IF EXISTS; DROP TABLE USER IF EXISTS;";
    String ddl1 =
        "CREATE TABLE USER(USER_ID INTEGER NOT NULL PRIMARY KEY,LOGIN_ID VARCHAR(128) NOT NULL,USER_NAME VARCHAR(254) DEFAULT ' ' NOT NULL,CREATE_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,UPDATE_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,LAST_ACCESS_DATE TIMESTAMP,CONSTRAINT IXUQ_LOGIN_ID0 UNIQUE(LOGIN_ID))";
    String ddl2 =
        "CREATE TABLE ADDRESSBOOK_CATEGORY(USER_ID INTEGER NOT NULL,CATEGORY_ID INTEGER DEFAULT 0 NOT NULL,CATEGORY_NAME VARCHAR(60) DEFAULT '' NOT NULL,CONSTRAINT SYS_PK_ADDRESSBOOK_CATEGORY PRIMARY KEY(USER_ID,CATEGORY_ID),CONSTRAINT FK_ADRBKCAT1 FOREIGN KEY(USER_ID) REFERENCES USER(USER_ID) ON DELETE CASCADE)";
    String ddl3 =
        "CREATE TABLE ADDRESSBOOK(USER_ID INTEGER NOT NULL,ADDRESSBOOK_ID INTEGER NOT NULL,CATEGORY_ID INTEGER DEFAULT 0 NOT NULL,FIRST VARCHAR(64) DEFAULT '' NOT NULL,LAST VARCHAR(64) DEFAULT '' NOT NULL,NOTE VARCHAR(128) DEFAULT '' NOT NULL,CONSTRAINT SYS_PK_ADDRESSBOOK PRIMARY KEY(USER_ID,ADDRESSBOOK_ID),CONSTRAINT FK_ADRBOOK1 FOREIGN KEY(USER_ID,CATEGORY_ID) REFERENCES ADDRESSBOOK_CATEGORY(USER_ID,CATEGORY_ID) ON DELETE CASCADE)";
    String result1 = "1";
    String result2 = "2";
    String result3 = "3";
    String result4 = "4";
    String result5 = "5";

    try {
      stmnt.execute(ddl0);
      stmnt.execute(ddl1);
      stmnt.execute(ddl2);
      stmnt.execute(ddl3);

      DatabaseMetaData md = connection.getMetaData();

      {
        System.out.println("Testing DatabaseMetaData methods");
        System.out.println(md.getDatabaseMajorVersion());
        System.out.println(md.getDatabaseMinorVersion());
        System.out.println(md.getDatabaseProductName());
        System.out.println(md.getDatabaseProductVersion());
        System.out.println(md.getDefaultTransactionIsolation());
        System.out.println(md.getDriverMajorVersion());
        System.out.println(md.getDriverMinorVersion());
        System.out.println(md.getDriverName());
        System.out.println(md.getDriverVersion());
        System.out.println(md.getExtraNameCharacters());
        System.out.println(md.getIdentifierQuoteString());
        System.out.println(md.getJDBCMajorVersion());
        System.out.println(md.getJDBCMinorVersion());
        System.out.println(md.getMaxBinaryLiteralLength());
        System.out.println(md.getMaxCatalogNameLength());
        System.out.println(md.getMaxColumnsInGroupBy());
        System.out.println(md.getMaxColumnsInIndex());
        System.out.println(md.getMaxColumnsInOrderBy());
        System.out.println(md.getMaxColumnsInSelect());
        System.out.println(md.getMaxColumnsInTable());
        System.out.println(md.getMaxConnections());
        System.out.println(md.getMaxCursorNameLength());
        System.out.println(md.getMaxIndexLength());
        System.out.println(md.getMaxProcedureNameLength());
        System.out.println(md.getMaxRowSize());
        System.out.println(md.getMaxSchemaNameLength());
        System.out.println(md.getMaxStatementLength());
        System.out.println(md.getMaxStatements());
        System.out.println(md.getMaxTableNameLength());
        System.out.println(md.getMaxUserNameLength());
        System.out.println(md.getNumericFunctions());
        System.out.println(md.getProcedureTerm());
        System.out.println(md.getResultSetHoldability());
        System.out.println(md.getSchemaTerm());
        System.out.println(md.getSearchStringEscape());
        System.out.println("Testing DatabaseMetaData.getSQLKeywords()");
        System.out.println(md.getSQLKeywords());
        System.out.println(md.getSQLStateType());
        System.out.println("Testing DatabaseMetaData.getStringFunctions()");
        System.out.println(md.getStringFunctions());
        System.out.println("Testing DatabaseMetaData.getSystemFunctions()");
        System.out.println(md.getSystemFunctions());
        System.out.println("Testing DatabaseMetaData.getTimeDateFunctions()");
        System.out.println(md.getTimeDateFunctions());
        System.out.println(md.getURL());
        System.out.println(md.getUserName());
        System.out.println(DatabaseMetaData.importedKeyCascade);
        System.out.println(md.isCatalogAtStart());
        System.out.println(md.isReadOnly());

        ResultSet rs;

        rs = md.getPrimaryKeys(null, null, "USER");

        ResultSetMetaData rsmd = rs.getMetaData();
        String result0 = "";

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result0 += rs.getString(i + 1) + ":";
          }

          result0 += "\n";
        }

        rs.close();
        System.out.println(result0);
      }

      {
        ResultSet rs;

        rs = md.getBestRowIdentifier(null, null, "USER", 0, true);

        ResultSetMetaData rsmd = rs.getMetaData();
        String result0 = "";

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result0 += rs.getString(i + 1) + ":";
          }

          result0 += "\n";
        }

        rs.close();
        System.out.println(result0);
      }

      {
        ResultSet rs = md.getImportedKeys(null, null, "ADDRESSBOOK");
        ResultSetMetaData rsmd = rs.getMetaData();

        result1 = "";

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result1 += rs.getString(i + 1) + ":";
          }

          result1 += "\n";
        }

        rs.close();
        System.out.println(result1);
      }

      {
        ResultSet rs =
            md.getCrossReference(null, null, "ADDRESSBOOK_CATEGORY", null, null, "ADDRESSBOOK");
        ResultSetMetaData rsmd = rs.getMetaData();

        result2 = "";

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result2 += rs.getString(i + 1) + ":";
          }

          result2 += "\n";
        }

        rs.close();
        System.out.println(result2);
      }

      {
        ResultSet rs = md.getExportedKeys(null, null, "USER");
        ResultSetMetaData rsmd = rs.getMetaData();

        result3 = "";

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result3 += rs.getString(i + 1) + ":";
          }

          result3 += "\n";
        }

        rs.close();
        System.out.println(result3);
      }

      {
        ResultSet rs = md.getCrossReference(null, null, "USER", null, null, "ADDRESSBOOK_CATEGORY");
        ResultSetMetaData rsmd = rs.getMetaData();

        result4 = "";

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result4 += rs.getString(i + 1) + ":";
          }

          result4 += "\n";
        }

        rs.close();
        System.out.println(result4);
      }

      {
        stmnt.execute("DROP TABLE T IF EXISTS;");
        stmnt.execute("CREATE TABLE T (I IDENTITY, A CHAR(20), B CHAR(20));");
        stmnt.execute("INSERT INTO T VALUES (NULL, 'get_column_name', '" + getColumnName + "');");

        ResultSet rs = stmnt.executeQuery("SELECT I, A, B, A \"aliasA\", B \"aliasB\", 1 FROM T;");
        ResultSetMetaData rsmd = rs.getMetaData();

        result5 = "";

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result5 += rsmd.getColumnName(i + 1) + ":" + rs.getString(i + 1) + ":";
          }

          result5 += "\n";
        }

        rs.close();

        rs = stmnt.executeQuery("SELECT I, A, B, A \"aliasA\", B \"aliasB\", 1 FROM T;");
        rsmd = rs.getMetaData();

        for (; rs.next(); ) {
          for (int i = 0; i < rsmd.getColumnCount(); i++) {
            result5 += rsmd.getColumnLabel(i + 1) + ":" + rs.getString(i + 1) + ":";
          }

          result5 += "\n";
        }

        System.out.println(result5);
        System.out.println("first column identity: " + rsmd.isAutoIncrement(1));
        rsmd.isCaseSensitive(1);
        rsmd.isCurrency(1);
        rsmd.isDefinitelyWritable(1);
        rsmd.isNullable(1);
        rsmd.isReadOnly(1);
        rsmd.isSearchable(1);
        rsmd.isSigned(1);
        rsmd.isWritable(1);
        rs.close();

        // test identity with PreparedStatement
        pstmnt = connection.prepareStatement("INSERT INTO T VALUES (?,?,?)");

        pstmnt.setString(1, null);
        pstmnt.setString(2, "test");
        pstmnt.setString(3, "test2");
        pstmnt.executeUpdate();

        pstmnt = connection.prepareStatement("call identity()");

        ResultSet rsi = pstmnt.executeQuery();

        rsi.next();

        int identity = rsi.getInt(1);

        System.out.println("call identity(): " + identity);
        rsi.close();
      }
    } catch (SQLException e) {
      fail(e.getMessage());
    }

    System.out.println("testMetaData complete");

    // assert equality of exported and imported with xref
    assertEquals(result1, result2);
    assertEquals(result3, result4);
  }
  /* Clear all existing nodes from the tree model and rebuild from scratch.
   */
  protected void refreshTree() {

    DefaultMutableTreeNode propertiesNode;
    DefaultMutableTreeNode leaf;

    // First clear the existing tree by simply enumerating
    // over the root node's children and removing them one by one.
    while (treeModel.getChildCount(rootNode) > 0) {
      DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeModel.getChild(rootNode, 0);

      treeModel.removeNodeFromParent(child);
      child.removeAllChildren();
      child.removeFromParent();
    }

    treeModel.nodeStructureChanged(rootNode);
    treeModel.reload();
    tScrollPane.repaint();

    // Now rebuild the tree below its root
    try {

      // Start by naming the root node from its URL:
      rootNode.setUserObject(dMeta.getURL());

      // get metadata about user tables by building a vector of table names
      String usertables[] = {"TABLE", "GLOBAL TEMPORARY", "VIEW"};
      ResultSet result = dMeta.getTables(null, null, null, usertables);
      Vector tables = new Vector();

      // sqlbob@users Added remarks.
      Vector remarks = new Vector();

      while (result.next()) {
        tables.addElement(result.getString(3));
        remarks.addElement(result.getString(5));
      }

      result.close();

      // For each table, build a tree node with interesting info
      for (int i = 0; i < tables.size(); i++) {
        String name = (String) tables.elementAt(i);
        DefaultMutableTreeNode tableNode = makeNode(name, rootNode);
        ResultSet col = dMeta.getColumns(null, null, name, null);

        // sqlbob@users Added remarks.
        String remark = (String) remarks.elementAt(i);

        if ((remark != null) && !remark.trim().equals("")) {
          makeNode(remark, tableNode);
        }

        // With a child for each column containing pertinent attributes
        while (col.next()) {
          String c = col.getString(4);
          DefaultMutableTreeNode columnNode = makeNode(c, tableNode);
          String type = col.getString(6);

          makeNode("Type: " + type, columnNode);

          boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls;

          makeNode("Nullable: " + nullable, columnNode);
        }

        col.close();

        DefaultMutableTreeNode indexesNode = makeNode("Indices", tableNode);
        ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false);
        String oldiname = null;

        // A child node to contain each index - and its attributes
        while (ind.next()) {
          DefaultMutableTreeNode indexNode = null;
          boolean nonunique = ind.getBoolean(4);
          String iname = ind.getString(6);

          if ((oldiname == null || !oldiname.equals(iname))) {
            indexNode = makeNode(iname, indexesNode);

            makeNode("Unique: " + !nonunique, indexNode);

            oldiname = iname;
          }

          // And the ordered column list for index components
          makeNode(ind.getString(9), indexNode);
        }

        ind.close();
      }

      // Finally - a little additional metadata on this connection
      propertiesNode = makeNode("Properties", rootNode);

      makeNode("User: "******"ReadOnly: " + cConn.isReadOnly(), propertiesNode);
      makeNode("AutoCommit: " + cConn.getAutoCommit(), propertiesNode);
      makeNode("Driver: " + dMeta.getDriverName(), propertiesNode);
      makeNode("Product: " + dMeta.getDatabaseProductName(), propertiesNode);
      makeNode("Version: " + dMeta.getDatabaseProductVersion(), propertiesNode);
    } catch (SQLException se) {
      propertiesNode = makeNode("Error getting metadata:", rootNode);

      makeNode(se.getMessage(), propertiesNode);
      makeNode(se.getSQLState(), propertiesNode);
    }

    treeModel.nodeStructureChanged(rootNode);
    treeModel.reload();
    tScrollPane.repaint();
  }
Example #20
0
    @Override
    public IStatus run(DBRProgressMonitor monitor) {
      if (ownerMonitor != null) {
        monitor = ownerMonitor;
      }
      monitor.beginTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_start, 4);
      Thread.currentThread()
          .setName(CoreMessages.dialog_connection_wizard_start_connection_monitor_thread);

      try {
        container.setName(container.getConnectionConfiguration().getUrl());
        monitor.worked(1);
        long startTime = System.currentTimeMillis();
        super.run(monitor);
        connectTime = (System.currentTimeMillis() - startTime);
        if (connectError != null || monitor.isCanceled()) {
          return Status.OK_STATUS;
        }

        monitor.worked(1);
        DBPDataSource dataSource = container.getDataSource();
        if (dataSource == null) {
          throw new DBException(CoreMessages.editors_sql_status_not_connected_to_database);
        }
        //                monitor.subTask("Initialize connection");
        //                dataSource.initialize(monitor);
        //                monitor.worked(1);
        monitor.subTask(
            CoreMessages.dialog_connection_wizard_start_connection_monitor_subtask_test);

        DBPDataSourceInfo info = dataSource.getInfo();
        if (info != null) {
          try {
            productName = info.getDatabaseProductName();
            productVersion = info.getDatabaseProductVersion();
            driverName = info.getDriverName();
            driverVersion = info.getDriverVersion();
          } catch (Exception e) {
            log.error("Can't obtain connection metadata", e);
          }
        } else {
          try (DBCSession session =
              DBUtils.openUtilSession(monitor, dataSource, "Test connection")) {
            if (session instanceof Connection) {
              try {
                Connection connection = (Connection) session;
                DatabaseMetaData metaData = connection.getMetaData();
                productName = metaData.getDatabaseProductName();
                productVersion = metaData.getDatabaseProductVersion();
                driverName = metaData.getDriverName();
                driverVersion = metaData.getDriverVersion();
              } catch (Exception e) {
                log.error("Can't obtain connection metadata", e);
              }
            }
          }
        }
        new DisconnectJob(container).schedule();
        monitor.subTask(CoreMessages.dialog_connection_wizard_start_connection_monitor_success);
      } catch (DBException ex) {
        connectError = ex;
      }
      monitor.done();
      return Status.OK_STATUS;
    }
  public void doWork(Connection conn) {
    try {
      stmt = conn.createStatement();
      dbma = conn.getMetaData();

      createTableDoc = new DocTableCreate();

      //			System.out.println("Connected to URL : " + dbma.getURL());
      System.out.println("Driver is : " + dbma.getDriverName());

      System.out.println("===================================");

      Map<String, String> titleMap = getXlsxTitleMap("D:\\docTest\\TableList.xlsx", "RC");

      // %是取所有資料表
      tableRs = dbma.getTables(catalog, null, "%", null);

      catalog = conn.getCatalog();
      while (tableRs.next()) {
        // 取得資料表名稱
        String tableName = tableRs.getString("TABLE_NAME");

        System.out.println("Table Name : " + tableName);
        System.out.println("-----Column Names of table [stkid]------");
        // 記錄欄位資訊
        Map<String, String> colMap = TableInfoUtils.getColumns(catalog, dbma, tableName);
        // 記錄主鍵資訊
        Map<String, String> pkeyMap = TableInfoUtils.getPKey(catalog, dbma, tableName);
        // 記錄索引資訊
        IdentityHashMap<String, String> indexMap =
            TableInfoUtils.getTableIndex(catalog, dbma, tableName);

        Iterator indexIter = indexMap.entrySet().iterator();
        // 記錄組合索引資訊
        Map<String, String> indexTemp = new HashMap<String, String>();

        // 組合索引
        while (indexIter.hasNext()) {
          Map.Entry entry = (Map.Entry) indexIter.next();
          String indexCol = entry.getKey().toString();
          String indexName = entry.getValue().toString();
          String tempIdxName = indexTemp.get(indexCol);

          if (tempIdxName == null) {
            indexTemp.put(indexCol, indexName);
          } else {
            tempIdxName = tempIdxName + "," + indexName;
            indexTemp.put(indexCol, tempIdxName);
          }
        }

        //					List<DocOutputModel> models = new ArrayList<DocOutputModel>();

        List<String[]> arrays = new ArrayList<String[]>();

        Iterator colIter = colMap.entrySet().iterator();
        // 索引、欄位組合
        while (colIter.hasNext()) {
          Map.Entry entry = (Map.Entry) colIter.next();
          String key = entry.getKey().toString();
          String value = entry.getValue().toString();

          String index = indexTemp.get(key);

          DocOutputModel model = setModel(index, value);
          System.out.println(TableInfoUtils.nullToSpace(index) + "\t" + value);

          String[] array =
              TableInfoUtils.setArrayModel(
                  index, value, DocOutputModel.class.getDeclaredFields().length);
          arrays.add(array);
          //						models.add(model);
        }

        String docFile = "D:\\docTest" + File.separator + tableName.toUpperCase() + ".doc";

        createTableDoc.createDoc("D:\\docTest\\temp.doc", docFile, arrays, titleMap, tableName);
      }
      //			}
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public String getDriverName() throws SQLException {
   return throwExceptionDelegate.getDriverName();
 }