Exemplo n.º 1
0
 public TableCellEditor getCellEditor(int row, int column) {
   final ColumnInfo<Item, ?> columnInfo =
       getListTableModel().getColumnInfos()[convertColumnIndexToModel(column)];
   final TableCellEditor editor =
       columnInfo.getEditor(getListTableModel().getItems().get(convertRowIndexToModel(row)));
   return editor == null ? super.getCellEditor(row, column) : editor;
 }
 public static ResultList fakeResultListData() {
   ResultList resList = new ResultList();
   ColumnInfo col1 = new ColumnInfo("TEST1");
   col1.setPosition(1);
   ColumnInfo col2 = new ColumnInfo("TEST2");
   col2.setPosition(2);
   java.util.ArrayList<ColumnInfo> colInfoList = new java.util.ArrayList<ColumnInfo>(2);
   colInfoList.add(col1);
   colInfoList.add(col2);
   ColumnDescriptor desc = new ColumnDescriptor();
   desc.setColumns(colInfoList);
   resList.setColumnDescriptor(desc);
   ResultRow row1 = new ResultRow();
   row1.setColumnDescriptor(desc);
   java.util.ArrayList<String> cols = new java.util.ArrayList<String>();
   cols.add("GOOD");
   cols.add("BAD");
   row1.setColumns(cols);
   ResultRow row2 = new ResultRow();
   cols = new java.util.ArrayList<String>();
   cols.add("LONG");
   cols.add("SHORT");
   row2.setColumns(cols);
   resList.getRows().add(row1);
   resList.getRows().add(row2);
   return resList;
 }
Exemplo n.º 3
0
 @Override
 public boolean equals(Object obj) {
   if (obj instanceof ColumnInfo) {
     ColumnInfo info = (ColumnInfo) obj;
     return getTypeString().equals(info.getTypeString());
   }
   return false;
 }
Exemplo n.º 4
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder('(');
   for (ColumnInfo col : signature) {
     sb.append(col.toString());
   }
   sb.append(')');
   return sb.toString();
 }
Exemplo n.º 5
0
 @Override
 public String getUniqueHeaderColumnName(String proposedName) {
   for (ColumnInfo info : getHeaderColumnInfoList()) {
     this.nameValidator.addExistingName(info.getName());
   }
   String changedName = this.nameValidator.createUniqueName(proposedName);
   String finalName = changedName == null ? proposedName : changedName;
   this.nameValidator.clearExistingNames();
   return finalName;
 }
Exemplo n.º 6
0
  /**
   * Return the names of all the columns of the given table.
   *
   * @param table The name of the table
   * @return The names of all the columns of the given table, as a List. Each element of the list is
   *     a String.
   * @exception SQLException If a database error occurs
   */
  static List<String> getColumnNames(String table) throws SQLException {
    List<String> results = new ArrayList<String>();
    Collection<ColumnInfo> info = getColumnInfo(table);

    for (ColumnInfo col : info) {
      results.add(col.getName());
    }

    return results;
  }
Exemplo n.º 7
0
  /**
   * Return column information for the primary key column, or null if the table has no primary key.
   * We assume there's only one primary key per table; if there are more, only the first one will be
   * returned.
   *
   * @param table The name of the RDBMS table
   * @return A ColumnInfo object, or null if the table has no primary key.
   * @exception SQLException If a database error occurs
   */
  static ColumnInfo getPrimaryKeyColumnInfo(String table) throws SQLException {
    Collection<ColumnInfo> cinfo = getColumnInfo(canonicalize(table));

    for (ColumnInfo info : cinfo) {
      if (info.isPrimaryKey()) {
        return info;
      }
    }

    return null;
  }
