dataform.sql.query.DefaultTable.java Source code

Java tutorial

Introduction

Here is the source code for dataform.sql.query.DefaultTable.java

Source

/*
 * Copyright 2013 Georges Stephan
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dataform.sql.query;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import dataform.globals.Globals;
import dataform.sql.Column;

/**
 * 
 * Should work with most SQL databases.
 * 
 * @author Georges Stephan  
 */
public abstract class DefaultTable implements Table, Serializable {
    private static Logger logger = Logger.getLogger(DefaultTable.class.getName());
    private int maxRows = -1; // Read all records
    private int keyColumnCount = 0;
    private int order = 0;
    private String tableName;
    private String description;
    private Vector<Column> columns = new Vector<Column>();
    private Vector<String> orderByColumns = new Vector<String>();
    private WhereClause whereClause;
    private WhereClause staticWhereClause;

    private Map<String, Integer> columnWidth = new HashMap<String, Integer>();

    public DefaultTable() {
    }

    public void addColumn(Column column) throws Exception {
        if (column == null)
            throw new Exception("Column should not be null.");
        if (column.getTable() != null && !column.getTable().equals(this)) {
            logger.warning("The column " + column.getColumnName() + " was already linked to the table "
                    + column.getTable().getTableName() + ".");
        }
        column.setTable(this);
        columns.add(column);
        if (column.isKeyColumn()) {
            keyColumnCount++;
        }
    }

    public void addOrderByColumn(String columnName) {
        if (columnName != null && columnName.trim().length() != 0)
            this.orderByColumns.add(columnName);
    }

    public void addWhereClause(WhereClause whereClause) {
        if (whereClause != null) {
            try {
                this.whereClause.addWhereClause(whereClause);
            } catch (Exception e) {
                if (logger.getLevel() == Level.FINEST)
                    e.printStackTrace();
                logger.log(Level.WARNING, e.getMessage());
            }
        } else {
            logger.log(Level.WARNING, "WhereClause is null.");
        }
    }

    public void addWhereClause(WhereClause.LogicalOperator logicalOperator, String whereCondition)
            throws Exception {
        whereClause.addWhereClause(logicalOperator, whereCondition);
    }

    /**
     * Use this class to build a Combobox based on a foreign  key.
     * 
     * @param columnIndex the column to keep when cloning. NOTE : The key flag is removed from this column
     * @return a copy of the current class, with all but the given column and it's keys.
     */
    public Table cloneKeysAndColumn(int columnIndex) throws Exception {
        if (columnIndex > getColumnCount())
            throw new ArrayIndexOutOfBoundsException();
        Table table = Globals.getGlobals().getDBManager().getTableInstance();
        table.setTableName(getTableName());
        for (int x = 0; x < getColumnCount(); x++) {
            if (x == columnIndex) {
                // The cloning will remove the key flag from the to be kept column
                table.addColumn(new Column(getColumn(x).getColumnName(),
                        getColumn(x).getColumnDescription() == null ? "" : getColumn(x).getColumnDescription(),
                        false, getColumn(x).getSQLColumnType()));
            } else if (getColumn(x).isKeyColumn()) {
                table.addColumn(getColumn(x));
            }
        }
        table.replaceWhereClause(getWhereClause());
        return table;
    }

    /**
     * Use this class to build a Combobox based on a foreign  key.
     * 
     * @param columnName the name of the column to keep when cloning
     * @return a copy of the current class, with all but the given column and it's keys.
     */
    public Table cloneKeysAndColumn(String columnName) throws Exception {
        int x = 0;
        boolean found = false;
        do {
            if (getColumn(x).getColumnName().equals(columnName)) {
                found = true;
            } else {
                x++;
            }
        } while (!found && x < getColumnCount());

        if (found) {
            return cloneKeysAndColumn(x);
        }
        throw new Exception("The column " + columnName + " was not found.");
    }

    @Override
    public boolean equals(Object o) {
        if (o != null && o instanceof Table) {
            if (((Table) o).getTableName().equals(getTableName()))
                return true;
        }
        return false;
    }

    public Column getColumn(int columnIndex) {
        return (columns.elementAt(columnIndex));
    }

    public Column getColumn(String sqlColumnName) {
        for (int i = 0; i < getColumnCount(); i++) {
            if (getColumn(i).getColumnName().equalsIgnoreCase(sqlColumnName)) {
                return getColumn(i);
            }
        }
        return null;
    }

    /**
     * @return the number of columns in this table.
     */
    public int getColumnCount() {
        return (this.columns.size());
    }

    /**
     * @return the name of the column for the given index.
     */
    public String getColumnName(int index) {
        return ((columns.elementAt(index)).getColumnName());
    }

