public void checkTables(consumer<Boolean> consumer) {

    Connection connection = null;
    ResultSet result = null;

    try {

      connection = HikariManager.getInstance().getConnection();

      DatabaseMetaData dbm = connection.getMetaData();

      boolean playersExists = false;
      boolean periodicExists = false;
      boolean allExist = false;

      result = dbm.getTables(null, null, HikariManager.getInstance().prefix + "players", null);
      if (result.next()) playersExists = true;

      result = dbm.getTables(null, null, HikariManager.getInstance().prefix + "periodic", null);
      if (result.next()) periodicExists = true;

      if (playersExists && periodicExists) allExist = true;

      if (consumer != null) consumer.accept(allExist);

    } catch (SQLException e) {

      e.printStackTrace();

    } finally {

      HikariManager.getInstance().close(connection, null, result);
    }
  }
示例#2
0
 private ImmutableMap<String, JdbcTable> computeTables() {
   Connection connection = null;
   ResultSet resultSet = null;
   try {
     connection = dataSource.getConnection();
     DatabaseMetaData metaData = connection.getMetaData();
     resultSet = metaData.getTables(catalog, schema, null, null);
     final ImmutableMap.Builder<String, JdbcTable> builder = ImmutableMap.builder();
     while (resultSet.next()) {
       final String tableName = resultSet.getString(3);
       final String catalogName = resultSet.getString(1);
       final String schemaName = resultSet.getString(2);
       final String tableTypeName = resultSet.getString(4);
       // Clean up table type. In particular, this ensures that 'SYSTEM TABLE',
       // returned by Phoenix among others, maps to TableType.SYSTEM_TABLE.
       // We know enum constants are upper-case without spaces, so we can't
       // make things worse.
       final String tableTypeName2 = tableTypeName.toUpperCase().replace(' ', '_');
       final TableType tableType = Util.enumVal(TableType.class, tableTypeName2);
       final JdbcTable table = new JdbcTable(this, catalogName, schemaName, tableName, tableType);
       builder.put(tableName, table);
     }
     return builder.build();
   } catch (SQLException e) {
     throw new RuntimeException("Exception while reading tables", e);
   } finally {
     close(connection, null, resultSet);
   }
 }
 private List getAllTables(Connection conn) throws SQLException {
   DatabaseMetaData dbMetaData = conn.getMetaData();
   ResultSet rs = dbMetaData.getTables(getCatalog(), getSchema(), null, null);
   List tables = new ArrayList();
   while (rs.next()) {
     tables.add(createTable(conn, rs));
   }
   return tables;
 }
示例#4
0
  public static List<String> getTableNamesList(
      DatabaseMetaData mObject, String dbName, String schema) throws SQLException {
    List<String> tableList = new ArrayList<String>();
    ResultSet tableNamesList = mObject.getTables(dbName, schema, null, null);
    while (tableNamesList.next()) {
      tableList.add(tableNamesList.getString(DBConstants.DataServiceGenerator.TABLE_NAME));
    }

    return tableList;
  }
  private Table _getTable(String catalog, String schema, String tableName) throws SQLException {
    if (tableName == null || tableName.trim().length() == 0)
      throw new IllegalArgumentException("tableName must be not empty");
    catalog = StringHelper.defaultIfEmpty(catalog, null);
    schema = StringHelper.defaultIfEmpty(schema, null);

    Connection conn = getConnection();
    DatabaseMetaData dbMetaData = conn.getMetaData();
    ResultSet rs = dbMetaData.getTables(catalog, schema, tableName, null);
    while (rs.next()) {
      Table table = createTable(conn, rs);
      return table;
    }
    return null;
  }