Exemplo n.º 8
0
 public TableCellRenderer getCellRenderer(int row, int column) {
   final ColumnInfo<Item, ?> columnInfo =
       getListTableModel().getColumnInfos()[convertColumnIndexToModel(column)];
   final Item item = getListTableModel().getItems().get(convertRowIndexToModel(row));
   final TableCellRenderer renderer =
       columnInfo.getCustomizedRenderer(item, columnInfo.getRenderer(item));
   if (renderer == null) {
     return super.getCellRenderer(row, column);
   } else {
     return renderer;
   }
 }
  /**
   * Construct a ResultList from SQL query ResultSet with at most maxCount rows.
   *
   * @param rs
   * @param maxCount If positive number, at most that number of records will be returned
   * @return
   * @throws SQLException
   */
  public static ResultList fromSqlResultSet(ResultSet rs, int maxCount) throws SQLException {
    logger.fine(new java.util.Date() + ": Process results ...");
    ResultList resList = new ResultList();
    if (rs == null) return resList;
    java.sql.ResultSetMetaData meta = rs.getMetaData();
    int colCnt = meta.getColumnCount();
    ColumnDescriptor desc = new ColumnDescriptor();
    desc.setColumns(new java.util.ArrayList<ColumnInfo>(colCnt));
    for (int i = 1; i <= colCnt; i++) {
      // for now, we only record name
      ColumnInfo col = new ColumnInfo(meta.getColumnName(i));
      int sqlt = meta.getColumnType(i);
      if (sqlt == java.sql.Types.BIGINT
          || sqlt == java.sql.Types.DECIMAL
          || sqlt == java.sql.Types.DOUBLE
          || sqlt == java.sql.Types.FLOAT
          || sqlt == java.sql.Types.INTEGER
          || sqlt == java.sql.Types.NUMERIC
          || sqlt == java.sql.Types.TINYINT
          || sqlt == java.sql.Types.SMALLINT) col.setNumberType(true);
      col.setPosition(i);
      desc.getColumns().add(col);
    }
    resList.setColumnDescriptor(desc);
    int rowCnt = 0;
    List<ColumnInfo> cols = desc.getColumns();
    while (rs.next()) {
      // logger.info(new java.util.Date()+": process "+rowCnt+" rows");
      ResultRow row = new ResultRow();
      row.setColumnDescriptor(desc);
      java.util.ArrayList<String> cols2 = new java.util.ArrayList<String>(colCnt);
      row.setColumns(cols2);
      for (int i = 1; i <= colCnt; i++) {
        String val = rs.getString(i);

        if (cols.get(i - 1).isNumberType() && val != null && val.startsWith("."))
          val = "0" + val; // prefix Oracle float number with 0 if starting with "."
        else if (cols.get(i - 1).isNumberType() && val != null && val.startsWith("-."))
          val = val.replace("-.", "-0."); // prefix Oracle float number with 0 if starting with "."

        cols2.add(val);
      }
      resList.addRow(row);
      rowCnt++;
      if (maxCount > 0 && rowCnt >= maxCount) break;
    }
    logger.fine(new java.util.Date() + ": Process results done: " + resList.getRows().size());
    return resList;
  }
 /**
  * Used for text output
  *
  * @param rList
  */
 public static void updateColumnWidth(ResultList rList) {
   if (rList == null || rList.getColumnDescriptor() == null || rList.getRows().size() == 0) return;
   List<ColumnInfo> cols = rList.getColumnDescriptor().getColumns();
   for (ColumnInfo col : cols) {
     col.setMaxLength(col.getName().length());
   }
   for (ResultRow row : rList.getRows()) {
     List<String> l = row.getColumns();
     for (int i = 0; i < l.size(); i++) {
       String s = l.get(i);
       if (s != null && s.length() > cols.get(i).getMaxLength())
         cols.get(i).setMaxLength(s.length());
     }
   }
 }
Exemplo n.º 11
0
  /** @param rootPath */
  public void setRootPath(String path) {
    this.rootPath = path;

    // Need to walk through the ColumnInfo objects and have them re-set their paths
    for (ColumnInfo colInfo : getBodyColumnInfoList()) {
      colInfo.setRootPath(this.rootPath);
    }

    // Need to walk through the ColumnInfo objects and have them re-set their paths
    for (ColumnInfo colInfo : getHeaderColumnInfoList()) {
      colInfo.setRootPath(this.rootPath);
    }

    setChanged(true);
  }
Exemplo n.º 12
0
  /**
   * Constructor
   *
   * @param table The name of the database table containing this row.
   * @param columns A list of column names. Each member of the List is a String. After construction,
   *     the list of columns is fixed; attempting to access a column not in the list will cause an
   *     IllegalArgumentException to be thrown.
   */
  public TableRow(String table, List<String> columns) {
    this.table = table;

    for (String column : columns) {
      String canonicalized = ColumnInfo.canonicalize(column);
      data.put(canonicalized, NULL_OBJECT);
      changed.put(canonicalized, Boolean.TRUE);
    }
  }
Exemplo n.º 13
0
  public void updateColumnSizes() {
    final JTableHeader header = getTableHeader();
    final TableCellRenderer defaultRenderer = header == null ? null : header.getDefaultRenderer();

    final RowSorter<? extends TableModel> sorter = getRowSorter();
    final List<? extends RowSorter.SortKey> current = sorter == null ? null : sorter.getSortKeys();
    ColumnInfo[] columns = getListTableModel().getColumnInfos();
    for (int i = 0; i < columns.length; i++) {
      final ColumnInfo columnInfo = columns[i];
      final TableColumn column = getColumnModel().getColumn(i);
      // hack to get sort arrow included into the renderer component
      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(
            Collections.singletonList(new RowSorter.SortKey(i, SortOrder.ASCENDING)));
      }

      final Component headerComponent =
          defaultRenderer == null
              ? null
              : defaultRenderer.getTableCellRendererComponent(
                  this, column.getHeaderValue(), false, false, 0, 0);

      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(current);
      }
      final Dimension headerSize =
          headerComponent == null ? new Dimension(0, 0) : headerComponent.getPreferredSize();
      final String maxStringValue;
      final String preferredValue;
      if (columnInfo.getWidth(this) > 0) {
        int width = columnInfo.getWidth(this);
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
        column.setMinWidth(width);
      } else if ((maxStringValue = columnInfo.getMaxStringValue()) != null) {
        int width =
            getFontMetrics(getFont()).stringWidth(maxStringValue) + columnInfo.getAdditionalWidth();
        width = Math.max(width, headerSize.width);
        column.setPreferredWidth(width);
        column.setMaxWidth(width);
      } else if ((preferredValue = columnInfo.getPreferredStringValue()) != null) {
        int width =
            getFontMetrics(getFont()).stringWidth(preferredValue) + columnInfo.getAdditionalWidth();
        width = Math.max(width, headerSize.width);
        column.setPreferredWidth(width);
      }
    }
  }
Exemplo n.º 14
0
  private static String printFieldIdentsAndTypes(List fieldIdents, Map columnInfos) {
    StringBuffer buf = new StringBuffer();
    Iterator fieldItr = fieldIdents.iterator();
    while (fieldItr.hasNext()) {
      String aField = (String) fieldItr.next();
      if (aField != null) {
        buf.append("["); // $NON-NLS-1$
        buf.append(aField);
        buf.append(" - ["); // $NON-NLS-1$
        ColumnInfo colInfo = (ColumnInfo) columnInfos.get(aField);
        buf.append(colInfo.getDataType());
        buf.append(", "); // $NON-NLS-1$
        buf.append(colInfo.getJavaClass());
        buf.append("]"); // $NON-NLS-1$
      }
      buf.append("] "); // $NON-NLS-1$
    }

    return buf.toString();
  }
Exemplo n.º 15
0
  private String canonicalizeAndCheck(String column) {
    if (data.containsKey(column)) {
      return column;
    }

    String canonicalized = ColumnInfo.canonicalize(column);
    if (data.containsKey(canonicalized)) {
      return canonicalized;
    }

    throw new IllegalArgumentException("No such column '" + canonicalized + "'");
  }
Exemplo n.º 16
0
  /**
   * Add a new field into this result set. The field will be inserted in the order of the parameters
   * in the select statement if those parameters were specified upon construction of the result set;
   * otherwise, the field will be appended to the result set.
   *
   * <p>
   *
   * @param info The column information.
   */
  public void addField(ColumnInfo info) {
    // Add to ordered list of fields
    if (fields == null) {
      fields = new ArrayList();
    }
    fields.add(info.getName());

    // Save column information
    if (columnInfos == null) {
      columnInfos = new HashMap();
    }
    columnInfos.put(info.getName(), info);

    // Add new field to each record
    if (records != null) {
      for (int i = 0; i < records.size(); i++) {
        List record = (List) records.get(i);
        record.add(null);
      }
    }
  }
Exemplo n.º 17
0
  /**
   * Update changes to the RDBMS. Note that if the update fails, the values in the row will NOT be
   * reverted.
   *
   * @param context Current DSpace context
   * @param row The row to update
   * @return The number of rows affected (1 or 0)
   * @exception SQLException If a database error occurs
   */
  public static int update(Context context, TableRow row) throws SQLException {
    String table = row.getTable();

    StringBuilder sql = new StringBuilder().append("update ").append(table).append(" set ");

    List<ColumnInfo> columns = new ArrayList<ColumnInfo>();
    ColumnInfo pk = getPrimaryKeyColumnInfo(table);
    Collection<ColumnInfo> info = getColumnInfo(table);

    String separator = "";
    for (ColumnInfo col : info) {
      // Only update this column if it has changed
      if (!col.isPrimaryKey()) {
        if (row.hasColumnChanged(col.getName())) {
          sql.append(separator).append(col.getName()).append(" = ?");
          columns.add(col);
          separator = ", ";
        }
      }
    }

    // Only execute the update if there is anything to update
    if (columns.size() > 0) {
      sql.append(" where ").append(pk.getName()).append(" = ?");
      columns.add(pk);

      return executeUpdate(context.getDBConnection(), sql.toString(), columns, row);
    }

    return 1;
  }
