Java JTable Row createDBXMLFile(JTable table, String docField, String rowField, Connection con, boolean reuseConnection, String driver, String dsn, String user, String password, String tableName, String whereString, String orderByString, String groupByString, boolean convertCharsToEntites)

Here you can find the source of createDBXMLFile(JTable table, String docField, String rowField, Connection con, boolean reuseConnection, String driver, String dsn, String user, String password, String tableName, String whereString, String orderByString, String groupByString, boolean convertCharsToEntites)

Description

create DBXML File

License

Open Source License

Declaration

public static String createDBXMLFile(JTable table, String docField, String rowField, Connection con,
            boolean reuseConnection, String driver, String dsn, String user, String password, String tableName,
            String whereString, String orderByString, String groupByString, boolean convertCharsToEntites)
            throws Exception 

Method Source Code

//package com.java2s;
/*/*from   w w w .j  ava2  s  . c  om*/
 * Id: 
 *
 * Copyright (C) 2004, Cladonia Ltd. All rights reserved.
 *
 * This software is the proprietary information of Cladonia Ltd.  
 * Use is subject to license terms.
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JTable;

import javax.swing.table.TableColumn;

public class Main {
    public static String[] badChars = { "<", ">", "=", ",", "\"", "&", "[", "]" };
    public static String[] goodChars = { "", "", "", "", "", "", "", "" };

    public static String createDBXMLFile(JTable table, String docField, String rowField, Connection con,
            boolean reuseConnection, String driver, String dsn, String user, String password, String tableName,
            String whereString, String orderByString, String groupByString, boolean convertCharsToEntites)
            throws Exception {

        String rootElement = docField;
        String elementName = rowField;

        StringBuffer toWrite = new StringBuffer("");
        toWrite.append("<?xml version=\"1.0\" encoding=\"" + "UTF-8" + "\"?>\n");
        toWrite.append("<" + rootElement + ">");

        //get the vector of data from the database
        //use 0 for number of rows to get all rows
        Vector data = getRowsFromDatabase(con, 0, reuseConnection, driver, dsn, user, password, tableName,
                whereString, orderByString, groupByString);
        data = removeBadChars(data, convertCharsToEntites);
        //get the headers

        //cycle through vector to add data to xml file
        int rowCount = data.size();

        for (int oCnt = 1; oCnt < rowCount; ++oCnt) {
            String[] rowData = (String[]) data.get(oCnt);
            int columnCount = rowData.length;

            //         add root element
            toWrite.append("\n<" + elementName);
            for (int cCnt = 0; cCnt < columnCount; ++cCnt) {
                TableColumn col = table.getColumnModel().getColumn(cCnt);
                String type = (String) col.getHeaderValue();
                if (type.equalsIgnoreCase("=\"ATTRIBUTE\"")) {
                    toWrite.append(" " + table.getValueAt(0, cCnt) + "=\"" + rowData[cCnt] + "\"");
                }
            }
            toWrite.append(">\n");
            for (int cCnt = 0; cCnt < columnCount; ++cCnt) {
                TableColumn col = table.getColumnModel().getColumn(cCnt);
                String type = (String) col.getHeaderValue();
                if (type.equalsIgnoreCase("<ELEMENT>")) {
                    toWrite.append("\t<" + table.getValueAt(0, cCnt) + ">");
                    toWrite.append(rowData[cCnt]);
                    toWrite.append("</" + table.getValueAt(0, cCnt) + ">\n");
                }
            }
            toWrite.append("</" + elementName + ">");

        }
        toWrite.append("\n</" + rootElement + ">\n");
        return (toWrite.toString());

    }