示例#6
0
  // UTILITY
  public boolean hasTable(String tableName) {

    try {
      DatabaseMetaData dbm = connection.getMetaData();
      ResultSet tables = dbm.getTables(null, null, tableName, null);
      while (tables.next()) {
        String foundName = tables.getString("TABLE_NAME");
        if (tableName.equals(foundName)) {
          return true;
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return false;
  }
示例#7
0
  boolean tiene_tablas() {
    DatabaseMetaData dbmd = null;
    Integer contador = 0;
    try {
      dbmd = conexion.getMetaData();
      String[] tipo = {"TABLE"};
      ResultSet rs = dbmd.getTables(null, null, "%", tipo);
      while (rs.next()) {
        contador++;
      }
    } catch (SQLException e) {
      System.out.println("Error al obtener información de la bd...");
    }

    return contador > 0;
  }
示例#8
0
  @Override
  public ArrayList<String> getListOfTables(Connection conn)
      throws SQLException, ClassNotFoundException {

    ArrayList<String> tableNames = new ArrayList<String>();
    DatabaseMetaData dmd = conn.getMetaData();
    // Pedro: 2012/12/03 comment out to enable loading Views in Karma (on behalf of Maria)
    // ResultSet rs = dmd.getTables(null, null, null, new String[] {"TABLE"});
    ResultSet rs = dmd.getTables(null, null, null, new String[] {"TABLE", "VIEW"});
    while (rs.next()) {
      String tablename = rs.getString(3);
      String schema = rs.getString(2);
      if (schema != null && schema.length() > 0) tableNames.add(schema + "." + tablename);
      else tableNames.add(tablename);
    }
    Collections.sort(tableNames);
    return tableNames;
  }
 private Connection createDatasource() throws ClassNotFoundException, SQLException {
   Connection connection = getConnection();
   boolean exist = false;
   int tableNameColumn = 3;
   DatabaseMetaData dbm = connection.getMetaData();
   for (ResultSet rs = dbm.getTables(null, null, null, null); rs.next(); ) {
     if (rs.getString(tableNameColumn).equals(TABLE_NAME)) {
       exist = true;
       rs.close();
       break;
     }
   }
   if (!exist) {
     Statement statement = connection.createStatement();
     statement.executeUpdate(
         "CREATE TABLE " + TABLE_NAME + " (name VARCHAR(32) PRIMARY KEY, balance FLOAT)");
   }
   return connection;
 }
示例#10
0
  public static void main(String args[]) {
    try {
      Class.forName("org.gjt.mm.mysql.Driver");

      Connection con =
          DriverManager.getConnection("jdbc:mysql://localhost:3333/world", "root", "root");

      DatabaseMetaData dbmd = con.getMetaData();
      String table[] = {"TABLE"};
      ResultSet rs = dbmd.getTables(null, null, null, table);

      while (rs.next()) {
        System.out.println(rs.getString(3));
      }

      con.close();

    } catch (Exception e) {
      System.out.println(e);
    }
  }
示例#11
0
  public Map<String, List<String>> querySchema(DBConfig config) {
    Map<String, List<String>> map = new HashMap<String, List<String>>();
    List<String> schemaList = config.getSchemaList();
    Connection conn = null;
    DatabaseMetaData databaseMetaData = null;
    try {
      conn = ConnectionFactory.getInstance().getConnection(config);
      databaseMetaData = conn.getMetaData();
    } catch (Exception e) {
      e.printStackTrace();
      return map;
    }

    for (String schema : schemaList) {
      List<String> tableList = new ArrayList<String>();
      try {
        String localSchema = schema;
        if (databaseMetaData.storesLowerCaseIdentifiers()) {
          localSchema = localSchema == null ? null : localSchema.toLowerCase();
        } else if (databaseMetaData.storesUpperCaseIdentifiers()) {
          localSchema = localSchema == null ? null : localSchema.toUpperCase();
        }

        ResultSet rs = databaseMetaData.getTables(null, localSchema, null, null);
        while (rs.next()) {
          String tableName = rs.getString("TABLE_NAME");
          tableList.add(tableName);
          // System.out.println(tableName);
        }
        map.put(schema, tableList);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return map;
  }
  /** 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();
  }
示例#13
0
  /**
   * Each table description has the following columns:
   *
   * <p>TABLE_CAT String => table catalog (may be null) TABLE_SCHEM String => table schema (may be
   * null) TABLE_NAME String => table name TABLE_TYPE String => table type. Typical types are
   * "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
   * REMARKS String => explanatory comment on the table TYPE_CAT String => the types catalog (may be
   * null) TYPE_SCHEM String => the types schema (may be null) TYPE_NAME String => type name (may be
   * null) SELF_REFERENCING_COL_NAME String => name of the designated "identifier" column of a typed
   * table (may be null) REF_GENERATION String => specifies how values in SELF_REFERENCING_COL_NAME
   * are created. Values are "SYSTEM", "USER", "DERIVED". (may be null)
   */
  public ResultSet getTables(Connection conn) throws SQLException {
    DatabaseMetaData md = conn.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", new String[] {"TABLE"});

    return rs;
  }
  public static void main(String args[]) {

    Connection connection = null;
    SQLMXJdbcRowSet jrs = null;
    Statement stmt = null;
    ResultSet rs = null;
    DatabaseMetaData dbMeta = null;
    ResultSetMetaData rsMD = null;
    int rowNo;

    try {
      Class.forName("org.trafodion.jdbc.t2.T2Driver");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
      return;
    }
    try {
      String url = "jdbc:t2jdbc:";
      connection = DriverManager.getConnection(url);
      stmt = connection.createStatement();
      try {
        stmt.executeUpdate("drop table jdbcrsdemo");
      } catch (SQLException e) {
      }
      stmt.executeUpdate(
          "create table jdbcrsdemo (c1 char(20), c2 smallint, c3 integer, c4 largeint, c5 varchar(120), c6 numeric(10,2), c7 decimal(10,2),c8 date, c9 time, c10 timestamp, c11 float, c12 double precision)");
      stmt.executeUpdate(
          "insert into jdbcrsdemo values('Doberman Pinscher', 100, 12345678, 123456789012, 'Canine', 100.12, 100.12, {d '2005-12-23'}, {t '10:11:12'}, {ts '2000-12-23 10:11:12'}, 100.12, 100.12)");
      stmt.executeUpdate(
          "insert into jdbcrsdemo values('Rottweiler', 150, -12345678, -123456789012, 'Canine', -100.12, -100.12, {d '2005-12-24'}, {t '10:11:12'}, {ts '2005-12-24 10:11:12'}, -100.12, -100.12)");
      stmt.executeUpdate(
          "insert into jdbcrsdemo values('Tiger', 101, -12345678, 123456789012, 'Feline', -100.12, 100.12, {d '2005-12-25'}, {t '10:11:12'}, {ts '2005-12-25 10:11:12.0'}, -100.12, 100.12)");

      System.out.println("Creating JdbcRowSet");
      jrs = new SQLMXJdbcRowSet();
      jrs.setUrl(url);

      for (int i = 0; i < 5; i++) {
        switch (i) {
          case 0:
            System.out.println("");
            System.out.println("Simple Select ");
            jrs.setCommand("select * from jdbcrsdemo");
            jrs.execute();
            break;
          case 1:
            System.out.println("");
            System.out.println("Parameterized Select - CHAR");
            jrs.setCommand("select c1, c2 from jdbcrsdemo where c1 = ?");
            jrs.setString(1, "Rottweiler");
            jrs.execute();
            break;
          case 2:
            System.out.println("");
            System.out.println("Parameterized Select - INT");
            jrs.setCommand("select c1, c2, c3 from jdbcrsdemo where c2 = ?  or c2 = ?");
            jrs.setInt(1, 100);
            jrs.setInt(2, 150);
            jrs.execute();
            break;
          case 3:
            System.out.println("");
            System.out.println("Parameterized Select - TIMESTAMP");
            jrs.setCommand("select c1, c2, c3, c10 from jdbcrsdemo where c10 = ?");
            jrs.setTimestamp(1, Timestamp.valueOf("2005-12-25 10:11:12.0"));
            jrs.execute();
            break;
          case 4:
            System.out.println("");
            System.out.println("Parameterized Select - DECIMAL");
            jrs.setCommand("select c1, c2, c3, c7 from jdbcrsdemo where c7 = ? or c7 = ?");
            jrs.setBigDecimal(1, new BigDecimal("100.12"));
            jrs.setBigDecimal(2, new BigDecimal("-100.12"));
            jrs.execute();
            break;
        }
        rsMD = jrs.getMetaData();
        System.out.println("");
        System.out.println("Printing JdbcRowSet ResultSetMetaData ...");
        System.out.println("No. of Columns " + rsMD.getColumnCount());
        for (int j = 1; j <= rsMD.getColumnCount(); j++) {
          System.out.println(
              "Column "
                  + j
                  + " Data Type: "
                  + rsMD.getColumnTypeName(j)
                  + " Name: "
                  + rsMD.getColumnName(j));
        }
        System.out.println("");
        System.out.println("Fetching JdbcRowSet rows...");
        rowNo = 0;
        while (jrs.next()) {
          rowNo++;
          System.out.println("");
          System.out.println("Printing Row " + rowNo + " using getString(), getObject()");
          for (int j = 1; j <= rsMD.getColumnCount(); j++) {
            System.out.println("Column " + j + " - " + jrs.getString(j) + "," + jrs.getObject(j));
          }
        }
        System.out.println("");
      }

      System.out.println("Calling JdbcRowSet.getDatabaseMetaData()");
      dbMeta = jrs.getDatabaseMetaData();

      for (int k = 0; k < 4; k++) {
        switch (k) {
          case 0:
            System.out.println("");
            System.out.println("getTypeInfo() ");
            rs = dbMeta.getTypeInfo();
            break;
          case 1:
            System.out.println("");
            System.out.println("getCatalogs()");
            rs = dbMeta.getCatalogs();
            break;
          case 2:
            System.out.println("");
            System.out.println("getTables() ");
            rs = dbMeta.getTables(null, null, "JDB%", null);
            break;
          case 3:
            System.out.println("");
            System.out.println("getColumns()");
            rs = dbMeta.getColumns(null, null, "JDBCRSDEMO", "%");
            break;
          default:
            rs = null;
            continue;
        }

        if (rs != null) {
          rsMD = rs.getMetaData();
          System.out.println("");

          System.out.println("Printing ResultSetMetaData ...");
          System.out.println("No. of Columns " + rsMD.getColumnCount());
          for (int j = 1; j <= rsMD.getColumnCount(); j++) {
            System.out.println(
                "Column "
                    + j
                    + " Data Type: "
                    + rsMD.getColumnTypeName(j)
                    + " Name: "
                    + rsMD.getColumnName(j));
          }
          System.out.println("");
          System.out.println("Fetching resultSet rows...");
          rowNo = 0;
          while (rs.next()) {
            rowNo++;
            System.out.println("");
            System.out.println("Printing Row " + rowNo + " using getString(), getObject()");
            for (int j = 1; j <= rsMD.getColumnCount(); j++) {
              System.out.println("Column " + j + " - " + rs.getString(j) + "," + rs.getObject(j));
            }
          }
        }
        System.out.println("");
        System.out.println("End of Data");
        if (rs != null) rs.close();
      }
      System.out.println("Demo Completed");
    } catch (SQLException e) {
      SQLException nextException;

      nextException = e;
      do {
        System.out.println(nextException.getMessage());
        System.out.println("SQLState   " + nextException.getSQLState());
        System.out.println("Error Code " + nextException.getErrorCode());
      } while ((nextException = nextException.getNextException()) != null);
    } finally {
      try {
        if (connection != null) connection.close();
        if (jrs != null) jrs.close();
      } catch (SQLException sqle) {
        sqle.printStackTrace();
        System.out.println(sqle.getMessage());
      }
    }
  }
示例#15
0
  public static void main(String arg[]) {
    Hashtable ignoreList = new Hashtable();
    Class cl = null;
    Model model = null;
    System.out.println("Synchronizing forms with database...");
    Db.init();

    try {
      DatabaseMetaData meta = Db.getCon().getMetaData();
      String[] types = {"TABLE"};
      ResultSet rs = meta.getTables(null, null, "%", types);

      // read ignore.list
      ignoreList = AutogenerateUtil.readIgnoreList();
      // prepare directory
      File fDir = new File("../../web/WEB-INF/views/crud_form");
      if (!fDir.exists()) fDir.mkdir();
      while (rs.next()) {
        // proper file name generationm
        String className = "";
        String tableName = rs.getString("TABLE_NAME");
        className = StringUtil.toProperClassName(tableName); // space allowed...
        // tableName = tableName.toUpperCase(); //If Oracle that need uppercase tablename. In MySQL
        // in Mac OS X (and probably Linux), it mustbe case sensitive
        // open table
        String sql = "select * from " + tableName;
        PreparedStatement pstmt =
            Db.getCon()
                .prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();

        // get foreign keys,and stored it in hashtable
        ResultSet rsFk = meta.getImportedKeys(Db.getCon().getCatalog(), null, tableName);
        Hashtable hashFk = new Hashtable();
        System.out.println("FK Infos for table " + tableName);
        while (rsFk.next()) {
          String pkTableName = rsFk.getString("PKTABLE_NAME");
          String pkColumnName = rsFk.getString("PKCOLUMN_NAME");
          String fkColumnName = rsFk.getString("FKCOLUMN_NAME");

          int fkSequence = rsFk.getInt("KEY_SEQ");
          System.out.println(
              tableName + "." + fkColumnName + " => " + pkTableName + "." + pkColumnName);
          hashFk.put(fkColumnName, pkColumnName);
          hashFk.put(fkColumnName + "_table", pkTableName);
        }
        rsFk.close();

        // create form page
        System.out.println(
            "Creating form page for "
                + tableName
                + " from table + "
                + application.config.Database.DB
                + "."
                + tableName);
        fDir = new File("../../web/WEB-INF/views/" + tableName);
        if (!fDir.exists()) fDir.mkdir();
        File f = new File("../../web/WEB-INF/views/" + tableName + "/form_" + tableName + ".jsp");
        if (ignoreList.get("form_" + tableName + ".jsp") != null) {
          Logger.getLogger(GenerateForm.class.getName())
              .log(Level.INFO, "Ignoring creation of form_" + tableName + ".jsp");
        } else {
          Writer out = new FileWriter(f);
          out.write(
              "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>");
          out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n");
          out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n");

          // create model for this class, use in detecting its PK Field
          cl = Class.forName("application.models." + className + "Model");
          model = (Model) cl.newInstance();

          // iterate all columns
          resultSet.beforeFirst();
          resultSet.next();
          out.write(
              "<table border=\"1\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" bordercolor=\"#E8EDFF\">\n");
          out.write("<tr>\n");
          out.write("<td>\n");
          out.write(
              "<form action=\"<%=Config.base_url%>index/"
                  + className
                  + "/save\" method=\"post\" enctype=\"multipart/form-data\">\n"); // I hope it's
          // okay to
          // default it to
          // multipart data
          out.write("<table id=\"hor-zebra\" summary=\"Form " + className + "\">\n");
          out.write("<thead>\n");
          out.write("<tr>\n");
          out.write("<th colspan=\"2\" class=\"odd\" scope=\"col\">Form " + className + " </th>\n");
          out.write("</tr>\n");
          out.write("</thead>\n");
          out.write("<tbody>\n");

          for (int i = 1; i <= nColoumn; i++) {
            String columnName = metaColumn.getColumnName(i);
            String dataType = metaColumn.getColumnClassName(i);
            out.write("<tr>\n");

            // if(!columnName.equals(model.getPkFieldName())) // implementing the case of PK not
            // AutoIncrement
            // if(!metaColumn.isAutoIncrement(i))
            // {
            // varying field input for type

            // foreign field, as chooser page view
            if (hashFk.get(columnName)
                != null) // TODO: what if PK is chooser also?? :) CUrrently I add it manually the
            // hidden_*Pk_nama* field
            {
              String fkTableName = hashFk.get(columnName + "_table") + "";
              String fkColumnName = hashFk.get(columnName) + "";
              String fkController = StringUtil.toProperClassName(fkTableName);

              out.write("<td>" + columnName + "</td>\n");
              out.write("<td>\n");
              out.write(
                  "<input name=\""
                      + columnName
                      + "\" type=\"hidden\" id=\""
                      + columnName
                      + "\" value=\"${model."
                      + columnName
                      + "}\"/>\n");
              out.write(
                  "<input name=\"label_"
                      + columnName
                      + "\" readonly=\"true\" type=\"text\" id=\"label_"
                      + columnName
                      + "\" value=\"${model."
                      + columnName
                      + "}\"/>\n"); // TODO : translate I
              out.write(
                  "<a href=\"<%=Config.base_url%>index/"
                      + fkController
                      + "/chooseView?height=220&width=700\" class=\"thickbox\">Pilih</a>");
              out.write("</td>\n");
            } else {

              // regular field input, not foreign key case
              if (!columnName.equals(model.getPkFieldName())) {
                out.write("<td>" + columnName + "</td>\n");
                out.write("<td>\n");

                // ENUM Column, displayed as HTML SELECT. May will only work for mysql only...
                Logger.getLogger(GenerateForm.class.getName())
                    .log(Level.INFO, columnName + " type is " + metaColumn.getColumnType(i));
                if (metaColumn.getColumnType(i) == 1) {
                  String enum_content[][] =
                      Db.getDataSet(
                          "SELECT SUBSTRING(COLUMN_TYPE,6,length(SUBSTRING(COLUMN_TYPE,6))-1) as enum_content "
                              + " FROM information_schema.COLUMNS "
                              + " WHERE TABLE_NAME='"
                              + tableName
                              + "' "
                              + " AND COLUMN_NAME='"
                              + columnName
                              + "'");
                  if (enum_content.length > 0) {
                    // Logger.getLogger(Model.class.getName()).log(Level.INFO, "Enum Content = " +
                    // enum_content[0][0]);
                    String enum_list[] = enum_content[0][0].split(",");
                    out.write("<select name=\"" + columnName + "\" id=\"" + columnName + "\">\n");
                    for (int ienum_list = 0; ienum_list < enum_list.length; ienum_list++)
                      out.write(
                          "\t<option <c:if test=\"${model."
                              + columnName
                              + "=='"
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "'}\"> selected=\"selected\" </c:if> value=\""
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "\">"
                              + enum_list[ienum_list].substring(
                                  1, enum_list[ienum_list].length() - 1)
                              + "</option>\n");
                    out.write("</select>\n\n");

                  } else {
                    // no enum content detected.. :)
                    out.write(
                        "<input name=\""
                            + columnName
                            + "\" type=\"text\" id=\""
                            + columnName
                            + "\" value=\"${model."
                            + columnName
                            + "}\"/>\n");
                  }
                } else if (metaColumn.getColumnType(i) == 91) {
                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("<script>\n");
                  out.write(
                      " if(!isValidDate($('#"
                          + columnName
                          + "').val())) $('#"
                          + columnName
                          + "').val('1980-1-1');\n"); // TODO: default value
                  out.write("  (function($){\n");

                  out.write("  $('#" + columnName + "').click(function() {\n");
                  out.write("    $('#" + columnName + "').DatePickerShow();\n");
                  out.write("  });\n");

                  out.write("  $('#" + columnName + "').DatePicker({\n");
                  out.write("    format:'Y-m-d',\n");
                  out.write("    date: $('#" + columnName + "').val(),\n");
                  out.write("    current: $('#" + columnName + "').val(),\n");
                  out.write("    starts: 1,\n");
                  out.write("    position: 'r',\n");

                  out.write("    onBeforeShow: function(){\n");
                  out.write(
                      "      $('#"
                          + columnName
                          + "').DatePickerSetDate($('#"
                          + columnName
                          + "').val(), true);\n");
                  out.write("    },\n");

                  out.write("    onChange: function(formated, dates){\n");
                  out.write("      $('#" + columnName + "').DatePickerHide();\n");
                  out.write("      $('#" + columnName + "').val(formated);\n");
                  out.write("    }\n");
                  out.write("  });\n");
                  out.write("  })(jQuery)\n");
                  out.write(" </script>\n");
                } else {
                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("${" + columnName + "_error}\n"); // regular input field
                }
              } else { // PK case
                if (metaColumn.isAutoIncrement(i)) {
                  out.write(
                      "<input name=\"hidden_"
                          + columnName
                          + "\" type=\"hidden\" id=\"hidden_"
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                } else {
                  out.write("<td>" + columnName + "</td>\n");
                  out.write("<td>\n");

                  out.write(
                      "<input name=\""
                          + columnName
                          + "\" type=\"text\" id=\""
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                  out.write("${" + columnName + "_error}\n");
                  out.write(
                      "<input name=\"hidden_"
                          + columnName
                          + "\" type=\"hidden\" id=\"hidden_"
                          + columnName
                          + "\" value=\"${model."
                          + columnName
                          + "}\"/>\n");
                }
              }
              out.write("</td>\n");
            }
            out.write("</tr>\n");
          }
          out.write("<tr class=\"odd\">\n");
          out.write("<td>&nbsp;</td>\n");
          out.write("<td><input type=\"submit\" name=\"Submit\" value=\"Simpan\">");
          out.write(
              "<input name=\"Button\" type=\"button\" id=\"Submit\" value=\"Batal\" onClick=\"javascript:history.back(-1);\"></td>\n");
          out.write("</tr>\n");
          out.write("</tbody>\n");
          out.write("</table>\n");
          out.write("</form></td>\n");
          out.write("</tr>\n");
          out.write("</table>\n");
          out.flush();
          out.close();
        }

        // create viewPage
        if (ignoreList.get("view_" + tableName + ".jsp") != null) {
          Logger.getLogger(GenerateForm.class.getName())
              .log(Level.INFO, "Ignoring creation of view_" + tableName + ".jsp");
        } else {
          System.out.println("Creating view page " + tableName);

          fDir = new File("../../web/WEB-INF/views/" + tableName);
          if (!fDir.exists()) fDir.mkdir();
          File fView =
              new File("../../web/WEB-INF/views/" + tableName + "/view_" + tableName + ".jsp");
          Writer outView = new FileWriter(fView);
          outView.write(
              "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>");
          outView.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n");
          outView.write(
              "<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n");
          outView.write("<% int pagenum = 0; %>\n");
          // outView.write("<%@ include file=\"/WEB-INF/views/header.jsp\" %>");
          outView.write(
              "<a href=\"<%=Config.base_url%>index/" + className + "/input/-1\">Tambah Data</a>\n");
          outView.write(
              "|| <a href=\"<%=Config.base_url%>index/" + className + "/print\">Cetak</a>\n");
          outView.write("<table width=\"100%\" id=\"rounded-corner\">\n");
          outView.write("<thead>\n");
          // iterate all columns : table header
          outView.write("  <tr>\n");
          outView.write("  <th scope=\"col\" class=\"rounded-company\">No.</th>\n");
          resultSet.beforeFirst();
          resultSet.next();

          // get Primary Key Field Name : often use
          String pkFieldName = "";
          try {
            Class params[] = null;
            Method objMethod = cl.getMethod("getPkFieldName", params);
            pkFieldName = "" + objMethod.invoke(model);
          } catch (Exception ex) {
            Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
          }

          // ALL Lower Case
          pkFieldName = pkFieldName.toLowerCase();

          // customize column view page
          for (int i = 1; i <= nColoumn; i++) {
            String columnName =
                metaColumn.getColumnName(i).toLowerCase(); // Caution : ALL LowerCase
            String dataType = metaColumn.getColumnClassName(i);
            String thClass = "rounded-q1";
            String thTitle = StringUtil.toProperFieldTitle(columnName);

            if (TableCustomization.getTable(tableName)
                != null) // there is customization for this table
            {
              if (TableCustomization.getTable(tableName).get(columnName) != null) {
                thTitle = TableCustomization.getTable(tableName).get(columnName) + "";
                outView.write(
                    "  <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n");
              }
            } else { // standard view for this table : hide PK, because mostly is auto increment
              if (!metaColumn.isAutoIncrement(i))
                outView.write(
                    "  <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n");
            }
          }

          outView.write("  <th scope=\"col\" class=\"rounded-q4\">Aksi</th>\n");
          outView.write("  </tr>\n");
          outView.write("</thead>\n");
          outView.write("<tfoot>\n");
          outView.write("  <tr>\n");
          outView.write(
              "    <td colspan=\""
                  + (nColoumn + 1)
                  + "\" class=\"rounded-foot-left\"><%=Pagination.createLinks(pagenum)%></td>\n");
          outView.write("    <td class=\"rounded-foot-right\">&nbsp;</td>\n");
          outView.write("  </tr>\n");
          outView.write("</tfoot>\n");

          outView.write("<tbody>\n");
          outView.write("  <c:forEach items=\"${row}\" var=\"item\" varStatus=\"status\" >\n");
          outView.write("    <tr>\n");
          outView.write("      <td>${status.count}</td>\n");

          // iterate all columns : table data
          resultSet.beforeFirst();
          resultSet.next();
          for (int i = 1; i <= nColoumn; i++) {
            String columnName = metaColumn.getColumnName(i);
            // if(!columnName.equals(pkFieldName)) //TOFIX : currently, PK Field is not shown
            if (TableCustomization.getTable(tableName) != null) {
              if (TableCustomization.getTable(tableName).get(columnName) != null) {
                outView.write("      <td>${item." + columnName + "}</td>\n");
              }
            } else {
              if (!metaColumn.isAutoIncrement(i))
                outView.write("      <td>${item." + columnName + "}</td>\n");
            }
          }

          outView.write("      <td>\n");
          outView.write(
              "         <a href=\"<%=Config.base_url%>index/"
                  + className
                  + "/input/${item."
                  + pkFieldName
                  + "}\">Ubah</a>\n");
          outView.write(
              "         <a href=\"<%=Config.base_url%>index/"
                  + className
                  + "/delete/${item."
                  + pkFieldName
                  + "}\" onClick=\"return confirm('Apakah Anda yakin?');\">Hapus</a>\n");
          outView.write("      </td>\n");

          outView.write("    </tr>\n");
          outView.write("  </c:forEach>\n");
          outView.write("</tbody>\n");
          outView.write("</table>\n");
          // outView.write("<%@ include file=\"/WEB-INF/views/footer.jsp\" %>");
          outView.flush();
          outView.close();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#16
0
  protected boolean checkExistence(Connection conn, DatabaseObjectType type, String... params)
      throws SQLException {
    boolean result = false;
    DatabaseMetaData metadata = null;
    PreparedStatement pstmt = null;
    BaseSchema baseSchema = catalogStore.getSchema();

    if (params == null || params.length < 1) {
      throw new IllegalArgumentException("checkExistence function needs at least one argument.");
    }

    switch (type) {
      case DATA:
        metadata = conn.getMetaData();
        ResultSet data =
            metadata.getUDTs(
                null,
                baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                    ? baseSchema.getSchemaName().toUpperCase()
                    : null,
                params[0].toUpperCase(),
                null);
        result = data.next();
        CatalogUtil.closeQuietly(data);
        break;
      case FUNCTION:
        metadata = conn.getMetaData();
        ResultSet functions =
            metadata.getFunctions(
                null,
                baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                    ? baseSchema.getSchemaName().toUpperCase()
                    : null,
                params[0].toUpperCase());
        result = functions.next();
        CatalogUtil.closeQuietly(functions);
        break;
      case INDEX:
        if (params.length != 2) {
          throw new IllegalArgumentException(
              "Finding index object is needed two strings, table name and index name");
        }

        pstmt = getExistQuery(conn, type);
        if (pstmt != null) {
          result = checkExistenceByQuery(pstmt, baseSchema, params);
        } else {
          metadata = conn.getMetaData();
          ResultSet indexes =
              metadata.getIndexInfo(
                  null,
                  baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                      ? baseSchema.getSchemaName().toUpperCase()
                      : null,
                  params[0].toUpperCase(),
                  false,
                  true);
          while (indexes.next()) {
            if (indexes.getString("INDEX_NAME").equals(params[1].toUpperCase())) {
              result = true;
              break;
            }
          }
          CatalogUtil.closeQuietly(indexes);
        }
        break;
      case TABLE:
        pstmt = getExistQuery(conn, type);
        if (pstmt != null) {
          result = checkExistenceByQuery(pstmt, baseSchema, params);
        } else {
          metadata = conn.getMetaData();
          ResultSet tables =
              metadata.getTables(
                  null,
                  baseSchema.getSchemaName() != null && !baseSchema.getSchemaName().isEmpty()
                      ? baseSchema.getSchemaName().toUpperCase()
                      : null,
                  params[0].toUpperCase(),
                  new String[] {"TABLE"});
          result = tables.next();
          CatalogUtil.closeQuietly(tables);
        }
        break;
      case DOMAIN:
      case OPERATOR:
      case RULE:
      case SEQUENCE:
      case TRIGGER:
      case VIEW:
        pstmt = getExistQuery(conn, type);

        if (pstmt == null) {
          throw new TajoInternalError(
              "Finding "
                  + type
                  + " type of database object is not supported on this database system.");
        }

        result = checkExistenceByQuery(pstmt, baseSchema, params);
        break;
    }

    return result;
  }
  /* 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();
  }