Exemplo n.º 18
0
 /**
  * Get the HTML that comes before the column text.
  *
  * @return The HTML that comes before the column text.
  */
 public String getHeaderCellPreProcess(ColumnInfo columnInfo, ValueListInfo info) {
   StringBuffer sb = new StringBuffer();
   sb.append("\n    <th");
   if (useNoWrap) {
     sb.append(" nowrap=\"true\"");
   }
   if (columnInfo != null) {
     if (columnInfo.getToolTip() != null) {
       sb.append(" title=\"")
           .append(columnInfo.getToolTip())
           .append("\""); // html attribute title renderes a toolTip
     }
     if (columnInfo.getAttributes() != null) {
       sb.append(" ").append(columnInfo.getAttributes());
     }
   }
   sb.append(">");
   if (usePadding) {
     sb.append("&nbsp;");
   }
   return sb.toString();
 }
Exemplo n.º 19
0
  /**
   * Renders a link as a header of the column if the sorting is enabled. Subclasses can overide or
   * extend the method to provide different behaviour.
   *
   * @param sb StringBuffer to render into
   * @param columnInfo The ColumnInfo.
   * @param tableInfo The TableInfo.
   * @param info The ValueListInfo.
   * @param parameters Map of parameters
   */
  protected void renderHeaderLabelLink(
      StringBuffer sb,
      ColumnInfo columnInfo,
      TableInfo tableInfo,
      ValueListInfo info,
      Map parameters) {

    // String column = info.getSortingColumn();
    // Integer direction = info.getSortingDirection();

    sb.append("<a href=\"").append(tableInfo.getUrl());

    sb.append(
        tableInfo.getConfig().getLinkEncoder().encode(tableInfo.getPageContext(), parameters));

    sb.append("\">").append(columnInfo.getTitle()).append("</a>");
  }
Exemplo n.º 20
0
  public void setOrdinality(ColumnInfo columnInfo, boolean value) {
    // Need to synchronize the setting of this value for a column info.
    // Basically only ONE Column can be set to TRUE .... AND ... the datatype MUST be an INTEGER

    if (value == false) {
      // Only need to set the columnInfo value
      columnInfo.setOrdinality(false);
    } else {
      for (ColumnInfo info : this.bodyColumnInfoList) {
        if (!(info == columnInfo)) {
          if (info.getOrdinality()) {
            info.setOrdinality(false);
          }
        }
      }

      if (!columnInfo.getDatatype().equalsIgnoreCase(IWsdlColumnInfo.INTEGER_DATATYPE)) {
        columnInfo.setDatatype(IWsdlColumnInfo.INTEGER_DATATYPE);
      }
      columnInfo.setOrdinality(true);
    }
    setChanged(true);
  }
Exemplo n.º 21
0
 public <T> List<T> select(
     Class<T> clazz, String query, Map<String, Object> params, Integer offset, Integer limit)
     throws SQLException, InstantiationException, IllegalAccessException {
   List<T> resultList = new ArrayList<T>();
   List<Object> paramList = new ArrayList<Object>();
   // add offset and limit
   addRange(query, params, offset, limit);
   Pattern pattern = Pattern.compile("/#[\\0x20-0x7F]+?[\\0x20-0x7F]#/", Pattern.DOTALL);
   Matcher matcher = pattern.matcher(query);
   while (matcher.find()) {
     int start = matcher.start();
     int end = matcher.end();
     Object param = params.get(query.substring(start + 2, end - 2).trim());
     query = query.substring(0, start) + "?" + query.substring(end, query.length());
     paramList.add(params.get(param));
   }
   PreparedStatement stmt = this.connection.prepareStatement(query);
   setParameter(stmt, paramList);
   ResultSet rs = stmt.executeQuery();
   ResultSetMetaData meta = rs.getMetaData();
   Map<String, ColumnInfo> columnMap = new HashMap<String, ColumnInfo>();
   int columnLength = meta.getColumnCount();
   for (int i = 0; i < columnLength; i++) {
     ColumnInfo columnInfo = new ColumnInfo();
     columnInfo.setColumnName(meta.getColumnLabel(i));
     columnInfo.setColumnType(meta.getColumnTypeName(i));
     columnInfo.setColumnClass(meta.getColumnClassName(i));
     columnMap.put(columnInfo.getColumnName(), columnInfo);
   }
   while (rs.next()) {
     T entity = clazz.newInstance();
     Field[] fields = clazz.getFields();
     for (Field field : fields) {
       ColumnInfo columnInfo = columnMap.get(field.getAnnotation(Column.class).name());
       if (columnInfo != null) {
         if (String.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getString(columnInfo.getColumnName()));
         } else if (Integer.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getInt(columnInfo.getColumnName()));
         } else if (Double.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getDouble(columnInfo.getColumnName()));
         } else if (Long.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getLong(columnInfo.getColumnName()));
         } else if (Float.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getFloat(columnInfo.getColumnName()));
         } else if (Short.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getShort(columnInfo.getColumnName()));
         } else if (Byte.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getByte(columnInfo.getColumnName()));
         } else if (Boolean.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getBoolean(columnInfo.getColumnName()));
         } else if (Date.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getDate(columnInfo.getColumnName()));
         } else if (Timestamp.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getTimestamp(columnInfo.getColumnName()));
         } else if (Object.class.getName().equals(columnInfo.getColumnClass())) {
           field.set(entity, rs.getObject(columnInfo.getColumnName()));
         }
       }
     }
     resultList.add(entity);
   }
   return resultList;
 }
