⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqlinfo.java

📁 java开源的企业总线.xmlBlaster
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
      if (fillData) {         int count = 0;         while (rs.next()) {            SqlRow row = new SqlRow(this.info, count);            count++;            getRows().add(row);            for (int i=1; i<=numberOfColumns; i++) {               String value = rs.getString(i);               ClientProperty prop = new ClientProperty(meta.getColumnName(i), null, null, value);               row.setColumn(prop);            }            if (transformer != null) {               Map attr = transformer.transform(rs, count);               if (attr != null) {                  Iterator iter = attr.entrySet().iterator();                  while (iter.hasNext()) {                     Map.Entry entry = (Map.Entry)iter.next();                     ClientProperty prop = new ClientProperty((String)entry.getKey(), null, null, entry.getValue().toString());                     row.setAttribute(prop);                  }               }            }         }      }   }   public final int getRowCount() {      return getRows().size();   }      /**    * Result set must come from a select spaning over a single table.    * @param rs    * @param conn    * @throws SQLException    */   public SqlRow fillOneRowWithStringEntriesDEPRECATED(ResultSet rs, I_AttributeTransformer transformer) throws Exception {      ResultSetMetaData meta = rs.getMetaData();      int numberOfColumns = meta.getColumnCount();      int count = getRowCount();      SqlRow row = new SqlRow(this.info, count);      getRows().add(row);      for (int i=1; i<=numberOfColumns; i++) {         String value = rs.getString(i);         ClientProperty prop = new ClientProperty(meta.getColumnName(i), null, null, value);         row.setColumn(prop);      }      if (transformer != null) {         Map attr = transformer.transform(rs, count);         if (attr != null)            row.addAttributes(attr);      }      return row;   }   /**    * Never returns null. If the result is null, the value of the returned client property will be null.    * @param name    * @param val    * @return    */   public static ClientProperty buildClientProperty(ResultSetMetaData meta, ResultSet rs, int pos) throws Exception {      String name = meta.getColumnName(pos);      Object val = rs.getObject(pos);      if (val == null)         return new ClientProperty(name, null, null, (String)null);      if (val instanceof String) // TODO FIX THIS DIRTY HACK         return new ClientProperty(name, null, Constants.ENCODING_BASE64, (String)val);            if (val instanceof Boolean)         return new ClientProperty(name, null, null, "" + ((Boolean)val).booleanValue());      if (val instanceof Short)         return new ClientProperty(name, null, null, "" + ((Short)val).shortValue());      if (val instanceof Integer)         return new ClientProperty(name, null, null, "" + ((Integer)val).intValue());      if (val instanceof Long)         return new ClientProperty(name, null, null, "" + ((Long)val).longValue());      if (val instanceof Float)         return new ClientProperty(name, null, null, "" + ((Float)val).floatValue());               if (val instanceof Double)         return new ClientProperty(name, null, null, "" + ((Double)val).doubleValue());      if (val instanceof byte[]) {         ClientProperty prop = new ClientProperty(name, null, null);         prop.setValue((byte[])val);      }      if (val instanceof Clob) { // only for relatively small clobs (< 10MB)         try {            Clob clob = (Clob)val;            InputStream in = clob.getAsciiStream();            ByteArrayOutputStream baos = new ByteArrayOutputStream();            // StringBuffer strBuf = new StringBuffer();            byte[] buf = new byte[100000];            int read = 0;            int count=0;            while (  (read=in.read(buf)) != -1) {               baos.write(buf, 0, read);               count++;               if (count > 100)                  throw new IllegalArgumentException("The clob '" + name + "' is too big, already exceeding 10 MB. Will stop processing it");            }            in.close();            ClientProperty prop  = new ClientProperty(name, null, null);            prop.setValue(new String(baos.toByteArray()));            return prop;         }         catch (Exception ex) {            throw new Exception("An exception occured when processing '" + name + "'", ex);         }      }      if (val instanceof Blob) { // only for relatively small clobs (< 10MB)         try {            Blob blob = (Blob)val;            InputStream in = blob.getBinaryStream();            ByteArrayOutputStream baos = new ByteArrayOutputStream();            // StringBuffer strBuf = new StringBuffer();            byte[] buf = new byte[100000];            int read = 0;            int count=0;            while (  (read=in.read(buf)) != -1) {               baos.write(buf, 0, read);               count++;               if (count > 100)                  throw new IllegalArgumentException("The blob '" + name + "' is too big, already exceeding 10 MB. Will stop processing it");            }            in.close();            ClientProperty prop  = new ClientProperty(name, null, null);            prop.setValue(new String(baos.toByteArray()));         }         catch (Exception ex) {            throw new Exception("An exception occured when processing '" + name + "'", ex);         }      }      if (val instanceof Timestamp) {         Timestamp ts = (Timestamp)val;         return new ClientProperty(name, null, null, ts.toString());      }      if (val instanceof BigDecimal) {         BigDecimal dec = (BigDecimal)val;         try {            return new ClientProperty(name, null, null, "" + dec.longValue());         }         catch (Exception ex) {            return new ClientProperty(name, null, null, "" + dec.doubleValue());         }      }      if (val instanceof BigInteger) {         BigInteger dec = (BigInteger)val;         return new ClientProperty(name, null, null, "" + dec.longValue());      }      if (val instanceof Date) {         // Date date = (Date)val;         Timestamp ts = rs.getTimestamp(pos);         // DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         // String dateTxt = format.format(date);         String dateTxt = ts.toString();         return new ClientProperty(name, null, null, dateTxt);      }      if (val instanceof Time) {         Time time = (Time)val;         return new ClientProperty(name, null, null, "" + time.getTime());      }      else {         return new ClientProperty(name, null, null, rs.getString(pos)); // e.g. oracle.sql.TIMESTAMP containing a byte[]         //throw new Exception("The object '" + name + "' of type '" + val.getClass().getName() + "' can not be processed since this type is not implemented");      }   }      /**    * Result set must come from a select spaning over a single table.    *     * @param rs    * @param conn    * @throws SQLException    */   public SqlRow fillOneRowWithObjects(ResultSet rs, I_AttributeTransformer transformer) throws Exception {      ResultSetMetaData meta = rs.getMetaData();      int numberOfColumns = meta.getColumnCount();      int count = getRowCount();      SqlRow row = new SqlRow(this.info, count);      getRows().add(row);      for (int i=1; i<=numberOfColumns; i++) {         ClientProperty prop = buildClientProperty(meta, rs, i);         if (prop.getValueRaw() != null)            row.setColumn(prop);      }      if (transformer != null) {         Map attr = transformer.transform(rs, count);         if (attr != null)            row.addAttributes(attr);      }      return row;   }      /**    * Result set must come from a select spaning over a single table.    * @param rawContent the raw content of all the columns belonging to this row.    * @param conn    * @throws SQLException    */   public SqlRow fillOneRow(ResultSet rs, String rawContent, I_AttributeTransformer transformer) throws Exception {      int count = getRowCount();      SqlRow row = new SqlRow(this.info, count);      getRows().add(row);      row.setColsRawContent(rawContent);      if (transformer != null) {         Map attr = transformer.transform(rs, count);         if (attr != null)            row.addAttributes(attr);      }      return row;   }      /**    * This method is used for testing other applications, it generates a new row and adds it    * if possible. Note that this is only added if it is possible, otherwise it returns null.    * It is currently not possible to add something if the table in question has a foreign key.    * No check is made against primary keys.     *     * @throws SQLException    */   public SqlRow fillOneRowWithRandomData() throws Exception {      int count = getRowCount();      SqlColumn[] cols = getDescription().getColumns();      SqlRow row = new SqlRow(this.info, count);      for (int i=0; i < cols.length; i++) {         if (cols[i].getFkCol() != null) {            log.warning("The column '" + cols[i].getTable() + "." + cols[i].getColName() + " has a fK '" + cols[i].getFkTable() + "." + cols[i].getFkCol() + "'");            return null;         }         ClientProperty prop = cols[i].generateRandomObject();         if (prop == null) {            log.warning("The column '" + cols[i].getTable() + "." + cols[i].getColName() + " has an unprocessable type '" + SqlColumn.getSqlTypeAsText(cols[i].getSqlType()) + "'");            return null;         }         row.setColumn(prop);      }      getRows().add(row);      return row;   }         public SqlDescription getDescription() {      return this.description;   }   public void setDescription(SqlDescription description) {      this.description = description;   }   public List getRows() {      return this.rows;   }   public String toXml(String extraOffset) {      return toXml(extraOffset, false, false, false);   }      public String toString() {      return toXml("", true, true, false);   }      public final String toXml(String extraOffset, boolean doTruncate, boolean forceReadable, boolean omitDecl) {      String charSet = info.get("charSet", "UTF-8");      final boolean withRowTag = true; // used for row.toXml()      StringBuffer sb = new StringBuffer(4096);      if (!omitDecl)         sb.append("<?xml version='1.0' encoding='" + charSet + "' ?>");      if (extraOffset == null) extraOffset = "";      String offset = Constants.OFFSET + extraOffset;      sb.append(offset).append("<").append(SQL_TAG).append(">");      if (this.description != null)         sb.append(this.description.toXml(extraOffset + "  ", doTruncate));      if (doTruncate && sb.length() > MAX_BUF_SIZE) {         sb.append(" ... (total num of rows=").append(this.rows.size()).append(")");         return sb.toString();      }      Iterator iter = this.rows.iterator();      while (iter.hasNext()) {         SqlRow recordRow = (SqlRow)iter.next();         sb.append(recordRow.toXml(extraOffset + "  ", withRowTag, doTruncate, forceReadable));         if (doTruncate && sb.length() > MAX_BUF_SIZE) {            sb.append(" ... (total num of rows=").append(this.rows.size()).append(")");            return sb.toString();         }      }      sb.append(offset).append("</").append(SQL_TAG).append(">");      return sb.toString();   }      public static SqlInfo getStructure(I_Info info) throws Exception {      I_DbPool pool = (I_DbPool) info.getObject("db.pool");      Connection conn = null;      try {         SqlInfo sqlInfo = new SqlInfo(info);         SqlDescription description = new SqlDescription(info);         conn = pool.reserve();         conn.setAutoCommit(true);         ArrayList list = new ArrayList();         TableToWatchInfo.getSortedTablesToWatch(conn, info, list);         for (int i=0; i < list.size(); i++) {            SqlDescription descr = (SqlDescription)list.get(i);            SqlColumn[] cols = descr.getColumns();            for (int j=0; j < cols.length; j++) {               description.addColumn(cols[j]);            }         }         sqlInfo.setDescription(description);         return sqlInfo;      }      finally {         if (conn != null)            pool.release(conn);      }   }      public static void main(String[] args) {      I_DbPool pool = null;      Connection conn = null;      try {         // ---- Database settings -----         if (System.getProperty("jdbc.drivers", null) == null) {            System.setProperty(                        "jdbc.drivers",                        "org.hsqldb.jdbcDriver:oracle.jdbc.driver.OracleDriver:com.microsoft.jdbc.sqlserver.SQLServerDriver:org.postgresql.Driver");         }         if (System.getProperty("db.url", null) == null) {            System.setProperty("db.url", "jdbc:postgresql:test//localhost/test");         }         if (System.getProperty("db.user", null) == null) {            System.setProperty("db.user", "postgres");         }         if (System.getProperty("db.password", null) == null) {            System.setProperty("db.password", "");         }         String propFile = System.getProperty("properties", null);         Properties props = null;         if (propFile == null) {            props = System.getProperties();            System.err.println("not using any properties file");         }         else {            System.err.println("Using properties file '" + propFile + "'");            props = new Properties(System.getProperties());            props.load(new FileInputStream(propFile));         }         I_Info info = new PropertiesInfo(props);                  boolean forceCreationAndInit = true;         ReplicationConverter.getDbSpecific(info, forceCreationAndInit);                  SqlInfo sqlInfo = SqlInfo.getStructure(info);         System.out.println(sqlInfo.toXml(""));      }       catch (Throwable e) {         System.err.println("SEVERE: " + e.toString());         e.printStackTrace();         final boolean ROLLBACK_NO = false;         conn = SpecificDefault.removeFromPool(conn, ROLLBACK_NO, pool);      }      finally {         if (pool != null) {            final boolean COMMIT_NO = false;            conn = SpecificDefault.releaseIntoPool(conn, COMMIT_NO, pool);         }      }   }   }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -