示例#1
1
  public static int serDiccGroupByToWriter(
      ResultSet rs,
      Writer writer,
      int maxRows,
      String idPor,
      String[] idAcumulados,
      String campoAcumuladoNombre) {
    int rowsCount = 0;

    try {

      ArrayList<String> acumulado = null;
      String idActual = null;
      StringBuilder reg = null;
      reg = new StringBuilder();
      String value = "";

      if (rs != null) {
        ResultSetMetaData rsm = rs.getMetaData();
        int countCol = rsm.getColumnCount();
        String name = "";
        for (int i = 1; i <= countCol; i++) {
          name = rsm.getColumnName(i);
          reg.append(name.toLowerCase()).append("\t");
        }
        reg.append(campoAcumuladoNombre);

        writer.write(reg.toString() + EOL);

        while (rs.next()) {
          if (idActual == null) {
            reg = new StringBuilder();
            acumulado = new ArrayList<String>();
            idActual = rs.getString(idPor);

            for (int i = 1; i <= countCol; i++) {
              reg.append(rs.getString(i)).append("\t");
            }

            for (String id : idAcumulados) {
              value = rs.getString(id);
              if (!rs.wasNull()) {
                acumulado.add(rs.getString(id));
              }
            }

          } else {

            if (idActual.equals(rs.getString(idPor))) {
              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            } else {
              if (acumulado.size() > 0) {
                for (String str : acumulado) {
                  reg.append(str).append(",");
                }
                reg.deleteCharAt(reg.length() - 1);
              }
              reg.append(EOL);

              writer.write(reg.toString());
              rowsCount++;
              if (maxRows == rowsCount) {
                break;
              }

              idActual = rs.getString(idPor);
              reg = new StringBuilder();
              acumulado = new ArrayList<String>();

              for (int i = 1; i <= countCol; i++) {
                reg.append(rs.getString(i)).append("\t");
              }

              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            }
          }
        }

        if (acumulado.size() > 0) {
          for (String str : acumulado) {
            reg.append(str).append(",");
          }
          reg.deleteCharAt(reg.length() - 1);
        }
        reg.append(EOL);

        writer.write(reg.toString());
        rowsCount++;
      }
    } catch (SQLException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    } catch (IOException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    }
    return rowsCount;
  }
示例#2
0
  public static String convertStreamToString(InputStream is) throws IOException {
    /*
     * To convert the InputStream to String we use the Reader.read(char[]
     * buffer) method. We iterate until the Reader return -1 which means there's
     * no more data to read. We use the StringWriter class to produce the
     * string.
     */
    if (is != null) {
      Writer writer = new StringWriter();

      char[] buffer = new char[1024];
      try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }
      } finally {
        is.close();
      }
      return writer.toString();
    } else {
      return "";
    }
  }
示例#3
0
 static void genclass(DelegatorGenerator dg, Class intfcl, String fqcn, File srcroot)
     throws IOException {
   File genDir = new File(srcroot, dirForFqcn(fqcn));
   if (!genDir.exists()) {
     System.err.println(
         JdbcProxyGenerator.class.getName()
             + " -- creating directory: "
             + genDir.getAbsolutePath());
     genDir.mkdirs();
   }
   String fileName = CodegenUtils.fqcnLastElement(fqcn) + ".java";
   Writer w = null;
   try {
     w = new BufferedWriter(new FileWriter(new File(genDir, fileName)));
     dg.writeDelegator(intfcl, fqcn, w);
     w.flush();
     System.err.println("Generated " + fileName);
   } finally {
     try {
       if (w != null) w.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
示例#4
0
 public static void closeWriterAppend(Writer writer) {
   try {
     writer.close();
   } catch (IOException e) {
     logmex("ERR", 0, "FILE WRITER CSV OUTPUT closing", null, e);
   }
 }
示例#5
0
  private void write(Writer os, Object rowValue, ArrayList encodedCols, String col)
      throws SQLException, IOException {
    try {
      if (!encodedCols.contains(col.toUpperCase())) {
        os.write(rowValue.toString());
        //            os.write("<![CDATA[" + rowValue.toString() + "]]>");
      } else {
        //              os.write("<![CDATA[" +
        //                       EncoderDecoder.escapeUnicodeString1(rowValue.toString(), true) +
        //                       "]]>");

        os.write(EncoderDecoder.escapeUnicodeString1(rowValue.toString(), true));
      }
    } catch (NullPointerException ex) {
      os.write("NULL");
    }
  }
示例#6
0
  /**
   * writes a long values in XML file
   *
   * @param os
   * @param rs
   * @param index
   * @throws IOException
   * @throws SQLException
   */
  public void write(Writer os, ResultSet rs, int index, ArrayList encodedCols, String col)
      throws SQLException, IOException {
    try {
      if (!encodedCols.contains(col.toUpperCase())) {
        os.write(getObject(rs, index).toString());
        //            os.write("<![CDATA[" + getObject(rs, index).toString() + "]]>");
      } else {
        os.write(EncoderDecoder.escapeUnicodeString1(getObject(rs, index).toString(), true));

        //              os.write("<![CDATA[" +
        //                       EncoderDecoder.escapeUnicodeString1(getObject(rs, index).
        //                  toString(), true) +
        //                       "]]>");
      }

    } catch (NullPointerException ex) {
      os.write("NULL");
    }
  }
示例#7
0
  /**
   * Tests that the data updated in a Clob is always reflected in the Reader got. Here the updates
   * are done using both a Writer obtained from this Clob and using Clob.setString.
   *
   * @throws Exception
   */
  public void testGetCharacterStreamClobUpdates() throws Exception {
    // The String that will be used
    // to do the inserts into the
    // Clob.
    String str1 = "Hi I am the insert string";

    // The String that will be used in the
    // second series of updates
    String str2 = "Hi I am the update string";

    // create the empty Clob.
    Clob clob = getConnection().createClob();

    // Get the Reader from this
    // Clob
    Reader r_BeforeWrite = clob.getCharacterStream();

    // Get a writer from this Clob
    // into which the data can be written
    Writer w = clob.setCharacterStream(1);
    char[] chars_str1 = new char[str1.length()];
    str2.getChars(0, str1.length(), chars_str1, 0);
    w.write(chars_str1);

    // Doing a setString now on the Clob
    // should reflect the same extension
    // in the InputStream also.
    clob.setString((str1.length()) + 1, str2);

    // Now get the reader from the Clob after
    // the update has been done.
    Reader r_AfterWrite = clob.getCharacterStream();

    // Now compare the two readers to see that they
    // contain the same data.
    assertEquals(r_BeforeWrite, r_AfterWrite);
  }
示例#8
0
  @SuppressWarnings("unchecked")
  public static int serDiccCsvToWriter(String csv, Writer writer, int maxRows, String separator) {
    int counter = 0;

    if (csv != null) {
      try {
        writer.write(csv);
        writer.write(EOL);

      } catch (IOException e) {
        logmex("ERR", 0, "FILE WRITER CSV OUTPUT writing", null, e);
        return -1;
      }
    } else {
      logm("NFO", 3, "DB FILE CSV RESULTSET IS NULL, was expected?", null);
    }

    return counter;
  }
示例#9
0
  /**
   * Convert an existing data object to the specified JDBC type.
   *
   * @param callerReference an object reference to the caller of this method; must be a <code>
   *     Connection</code>, <code>Statement</code> or <code>ResultSet</code>
   * @param x the data object to convert
   * @param jdbcType the required type constant from <code>java.sql.Types</code>
   * @return the converted data object
   * @throws SQLException if the conversion is not supported or fails
   */
  static Object convert(Object callerReference, Object x, int jdbcType, String charSet)
      throws SQLException {
    // handle null value
    if (x == null) {
      switch (jdbcType) {
        case java.sql.Types.BIT:
        case JtdsStatement.BOOLEAN:
          return Boolean.FALSE;

        case java.sql.Types.TINYINT:
        case java.sql.Types.SMALLINT:
        case java.sql.Types.INTEGER:
          return INTEGER_ZERO;

        case java.sql.Types.BIGINT:
          return LONG_ZERO;

        case java.sql.Types.REAL:
          return FLOAT_ZERO;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
          return DOUBLE_ZERO;

        default:
          return null;
      }
    }

    try {
      switch (jdbcType) {
        case java.sql.Types.TINYINT:
          if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
          } else if (x instanceof Byte) {
            return new Integer(((Byte) x).byteValue() & 0xFF);
          } else {
            long val;
            if (x instanceof Number) {
              val = ((Number) x).longValue();
            } else if (x instanceof String) {
              val = new Long(((String) x).trim()).longValue();
            } else {
              break;
            }
            if (val < Byte.MIN_VALUE || val > Byte.MAX_VALUE) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Integer(new Long(val).intValue());
            }
          }

        case java.sql.Types.SMALLINT:
          if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
          } else if (x instanceof Short) {
            return new Integer(((Short) x).shortValue());
          } else if (x instanceof Byte) {
            return new Integer(((Byte) x).byteValue() & 0xFF);
          } else {
            long val;
            if (x instanceof Number) {
              val = ((Number) x).longValue();
            } else if (x instanceof String) {
              val = new Long(((String) x).trim()).longValue();
            } else {
              break;
            }
            if (val < Short.MIN_VALUE || val > Short.MAX_VALUE) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Integer(new Long(val).intValue());
            }
          }

        case java.sql.Types.INTEGER:
          if (x instanceof Integer) {
            return x;
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
          } else if (x instanceof Short) {
            return new Integer(((Short) x).shortValue());
          } else if (x instanceof Byte) {
            return new Integer(((Byte) x).byteValue() & 0xFF);
          } else {
            long val;
            if (x instanceof Number) {
              val = ((Number) x).longValue();
            } else if (x instanceof String) {
              val = new Long(((String) x).trim()).longValue();
            } else {
              break;
            }
            if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Integer(new Long(val).intValue());
            }
          }

        case java.sql.Types.BIGINT:
          if (x instanceof BigDecimal) {
            BigDecimal val = (BigDecimal) x;
            if (val.compareTo(MIN_VALUE_LONG_BD) < 0 || val.compareTo(MAX_VALUE_LONG_BD) > 0) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Long(val.longValue());
            }
          } else if (x instanceof Long) {
            return x;
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO;
          } else if (x instanceof Byte) {
            return new Long(((Byte) x).byteValue() & 0xFF);
          } else if (x instanceof BigInteger) {
            BigInteger val = (BigInteger) x;
            if (val.compareTo(MIN_VALUE_LONG_BI) < 0 || val.compareTo(MAX_VALUE_LONG_BI) > 0) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Long(val.longValue());
            }
          } else if (x instanceof Number) {
            return new Long(((Number) x).longValue());
          } else if (x instanceof String) {
            return new Long(((String) x).trim());
          } else {
            break;
          }

        case java.sql.Types.REAL:
          if (x instanceof Float) {
            return x;
          } else if (x instanceof Byte) {
            return new Float(((Byte) x).byteValue() & 0xFF);
          } else if (x instanceof Number) {
            return new Float(((Number) x).floatValue());
          } else if (x instanceof String) {
            return new Float(((String) x).trim());
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO;
          }

          break;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
          if (x instanceof Double) {
            return x;
          } else if (x instanceof Byte) {
            return new Double(((Byte) x).byteValue() & 0xFF);
          } else if (x instanceof Number) {
            return new Double(((Number) x).doubleValue());
          } else if (x instanceof String) {
            return new Double(((String) x).trim());
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO;
          }

          break;

        case java.sql.Types.NUMERIC:
        case java.sql.Types.DECIMAL:
          if (x instanceof BigDecimal) {
            return x;
          } else if (x instanceof Number) {
            return new BigDecimal(x.toString());
          } else if (x instanceof String) {
            return new BigDecimal((String) x);
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO;
          }

          break;

        case java.sql.Types.VARCHAR:
        case java.sql.Types.CHAR:
          if (x instanceof String) {
            return x;
          } else if (x instanceof Number) {
            return x.toString();
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? "1" : "0";
          } else if (x instanceof Clob) {
            Clob clob = (Clob) x;
            long length = clob.length();

            if (length > Integer.MAX_VALUE) {
              throw new SQLException(Messages.get("error.normalize.lobtoobig"), "22000");
            }

            return clob.getSubString(1, (int) length);
          } else if (x instanceof Blob) {
            Blob blob = (Blob) x;
            long length = blob.length();

            if (length > Integer.MAX_VALUE) {
              throw new SQLException(Messages.get("error.normalize.lobtoobig"), "22000");
            }

            x = blob.getBytes(1, (int) length);
          }

          if (x instanceof byte[]) {
            return toHex((byte[]) x);
          }

          return x.toString(); // Last hope!

        case java.sql.Types.BIT:
        case JtdsStatement.BOOLEAN:
          if (x instanceof Boolean) {
            return x;
          } else if (x instanceof Number) {
            return (((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
          } else if (x instanceof String) {
            String tmp = ((String) x).trim();

            return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE;
          }

          break;

        case java.sql.Types.VARBINARY:
        case java.sql.Types.BINARY:
          if (x instanceof byte[]) {
            return x;
          } else if (x instanceof Blob) {
            Blob blob = (Blob) x;

            return blob.getBytes(1, (int) blob.length());
          } else if (x instanceof Clob) {
            Clob clob = (Clob) x;
            long length = clob.length();

            if (length > Integer.MAX_VALUE) {
              throw new SQLException(Messages.get("error.normalize.lobtoobig"), "22000");
            }

            x = clob.getSubString(1, (int) length);
          }

          if (x instanceof String) {
            //
            // Strictly speaking this conversion is not required by
            // the JDBC standard but jTDS has always supported it.
            //
            if (charSet == null) {
              charSet = "ISO-8859-1";
            }

            try {
              return ((String) x).getBytes(charSet);
            } catch (UnsupportedEncodingException e) {
              return ((String) x).getBytes();
            }
          } else if (x instanceof UniqueIdentifier) {
            return ((UniqueIdentifier) x).getBytes();
          }

          break;

        case java.sql.Types.TIMESTAMP:
          if (x instanceof DateTime) {
            return ((DateTime) x).toTimestamp();
          } else if (x instanceof java.sql.Timestamp) {
            return x;
          } else if (x instanceof java.sql.Date) {
            return new java.sql.Timestamp(((java.sql.Date) x).getTime());
          } else if (x instanceof java.sql.Time) {
            return new java.sql.Timestamp(((java.sql.Time) x).getTime());
          } else if (x instanceof java.lang.String) {
            return java.sql.Timestamp.valueOf(((String) x).trim());
          }

          break;

        case java.sql.Types.DATE:
          if (x instanceof DateTime) {
            return ((DateTime) x).toDate();
          } else if (x instanceof java.sql.Date) {
            return x;
          } else if (x instanceof java.sql.Time) {
            return DATE_ZERO;
          } else if (x instanceof java.sql.Timestamp) {
            GregorianCalendar cal = (GregorianCalendar) calendar.get();
            cal.setTime((java.util.Date) x);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            // VM1.4+ only              return new java.sql.Date(cal.getTimeInMillis());
            return new java.sql.Date(cal.getTime().getTime());
          } else if (x instanceof java.lang.String) {
            return java.sql.Date.valueOf(((String) x).trim());
          }

          break;

        case java.sql.Types.TIME:
          if (x instanceof DateTime) {
            return ((DateTime) x).toTime();
          } else if (x instanceof java.sql.Time) {
            return x;
          } else if (x instanceof java.sql.Date) {
            return TIME_ZERO;
          } else if (x instanceof java.sql.Timestamp) {
            GregorianCalendar cal = (GregorianCalendar) calendar.get();
            // VM 1.4+ only             cal.setTimeInMillis(((java.sql.Timestamp)x).getTime());
            cal.setTime((java.util.Date) x);
            cal.set(Calendar.YEAR, 1970);
            cal.set(Calendar.MONTH, 0);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            // VM 1.4+ only             return new java.sql.Time(cal.getTimeInMillis());*/
            return new java.sql.Time(cal.getTime().getTime());
          } else if (x instanceof java.lang.String) {
            return java.sql.Time.valueOf(((String) x).trim());
          }

          break;

        case java.sql.Types.OTHER:
          return x;

        case java.sql.Types.JAVA_OBJECT:
          throw new SQLException(
              Messages.get(
                  "error.convert.badtypes", x.getClass().getName(), getJdbcTypeName(jdbcType)),
              "22005");

        case java.sql.Types.LONGVARBINARY:
        case java.sql.Types.BLOB:
          if (x instanceof Blob) {
            return x;
          } else if (x instanceof byte[]) {
            return new BlobImpl(getConnection(callerReference), (byte[]) x);
          } else if (x instanceof Clob) {
            //
            // Convert CLOB to BLOB. Not required by the standard but we will
            // do it anyway.
            //
            Clob clob = (Clob) x;
            try {
              if (charSet == null) {
                charSet = "ISO-8859-1";
              }
              Reader rdr = clob.getCharacterStream();
              BlobImpl blob = new BlobImpl(getConnection(callerReference));
              BufferedWriter out =
                  new BufferedWriter(new OutputStreamWriter(blob.setBinaryStream(1), charSet));
              // TODO Use a buffer to improve performance
              int c;
              while ((c = rdr.read()) >= 0) {
                out.write(c);
              }
              out.close();
              rdr.close();
              return blob;
            } catch (UnsupportedEncodingException e) {
              // Unlikely to happen but fall back on in memory copy
              x = clob.getSubString(1, (int) clob.length());
            } catch (IOException e) {
              throw new SQLException(
                  Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
            }
          }

          if (x instanceof String) {
            //
            // Strictly speaking this conversion is also not required by
            // the JDBC standard but jTDS has always supported it.
            //
            BlobImpl blob = new BlobImpl(getConnection(callerReference));
            String data = (String) x;

            if (charSet == null) {
              charSet = "ISO-8859-1";
            }

            try {
              blob.setBytes(1, data.getBytes(charSet));
            } catch (UnsupportedEncodingException e) {
              blob.setBytes(1, data.getBytes());
            }

            return blob;
          }

          break;

        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.CLOB:
          if (x instanceof Clob) {
            return x;
          } else if (x instanceof Blob) {
            //
            // Convert BLOB to CLOB
            //
            Blob blob = (Blob) x;
            try {
              InputStream is = blob.getBinaryStream();
              ClobImpl clob = new ClobImpl(getConnection(callerReference));
              Writer out = clob.setCharacterStream(1);
              // TODO Use a buffer to improve performance
              int b;
              // These reads/writes are buffered by the underlying blob buffers
              while ((b = is.read()) >= 0) {
                out.write(hex[b >> 4]);
                out.write(hex[b & 0x0F]);
              }
              out.close();
              is.close();
              return clob;
            } catch (IOException e) {
              throw new SQLException(
                  Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
            }
          } else if (x instanceof Boolean) {
            x = ((Boolean) x).booleanValue() ? "1" : "0";
          } else if (!(x instanceof byte[])) {
            x = x.toString();
          }

          if (x instanceof byte[]) {
            ClobImpl clob = new ClobImpl(getConnection(callerReference));
            clob.setString(1, toHex((byte[]) x));

            return clob;
          } else if (x instanceof String) {
            return new ClobImpl(getConnection(callerReference), (String) x);
          }

          break;

        default:
          throw new SQLException(
              Messages.get("error.convert.badtypeconst", getJdbcTypeName(jdbcType)), "HY004");
      }

      throw new SQLException(
          Messages.get("error.convert.badtypes", x.getClass().getName(), getJdbcTypeName(jdbcType)),
          "22005");
    } catch (NumberFormatException nfe) {
      throw new SQLException(
          Messages.get("error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000");
    }
  }
示例#10
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();
    }
  }
示例#11
0
 public static void set_stream(Writer os, String data) throws IOException {
   os.write(data);
   os.close();
 }
示例#12
0
  public static int serRsCsvToWriter(
      ResultSet resultset, String[] columnNames, Writer writer, int maxRows, String separator) {
    int counter = 0;
    if (resultset != null) {
      if (columnNames == null) {
        try {
          logm("NFO", 9, "CSV titulos, obteniendo desde metadata", null);
          columnNames = dbRsColumnNames(resultset);
        } catch (SQLException e) {
          logmex("ERR", 1, "CSV titulos, obteniendo desde metadata", null, e);
          return -1;
        }
      }
      logm("DBG", 7, "CSV titulos", columnNames);
      // A: columnCount tiene el valor especificado o el default

      int columnCount = columnNames.length;
      // Itero el resultset escribiendo el output
      try {
        // XXX:OPCION escape separator si aparece en un valor?

        logm("DBG", 4, "ESCRIBIENDO ARCHIVO", resultset);

        for (int i = 0; i < columnCount - 1; i++) {
          logm("DBG", 9, "ESCRIBE COL: ", columnNames[i]);
          writer.write(columnNames[i]);
          writer.write(separator);
        }

        writer.write(columnNames[columnCount - 1]);
        writer.write(EOL);

        logm("DBG", 4, "SE ESCRIBIO LINEA DE COLUMNAS", null);
        logm("DBG", 4, "COUNTER", counter);
        logm("DBG", 4, "MAXROWS", maxRows);
        // A: escribi los nombres de las columnas

        boolean hasNext = resultset.next();

        logm("DBG", 4, "NEXT", hasNext);

        while ((counter < maxRows || maxRows < 0) && hasNext) {

          logm("DBG", 4, "Escribiendo fila :", counter);

          String buf;
          for (int i = 1; i < columnCount; i++) {

            if ((buf = resultset.getString(i)) != null) {
              writer.write(buf);
            }

            logm("DBG", 9, "STR", buf);

            writer.write(separator);
          }
          if ((buf = resultset.getString(columnCount)) != null) {
            writer.write(buf);
          }

          logm("DBG", 9, "STR", buf);

          writer.write(EOL);
          counter++;
          // XXX:loguear un cartelito ej. cada 1000
          hasNext = resultset.next();
        }

        logm("DBG", 2, "termino de escribir lineas", null);

      } catch (SQLException s) {
        logmex("ERR", 0, "DB leyendo resultset para CSV", null, s);
        return -1;
      } catch (IOException e) {
        logmex("ERR", 0, "FILE WRITER CSV OUTPUT writing", null, e);
        return -1;
      }
    } else {
      logm("NFO", 3, "DB FILE CSV RESULTSET IS NULL, was expected?", null);
    }
    try {
      writer.close();
    } catch (IOException e) {
      logmex("ERR", 0, "FILE WRITER CSV OUTPUT closing", null, e);
      return -1;
    }
    return counter;
  }