Exemplo n.º 22
0
  /**
   * Read metadata about a table from the database.
   *
   * @param table The RDBMS table.
   * @return A map of information about the columns. The key is the name of the column, a String;
   *     the value is a ColumnInfo object.
   * @exception SQLException If there is a problem retrieving information from the RDBMS.
   */
  private static Map<String, ColumnInfo> retrieveColumnInfo(String table) throws SQLException {
    Connection connection = null;
    ResultSet pkcolumns = null;
    ResultSet columns = null;

    try {
      String schema = ConfigurationManager.getProperty("db.schema");
      if (StringUtils.isBlank(schema)) {
        schema = null;
      }
      String catalog = null;

      int dotIndex = table.indexOf('.');
      if (dotIndex > 0) {
        catalog = table.substring(0, dotIndex);
        table = table.substring(dotIndex + 1, table.length());
        log.warn("catalog: " + catalog);
        log.warn("table: " + table);
      }

      connection = getConnection();

      DatabaseMetaData metadata = connection.getMetaData();
      Map<String, ColumnInfo> results = new HashMap<String, ColumnInfo>();

      int max = metadata.getMaxTableNameLength();
      String tname = ((max > 0) && (table.length() >= max)) ? table.substring(0, max - 1) : table;

      pkcolumns = metadata.getPrimaryKeys(catalog, schema, tname);

      Set<String> pks = new HashSet<String>();

      while (pkcolumns.next()) {
        pks.add(pkcolumns.getString(4));
      }

      columns = metadata.getColumns(catalog, schema, tname, null);

      while (columns.next()) {
        String column = columns.getString(4);
        ColumnInfo cinfo = new ColumnInfo();
        cinfo.setName(column);
        cinfo.setType((int) columns.getShort(5));

        if (pks.contains(column)) {
          cinfo.setIsPrimaryKey(true);
        }

        results.put(column, cinfo);
      }

      return Collections.unmodifiableMap(results);
    } finally {
      if (pkcolumns != null) {
        try {
          pkcolumns.close();
        } catch (SQLException sqle) {
        }
      }

      if (columns != null) {
        try {
          columns.close();
        } catch (SQLException sqle) {
        }
      }

      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException sqle) {
        }
      }
    }
  }
Exemplo n.º 23
0
  private static void loadParameters(
      PreparedStatement statement, Collection<ColumnInfo> columns, TableRow row)
      throws SQLException {
    int count = 0;
    for (ColumnInfo info : columns) {
      count++;
      String column = info.getCanonicalizedName();
      int jdbctype = info.getType();

      if (row.isColumnNull(column)) {
        statement.setNull(count, jdbctype);
      } else {
        switch (jdbctype) {
          case Types.BOOLEAN:
          case Types.BIT:
            statement.setBoolean(count, row.getBooleanColumn(column));
            break;

          case Types.INTEGER:
            if (isOracle) {
              statement.setLong(count, row.getLongColumn(column));
            } else {
              statement.setInt(count, row.getIntColumn(column));
            }
            break;

          case Types.NUMERIC:
          case Types.DECIMAL:
            statement.setLong(count, row.getLongColumn(column));
            // FIXME should be BigDecimal if TableRow supported that
            break;

          case Types.BIGINT:
            statement.setLong(count, row.getLongColumn(column));
            break;

          case Types.CLOB:
            if (isOracle) {
              // Support CLOBs in place of TEXT columns in Oracle
              statement.setString(count, row.getStringColumn(column));
            } else {
              throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype);
            }
            break;

          case Types.VARCHAR:
            statement.setString(count, row.getStringColumn(column));
            break;

          case Types.DATE:
            statement.setDate(count, new java.sql.Date(row.getDateColumn(column).getTime()));
            break;

          case Types.TIME:
            statement.setTime(count, new Time(row.getDateColumn(column).getTime()));
            break;

          case Types.TIMESTAMP:
            statement.setTimestamp(count, new Timestamp(row.getDateColumn(column).getTime()));
            break;

          default:
            throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype);
        }
      }
    }
  }