    public int getColumnWidth(String columnName) {
        int thisColumnWidth = 7;
        if (columnWidth.get(columnName) != null) {
            thisColumnWidth = ((columnWidth.get(columnName))).intValue();
        } else {
            logger.log(Level.WARNING, "Column " + columnName + " did not have a width assigned.");
        }
        return thisColumnWidth;
    }

    /**
     * Return an SQL Count Query that counts the number of rows in this table, while considering the where clause.
     */
    public String getCountRowQuery() throws Exception {
        Count countQuery = new Count(getTableName());
        countQuery.setWhereClause(getWhereClause());
        return (countQuery.toString());
    }

    public String getDeleteQuery(WhereClause wc) {
        // TODO consider adding the static where clause ???
        Delete delete = new Delete(getTableName());
        delete.setWhereClause(wc);
        return delete.toString();
    }

    /**
     * Return the key column at the specified location
     * 
     * @param keyColumnIndex
     * @return
     */
    public Column getKeyColumn(int keyColumnIndex) {
        boolean loop = true;
        int keyColumn = 0;
        Column column = null;
        for (int x = 0; x < getColumnCount() && loop; x++) {
            if (getColumn(x).isKeyColumn()) {
                keyColumn++;
            }

            if ((keyColumn - 1) == keyColumnIndex) {
                loop = false;
                column = getColumn(x);
            }
        }
        return (column);
    }

    /**
     * Return the number of key columns in this table
     * 
     */
    public int getKeyColumnCount() {
        int keyColumnCount = 0;
        for (int x = 0; x < getColumnCount(); x++) {
            if (getColumn(x).isKeyColumn())
                keyColumnCount++;
        }
        return keyColumnCount;
    }

    public int getNumberOfRowsToRead() {
        return (maxRows);
    }

    public int getOrder() {
        return this.order;
    }

    public String getSelectQuery() throws Exception {
        Select selectQuery = new Select(getTableName(), getWhereClause());
        for (int x = 0; x < getColumnCount(); x++) {
            selectQuery.addColumn(getColumn(x));
        }
        for (int y = 0; y < orderByColumns.size(); y++) {
            selectQuery.addOrderByColumnName(orderByColumns.elementAt(y));
        }
        return (selectQuery.toString());
    }

    public String getTableDescription() {
        return this.description == null ? getTableName() : this.description;
    }

    public String getTableName() {
        return (this.tableName);
    }

    public String getTableTitle() {
        return getTableDescription();
    }

    /**
     * @return the number of characters in every record of this table
     */
    public int getTotalColumnsWidth() {
        int totalWidth = 0;
        for (int x = 0; x < getColumnCount(); x++) {
            totalWidth = totalWidth + getColumnWidth(getColumnName(x));
        }
        return totalWidth;
    }

    public WhereClause getWhereClause() throws Exception {
        WhereClause wc = new WhereClause(getTableName());
        if (whereClause != null)
            wc.addWhereClause(whereClause);
        if (staticWhereClause != null)
            wc.addWhereClause(staticWhereClause);
        return (wc);
    }

    public boolean hasForeignColumns() {
        boolean hasForeign = false;
        for (int i = 0; i < getColumnCount() && !hasForeign; i++) {
            if (getColumn(i).isForeignKeyColumn()) {
                hasForeign = true;
            }
        }
        return hasForeign;
    }

    public void replaceWhereClause(WhereClause aWhereClause) throws Exception {
        if (whereClause != null) {
            this.whereClause.reset();
        } else {
            whereClause = new WhereClause(getTableName());
        }
        whereClause.addWhereClause(aWhereClause);
    }

    public void replaceWhereClause(WhereClause.LogicalOperator logicalOperator, String whereCondition)
            throws Exception {
        this.whereClause.reset();
        addWhereClause(logicalOperator, whereCondition);
    }

    public void reset() {
        this.columns.removeAllElements();
        this.keyColumnCount = 0;
        this.maxRows = -1;
        this.whereClause.reset();
    }

    public void setColumnWidth(String columnName, int thisColumnWidth) {
        if (columnName != null) {
            columnWidth.put(columnName, new Integer(thisColumnWidth));
        } else {
            logger.log(Level.WARNING, "The column name cannot be null.");
        }
    }

    public void setMaximumNumberOfRowsToRead(int numberOfRowsToRead) {
        this.maxRows = numberOfRowsToRead;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public void setStaticWhereClause(WhereClause whereClause) {
        this.staticWhereClause = whereClause;
    }

    public void setTableDescription(String description) {
        this.description = description;
    }

    public void setTableName(String tableName) {
        if (tableName != null) {
            this.tableName = tableName.trim();
            this.whereClause = new WhereClause(tableName);
        } else {
            logger.log(Level.SEVERE, "The name of the table cannot be null");
        }
    }

    public void setTableTitle(String title) {
        this.description = title;
    }

    @Override
    public String toString() {
        return org.apache.commons.lang.builder.ToStringBuilder.reflectionToString(this);
    }

}