    public static Vector getRowsFromDatabase(Connection con, int numberOfRows, boolean reuseConnection,
            String driver, String dsn, String user, String password, String tableName, String whereString,
            String orderByString, String groupByString) throws Exception {

        if (reuseConnection == false) {
            //close and reopen connection
            con.close();
            con = getConnection(driver, dsn, user, password);
        }

        Vector temp = new Vector();
        String query = null;
        String[] separated;

        Statement stmt = con.createStatement();

        //allow the setMaxRows to be set
        if (numberOfRows > 0)
            stmt.setMaxRows(numberOfRows);

        query = "select * from " + tableName;

        if (numberOfRows == 0) {
            String whereString1 = whereString;
            String orderByString1 = orderByString;
            String groupByString1 = groupByString;

            //check for whereString
            //System.out.println(">"+whereString+"<"+"\n"+">"+whereString.trim()+"<");
            if (whereString1.trim().length() > 0) {
                final String WHERE = "where ";

                //add it to the query
                if ((whereString1.indexOf(WHERE) > -1) || (whereString1.indexOf(WHERE.toUpperCase()) > -1)) {
                    query += " " + whereString;
                } else {
                    query += " where " + whereString;
                }

            }
            //check for orderbyString
            if (orderByString1.trim().length() > 0) {
                //add it to the query
                final String ORDER_BY = "order by ";
                if ((orderByString1.indexOf(ORDER_BY) > -1)
                        || (orderByString1.indexOf(ORDER_BY.toUpperCase()) > -1)) {
                    query += " " + orderByString;
                } else {
                    query += " order by " + orderByString;
                }

            }
            //check for groupbyString
            if (groupByString1.trim().length() > 0) {
                //add it to the query
                final String GROUP_BY = "group by ";
                if ((groupByString1.indexOf(GROUP_BY) > -1)
                        || (groupByString1.indexOf(GROUP_BY.toUpperCase()) > -1)) {
                    query += " " + groupByString;
                } else {
                    query += " group by " + groupByString;
                }
            }

        }

        ResultSet data = stmt.executeQuery(query);
        ResultSetMetaData rmeta = data.getMetaData();
        separated = new String[rmeta.getColumnCount()];
        //get column names
        for (int ccnt = 1; ccnt < rmeta.getColumnCount() + 1; ++ccnt) {
            separated[ccnt - 1] = rmeta.getColumnName(ccnt);
            //System.out.println(rmeta.getColumnName(ccnt));
        }
        temp.add(separated);
        while (data.next()) {
            String[] sep = new String[rmeta.getColumnCount()];
            for (int cnt = 1; cnt < rmeta.getColumnCount() + 1; ++cnt) {
                sep[cnt - 1] = data.getString(cnt);
            }
            temp.add(sep);
        }

        return (temp);
    }

    public static void removeBadChars(JTable table, boolean skipHeaderBoolean) throws Exception {
        //   for each cell in row, remove bad chars
        int columns = table.getColumnCount();
        int rows = table.getRowCount();
        int startRow = 0;

        cleanHeaderCells(table);
        startRow = 1;

        for (int rCnt = startRow; rCnt < rows; ++rCnt) {
            //      for each row
            for (int cCnt = 0; cCnt < columns; ++cCnt) {
                //         for each column in a row
                if (table.getValueAt(rCnt, cCnt) == null) {
                    //                  set this cell to ""
                    table.setValueAt("", rCnt, cCnt);
                } else {
                    String cellValue = (String) table.getValueAt(rCnt, cCnt);

                    if (cellValue.length() > 0) {

                        String newCellValue = removeBadCharsFromString(cellValue, skipHeaderBoolean);
                        if (!cellValue.equals(newCellValue)) {

                            table.setValueAt(newCellValue, rCnt, cCnt);
                        }
                    } else {
                        //set this cell to ""
                        table.setValueAt("", rCnt, cCnt);
                    }
                }

            }
        }
    }

    public static Vector removeBadChars(Vector data, boolean skipHeaderBoolean) throws Exception {

        //   for each cell in row, remove bad chars
        int rows = data.size();
        int columns = ((String[]) data.get(0)).length;

        for (int rCnt = 0; rCnt < rows; ++rCnt) {
            //      for each row

            boolean rowWasChanged = false;
            String[] rowData = (String[]) data.get(rCnt);
            for (int cCnt = 0; cCnt < columns; ++cCnt) {
                //         for each column in a row
                String cellValue = rowData[cCnt];
                if (cellValue.length() > 0) {
                    String newCellValue = removeBadCharsFromString(cellValue, skipHeaderBoolean);

                    if (!cellValue.equals(newCellValue)) {
                        rowWasChanged = true;
                        rowData[cCnt] = newCellValue;
                    }
                } else {
                    //set this cell to ""
                    rowWasChanged = true;
                    rowData[cCnt] = "";
                }

            }
            if (rowWasChanged) {
                data.set(rCnt, rowData);
            }
        }

        return (data);
    }

    public static Connection getConnection(String driver, String dsn, String user, String password)
            throws Exception {
        Connection con1 = null;
        Class.forName(driver);
        con1 = DriverManager.getConnection(dsn, user, password);

        return (con1);
    }

    private static void cleanHeaderCells(JTable table) {

        for (int cCnt = 0; cCnt < table.getColumnCount(); ++cCnt) {
            //         for each column in a row
            if (table.getValueAt(0, cCnt) == null) {
                //              set this cell to ""
                table.setValueAt("", 0, cCnt);
            } else {
                String cellValue = (String) table.getValueAt(0, cCnt);

                if (cellValue.length() > 0) {
                    //System.out.println(cellValue);

                    for (int cnt = 0; cnt < badChars.length; ++cnt) {
                        //check if cellValue contains any of the bad chars
                        int indexValue = -1;
                        try {
                            indexValue = cellValue.indexOf(badChars[cnt]);
                            if (cellValue.indexOf(badChars[cnt]) != -1) {
                                //change char
                                //System.out.println(badChars[cnt]+":"+goodChars[cnt]);
                                cellValue = cellValue.replaceAll("\\" + badChars[cnt], goodChars[cnt]);
                                table.setValueAt(cellValue, 0, cCnt);
                            }
                        } catch (NullPointerException e) {
                            System.out.println("null");
                        }
                    }
                }
            }
        }

    }

    private static String removeBadCharsFromString(String cellValue, boolean skipBoolean) throws Exception {

        /*for (int cnt = 0; cnt < badChars.length; ++cnt) {
         //check if cellValue contains any of the bad chars
          int indexValue = -1;
          try {
          indexValue = cellValue.indexOf(badChars[cnt]);
          if (cellValue.indexOf(badChars[cnt]) != -1) {
          //change char
           //System.out.println(badChars[cnt]+":"+goodChars[cnt]);
        cellValue = cellValue.replaceAll("\\"+badChars[cnt],goodChars[cnt]);
        }
        } catch (NullPointerException e) {
        System.out.println("null");
        }
        }*/

        return (substituteSelectedCharacters(cellValue, skipBoolean));
    }

    /**
     * Substitutes the selected characters with entities.
     */
    public static String substituteSelectedCharacters(String text, boolean skip) {

        if (text != null) {

            StringBuffer newText = new StringBuffer();

            for (int i = 0; i < text.length(); i++) {
                char character = text.charAt(i);

                if (character == '<') {
                    if (skip)
                        newText.append("&lt;");
                    else
                        newText.append((char) character);

                } else if (character == '>') {
                    if (skip)
                        newText.append("&gt;");
                    else
                        newText.append((char) character);
                } else if (character == '&') {
                    if (skip) {
                        newText.append("&amp;");
                    } else {
                        newText.append((char) character);
                    }

                } else if (character == '\'') {
                    if (skip)
                        newText.append("&apos;");
                    else
                        newText.append((char) character);

                } else if (character == '\"') {
                    if (skip)
                        newText.append("&quot;");
                    else
                        newText.append((char) character);

                    /*} else if (  character > 127) {
                    if(!skip) {
                    String name = CommonEntities.getEntityName( character);
                        
                    try {
                    if ( !name.equals( "lt") && !name.equals( "gt") && !name.equals( "amp") && !name.equals( "apos") && !name.equals( "quot")) {
                        newText.append( "&");
                        newText.append( name);
                        newText.append( ";");
                    }
                    }
                    catch (NullPointerException e) {
                    //problem with converting char to entity
                    //just use that char
                    newText.append((char)character);
                    }
                    }
                    else {
                    newText.append( (char)character);
                    }*/
                } else {
                    newText.append((char) character);
                }
            }

            return (newText.toString());
        } else {
            return (text);
        }

    }
}

Related

  1. checkRow(DefaultTableModel table, List data, int row)
  2. clearAllRows(JTable table)
  3. contains(int row, TableModel model)
  4. copyRows(JTable table)
  5. createThrowableMessage(Throwable t)
  6. deleteRows(final int[] sortedRows, final List list, final AbstractTableModel model)
  7. ensureRowCount(int count, JTable table)
  8. firstRowIsVoid(TableModel model)