Exemplo n.º 24
0
  /**
   * Generic version of row insertion with separate id get / insert
   *
   * @param context
   * @param row
   * @return
   * @throws SQLException
   */
  private static int doInsertGeneric(Context context, TableRow row) throws SQLException {
    int newID = -1;
    String table = row.getTable();
    PreparedStatement statement = null;
    ResultSet rs = null;

    try {
      // Get an ID (primary key) for this row by using the "getnextid"
      // SQL function in Postgres, or directly with sequences in Oracle
      if (isOracle) {
        statement =
            context
                .getDBConnection()
                .prepareStatement("SELECT " + table + "_seq" + ".nextval FROM dual");
      } else {
        statement = context.getDBConnection().prepareStatement("SELECT getnextid(?) AS result");
        loadParameters(statement, new Object[] {table});
      }
      rs = statement.executeQuery();
      rs.next();
      newID = rs.getInt(1);
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException sqle) {
        }
      }

      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException sqle) {
        }
      }
    }

    if (newID < 0) {
      throw new SQLException("Unable to retrieve sequence ID");
    }

    // Set the ID in the table row object
    row.setColumn(getPrimaryKeyColumn(table), newID);
    Collection<ColumnInfo> info = getColumnInfo(table);

    String sql = insertSQL.get(table);
    if (sql == null) {
      StringBuilder sqlBuilder =
          new StringBuilder().append("INSERT INTO ").append(table).append(" ( ");

      boolean firstColumn = true;
      for (ColumnInfo col : info) {
        if (firstColumn) {
          sqlBuilder.append(col.getName());
          firstColumn = false;
        } else {
          sqlBuilder.append(",").append(col.getName());
        }
      }

      sqlBuilder.append(") VALUES ( ");

      // Values to insert
      firstColumn = true;
      for (int i = 0; i < info.size(); i++) {
        if (firstColumn) {
          sqlBuilder.append("?");
          firstColumn = false;
        } else {
          sqlBuilder.append(",").append("?");
        }
      }

      // Watch the syntax
      sqlBuilder.append(")");
      sql = sqlBuilder.toString();
      insertSQL.put(table, sql);
    }

    execute(context.getDBConnection(), sql, info, row);
    return newID;
  }
Exemplo n.º 25
0
  /**
   * Postgres-specific row insert, combining getnextid() and insert into single statement for
   * efficiency
   *
   * @param context
   * @param row
   * @return
   * @throws SQLException
   */
  private static int doInsertPostgres(Context context, TableRow row) throws SQLException {
    String table = row.getTable();

    Collection<ColumnInfo> info = getColumnInfo(table);
    Collection<ColumnInfo> params = new ArrayList<ColumnInfo>();

    String primaryKey = getPrimaryKeyColumn(table);
    String sql = insertSQL.get(table);

    boolean firstColumn = true;
    boolean foundPrimaryKey = false;
    if (sql == null) {
      // Generate SQL and filter parameter columns
      StringBuilder insertBuilder = new StringBuilder("INSERT INTO ").append(table).append(" ( ");
      StringBuilder valuesBuilder = new StringBuilder(") VALUES ( ");
      for (ColumnInfo col : info) {
        if (firstColumn) {
          firstColumn = false;
        } else {
          insertBuilder.append(",");
          valuesBuilder.append(",");
        }

        insertBuilder.append(col.getName());

        if (!foundPrimaryKey && col.isPrimaryKey()) {
          valuesBuilder.append("getnextid('").append(table).append("')");
          foundPrimaryKey = true;
        } else {
          valuesBuilder.append('?');
          params.add(col);
        }
      }

      sql =
          insertBuilder
              .append(valuesBuilder.toString())
              .append(") RETURNING ")
              .append(getPrimaryKeyColumn(table))
              .toString();
      insertSQL.put(table, sql);
    } else {
      // Already have SQL, just filter parameter columns
      for (ColumnInfo col : info) {
        if (!foundPrimaryKey && col.isPrimaryKey()) {
          foundPrimaryKey = true;
        } else {
          params.add(col);
        }
      }
    }

    PreparedStatement statement = null;

    if (log.isDebugEnabled()) {
      log.debug("Running query \"" + sql + "\"");
    }

    ResultSet rs = null;
    try {
      statement = context.getDBConnection().prepareStatement(sql);
      loadParameters(statement, params, row);
      rs = statement.executeQuery();
      rs.next();
      return rs.getInt(1);
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException sqle) {
        }
      }

      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException sqle) {
        }
      }
    }
  }
  public void updateColumnSizes() {
    final JTableHeader header = getTableHeader();
    final TableCellRenderer defaultRenderer = header == null ? null : header.getDefaultRenderer();

    final RowSorter<? extends TableModel> sorter = getRowSorter();
    final List<? extends RowSorter.SortKey> current = sorter == null ? null : sorter.getSortKeys();
    ColumnInfo[] columns = getListTableModel().getColumnInfos();
    int[] sizeMode = new int[columns.length];
    int[] headers = new int[columns.length];
    int[] widths = new int[columns.length];
    int allColumnWidth = 0;
    int varCount = 0;

    // calculate
    for (int i = 0; i < columns.length; i++) {
      final ColumnInfo columnInfo = columns[i];
      final TableColumn column = getColumnModel().getColumn(i);
      // hack to get sort arrow included into the renderer component
      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(
            Collections.singletonList(new RowSorter.SortKey(i, SortOrder.ASCENDING)));
      }

      final Component headerComponent =
          defaultRenderer == null
              ? null
              : defaultRenderer.getTableCellRendererComponent(
                  this, column.getHeaderValue(), false, false, 0, 0);

      if (sorter != null && columnInfo.isSortable()) {
        sorter.setSortKeys(current);
      }
      if (headerComponent != null) {
        headers[i] = headerComponent.getPreferredSize().width;
      }
      final String maxStringValue;
      final String preferredValue;
      if (columnInfo.getWidth(this) > 0) {
        sizeMode[i] = 1;
        int width = columnInfo.getWidth(this);
        widths[i] = width;
      } else if ((maxStringValue = columnInfo.getMaxStringValue()) != null) {
        sizeMode[i] = 2;
        widths[i] =
            getFontMetrics(getFont()).stringWidth(maxStringValue) + columnInfo.getAdditionalWidth();
        varCount++;
      } else if ((preferredValue = columnInfo.getPreferredStringValue()) != null) {
        sizeMode[i] = 3;
        widths[i] =
            getFontMetrics(getFont()).stringWidth(preferredValue) + columnInfo.getAdditionalWidth();
        varCount++;
      }
      allColumnWidth += widths[i];
    }

    // apply: distribute available space between resizable columns
    //        and make sure that header will fit as well
    int viewWidth = getParent() != null ? getParent().getWidth() : getWidth();
    double gold = 0.5 * (3 - Math.sqrt(5));
    int addendum =
        varCount == 0 || viewWidth < allColumnWidth
            ? 0
            : (int)
                    ((allColumnWidth < gold * viewWidth
                            ? gold * viewWidth
                            : allColumnWidth < (1 - gold) * viewWidth
                                ? (1 - gold) * viewWidth
                                : viewWidth)
                        - allColumnWidth)
                / varCount;

    for (int i = 0; i < columns.length; i++) {
      TableColumn column = getColumnModel().getColumn(i);
      int width = widths[i];
      if (sizeMode[i] == 1) {
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
        column.setMinWidth(width);
      } else if (sizeMode[i] == 2) {
        width = Math.max(width + addendum, headers[i]);
        column.setPreferredWidth(width);
        column.setMaxWidth(width);
      } else if (sizeMode[i] == 3) {
        width = Math.max(width + addendum, headers[i]);
        column.setPreferredWidth(width);
      }
    }
  }
Exemplo n.º 27
0
  /**
   * Return the name of the primary key column in the given table. We assume there's only one
   * primary key per table; if there are more, only the first one will be returned.
   *
   * @param table The name of the RDBMS table
   * @return The name of the primary key column, or null if the table has no primary key.
   * @exception SQLException If a database error occurs
   */
  protected static String getPrimaryKeyColumn(String table) throws SQLException {
    ColumnInfo info = getPrimaryKeyColumnInfo(table);

    return (info == null) ? null : info.getName();
  }
Exemplo n.º 28
0
  /**
   * Formats the text to be displayed as the header by wraping it in a link if sorting is enabled.
   * Alt (hint) is localized, please define in your property file for messages the property
   * "sorting"
   *
   * @param columnInfo The ColumnInfo.
   * @param tableInfo The TableInfo.
   * @param info The ValueListInfo.
   * @return The formated HTML.
   */
  public String getHeaderLabel(
      ColumnInfo columnInfo, TableInfo tableInfo, ValueListInfo info, Map includeParameters) {

    ValueListConfigBean config = tableInfo.getConfig();
    Map parameters = new HashMap(includeParameters);

    if (columnInfo.getDefaultSort() != null) {
      // Get the current sort column and direction.
      String column = info.getSortingColumn();
      Integer direction = info.getSortingDirection();

      parameters.put(
          ValueListInfo.PAGING_NUMBER_PER + tableInfo.getId(),
          String.valueOf(info.getPagingNumberPer()));
      parameters.put(ValueListInfo.PAGING_PAGE + tableInfo.getId(), "1");
      parameters.put(
          ValueListInfo.SORT_COLUMN + tableInfo.getId(), columnInfo.getAdapterPropertyName());
      parameters.put(
          ValueListInfo.SORT_DIRECTION + tableInfo.getId(),
          ((columnInfo.getAdapterPropertyName().equals(column))
              ? (ValueListInfo.ASCENDING.equals(direction)
                  ? ValueListInfo.DESCENDING
                  : ValueListInfo.ASCENDING)
              : columnInfo.getDefaultSort()));

      if (info.isFocusEnabled()) {
        parameters.put(
            ValueListInfo.DO_FOCUS + tableInfo.getId(), info.isDoFocusAgain() ? "true" : "false");
        if (info.getFocusProperty() != null) {
          parameters.put(ValueListInfo.FOCUS_PROPERTY + tableInfo.getId(), info.getFocusProperty());
        }
        if (info.getFocusValue() != null) {
          parameters.put(ValueListInfo.FOCUS_VALUE + tableInfo.getId(), info.getFocusValue());
        }
      }

      StringBuffer sb = new StringBuffer();

      renderHeaderLabelLink(sb, columnInfo, tableInfo, info, parameters);

      if (columnInfo.getAdapterPropertyName().equals(column)) {
        if (usePadding) {
          sb.append("&nbsp;");
        }
        sb.append("<img src=\"")
            .append(getImageHome((HttpServletRequest) tableInfo.getPageContext().getRequest()))
            .append("/sort(");
        sb.append(
            (ValueListInfo.ASCENDING.equals(direction)
                ? ValueListInfo.DESCENDING
                : ValueListInfo.ASCENDING));
        sb.append(").png\" border=\"0\"/>");
      } else if (columnInfo.getDefaultSort() != null) {
        Locale locale =
            config
                .getLocaleResolver()
                .resolveLocale((HttpServletRequest) (tableInfo.getPageContext().getRequest()));
        String altSort;
        try {
          altSort =
              config
                  .getDisplayHelper()
                  .help(
                      tableInfo.getPageContext(),
                      config.getMessageSource().getMessage("sorting", null, "Sort", locale));
        } catch (JspException e) {
          LOGGER.error(
              "getHeaderLabel() - Error getting property 'sorting' : "
                  + e.getMessage()
                  + " Locale locale = "
                  + locale
                  + ", String column = "
                  + column
                  + " using defalt hint for sorting images.");

          altSort = "Sort";
        }

        sb.append(((usePadding) ? "&nbsp;" : ""))
            .append("<img alt=\"")
            .append(altSort)
            .append("\" src=\"")
            .append(getImageHome((HttpServletRequest) tableInfo.getPageContext().getRequest()))
            .append("/sort(null).png\" border=\"0\"/>");
      }

      return sb.toString();

    } else {
      return columnInfo.getTitle();
    }
  }
Exemplo n.º 29
0
 /**
  * Javaのデータ型を返す
  *
  * @return
  */
 public String getJavaDataType() {
   return ColumnInfo.convertDataType(this.dataType);
 }
Exemplo n.º 30
0
 public ColumnInfo getColumnDetails(JProperty property) {
   ColumnInfo answer = new ColumnInfo();
   answer.setCardinality("0..1");
   JAnnotation ann = property.getAnnotation("hibernate.map");
   if (ann != null) {
     answer.setTableName(stringValue(ann, "table"));
     answer.setQualifiedTypeName(
         annotationValue(property, "hibernate.collection-composite-element", "class"));
     answer.setCardinality("0..N");
     return answer;
   }
   ann = property.getAnnotation("hibernate.set");
   if (ann != null) {
     answer.setTableName(stringValue(ann, "table"));
     answer.setQualifiedTypeName(
         annotationValue(property, "hibernate.collection-many-to-many", "class"));
     answer.setCardinality("0..N");
     return answer;
   }
   ann = property.getAnnotation("hibernate.bag");
   if (ann != null) {
     answer.setTableName(stringValue(ann, "table"));
     answer.setQualifiedTypeName(
         annotationValue(property, "hibernate.collection-many-to-many", "class"));
     answer.setCardinality("0..N");
     return answer;
   }
   ann = property.getAnnotation("hibernate.many-to-one");
   if (ann != null) {
     answer.setQualifiedTypeName(stringValue(ann, "class"));
     answer.setForeignKey(stringValue(ann, "foreignKey"));
   }
   ann = property.getAnnotation("hibernate.property");
   if (ann != null) {
     answer.setColumnName(stringValue(ann, "column"));
     answer.setQualifiedTypeName(stringValue(ann, "type"));
     answer.setLength(intValue(ann, "length"));
     answer.setNotNull(booleanValue(ann, "not-null"));
     if (answer.isNotNull()) {
       answer.setCardinality("1..1");
     }
   }
   return answer;
 }