Coverage Report - liquibase.util.csv.opencsv.CSVWriter
 
Classes in this File Line Coverage Branch Coverage Complexity
CSVWriter
0%
0/114
0%
0/76
4.429
 
 1  
 package liquibase.util.csv.opencsv;
 2  
 
 3  
 /**
 4  
  * Copyright 2005 Bytecode Pty Ltd.
 5  
  * 
 6  
  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 7  
  * the License. You may obtain a copy of the License at
 8  
  * 
 9  
  * http://www.apache.org/licenses/LICENSE-2.0
 10  
  * 
 11  
  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 12  
  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 13  
  * specific language governing permissions and limitations under the License.
 14  
  */
 15  
 
 16  
 import java.io.IOException;
 17  
 import java.io.PrintWriter;
 18  
 import java.io.Reader;
 19  
 import java.io.Writer;
 20  
 import java.math.BigDecimal;
 21  
 import java.sql.Clob;
 22  
 import java.sql.ResultSet;
 23  
 import java.sql.ResultSetMetaData;
 24  
 import java.sql.SQLException;
 25  
 import java.sql.Time;
 26  
 import java.sql.Timestamp;
 27  
 import java.sql.Types;
 28  
 import java.text.SimpleDateFormat;
 29  
 import java.util.Iterator;
 30  
 import java.util.List;
 31  
 
 32  
 /**
 33  
  * A very simple CSV writer released under a commercial-friendly license.
 34  
  * 
 35  
  * @author Glen Smith
 36  
  * 
 37  
  */
 38  
 public class CSVWriter {
 39  
 
 40  
     private Writer rawWriter;
 41  
 
 42  
     private PrintWriter pw;
 43  
 
 44  
     private char separator;
 45  
 
 46  
     private char quotechar;
 47  
 
 48  
     private char escapechar;
 49  
 
 50  
     private String lineEnd;
 51  
 
 52  
     /** The character used for escaping quotes. */
 53  
     public static final char DEFAULT_ESCAPE_CHARACTER = '"';
 54  
 
 55  
     /** The default separator to use if none is supplied to the constructor. */
 56  
     public static final char DEFAULT_SEPARATOR = ',';
 57  
 
 58  
     /**
 59  
      * The default quote character to use if none is supplied to the constructor.
 60  
      */
 61  
     public static final char DEFAULT_QUOTE_CHARACTER = '"';
 62  
 
 63  
     /** The quote constant to use when you wish to suppress all quoting. */
 64  
     public static final char NO_QUOTE_CHARACTER = '\u0000';
 65  
 
 66  
     /** The escape constant to use when you wish to suppress all escaping. */
 67  
     public static final char NO_ESCAPE_CHARACTER = '\u0000';
 68  
 
 69  
     /** Default line terminator uses platform encoding. */
 70  
     public static final String DEFAULT_LINE_END = "\n";
 71  
 
 72  0
     private static final SimpleDateFormat TIMESTAMP_FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
 73  
 
 74  0
     private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("dd-MMM-yyyy");
 75  
 
 76  
     /**
 77  
      * Constructs CSVWriter using a comma for the separator.
 78  
      * 
 79  
      * @param writer
 80  
      *            the writer to an underlying CSV source.
 81  
      */
 82  
     public CSVWriter(Writer writer) {
 83  0
         this(writer, DEFAULT_SEPARATOR);
 84  0
     }
 85  
 
 86  
     /**
 87  
      * Constructs CSVWriter with supplied separator.
 88  
      * 
 89  
      * @param writer
 90  
      *            the writer to an underlying CSV source.
 91  
      * @param separator
 92  
      *            the delimiter to use for separating entries.
 93  
      */
 94  
     public CSVWriter(Writer writer, char separator) {
 95  0
         this(writer, separator, DEFAULT_QUOTE_CHARACTER);
 96  0
     }
 97  
 
 98  
     /**
 99  
      * Constructs CSVWriter with supplied separator and quote char.
 100  
      * 
 101  
      * @param writer
 102  
      *            the writer to an underlying CSV source.
 103  
      * @param separator
 104  
      *            the delimiter to use for separating entries
 105  
      * @param quotechar
 106  
      *            the character to use for quoted elements
 107  
      */
 108  
     public CSVWriter(Writer writer, char separator, char quotechar) {
 109  0
         this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER);
 110  0
     }
 111  
 
 112  
     /**
 113  
      * Constructs CSVWriter with supplied separator and quote char.
 114  
      * 
 115  
      * @param writer
 116  
      *            the writer to an underlying CSV source.
 117  
      * @param separator
 118  
      *            the delimiter to use for separating entries
 119  
      * @param quotechar
 120  
      *            the character to use for quoted elements
 121  
      * @param escapechar
 122  
      *            the character to use for escaping quotechars or escapechars
 123  
      */
 124  
     public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) {
 125  0
         this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END);
 126  0
     }
 127  
 
 128  
     /**
 129  
      * Constructs CSVWriter with supplied separator and quote char.
 130  
      * 
 131  
      * @param writer
 132  
      *            the writer to an underlying CSV source.
 133  
      * @param separator
 134  
      *            the delimiter to use for separating entries
 135  
      * @param quotechar
 136  
      *            the character to use for quoted elements
 137  
      * @param lineEnd
 138  
      *            the line feed terminator to use
 139  
      */
 140  
     public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) {
 141  0
         this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd);
 142  0
     }
 143  
 
 144  
     /**
 145  
      * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
 146  
      * 
 147  
      * @param writer
 148  
      *            the writer to an underlying CSV source.
 149  
      * @param separator
 150  
      *            the delimiter to use for separating entries
 151  
      * @param quotechar
 152  
      *            the character to use for quoted elements
 153  
      * @param escapechar
 154  
      *            the character to use for escaping quotechars or escapechars
 155  
      * @param lineEnd
 156  
      *            the line feed terminator to use
 157  
      */
 158  0
     public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
 159  0
         this.rawWriter = writer;
 160  0
         this.pw = new PrintWriter(writer);
 161  0
         this.separator = separator;
 162  0
         this.quotechar = quotechar;
 163  0
         this.escapechar = escapechar;
 164  0
         this.lineEnd = lineEnd;
 165  0
     }
 166  
 
 167  
     /**
 168  
      * Writes the entire list to a CSV file. The list is assumed to be a String[]
 169  
      * 
 170  
      * @param allLines
 171  
      *            a List of String[], with each String[] representing a line of the file.
 172  
      */
 173  
     public void writeAll(List allLines) {
 174  
 
 175  0
         for (Iterator iter = allLines.iterator(); iter.hasNext();) {
 176  0
             String[] nextLine = (String[]) iter.next();
 177  0
             writeNext(nextLine);
 178  0
         }
 179  
 
 180  0
     }
 181  
 
 182  
     protected void writeColumnNames(ResultSetMetaData metadata) throws SQLException {
 183  
 
 184  0
         int columnCount = metadata.getColumnCount();
 185  
 
 186  0
         String[] nextLine = new String[columnCount];
 187  0
         for (int i = 0; i < columnCount; i++) {
 188  0
             nextLine[i] = metadata.getColumnName(i + 1);
 189  
         }
 190  0
         writeNext(nextLine);
 191  0
     }
 192  
 
 193  
     /**
 194  
      * Writes the entire ResultSet to a CSV file.
 195  
      * 
 196  
      * The caller is responsible for closing the ResultSet.
 197  
      * 
 198  
      * @param rs
 199  
      *            the recordset to write
 200  
      * @param includeColumnNames
 201  
      *            true if you want column names in the output, false otherwise
 202  
      * 
 203  
      */
 204  
     public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws SQLException, IOException {
 205  
 
 206  0
         ResultSetMetaData metadata = rs.getMetaData();
 207  
 
 208  0
         if (includeColumnNames) {
 209  0
             writeColumnNames(metadata);
 210  
         }
 211  
 
 212  0
         int columnCount = metadata.getColumnCount();
 213  
 
 214  0
         while (rs.next()) {
 215  0
             String[] nextLine = new String[columnCount];
 216  
 
 217  0
             for (int i = 0; i < columnCount; i++) {
 218  0
                 nextLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1);
 219  
             }
 220  
 
 221  0
             writeNext(nextLine);
 222  0
         }
 223  0
     }
 224  
 
 225  
     private static String getColumnValue(ResultSet rs, int colType, int colIndex) throws SQLException, IOException {
 226  
 
 227  0
         String value = "";
 228  
 
 229  0
         switch (colType) {
 230  
         case Types.BIT:
 231  0
             Object bit = rs.getObject(colIndex);
 232  0
             if (bit != null) {
 233  0
                 value = String.valueOf(bit);
 234  
             }
 235  
             break;
 236  
         case Types.BOOLEAN:
 237  0
             boolean b = rs.getBoolean(colIndex);
 238  0
             if (!rs.wasNull()) {
 239  0
                 value = Boolean.valueOf(b).toString();
 240  
             }
 241  
             break;
 242  
         case Types.CLOB:
 243  0
             Clob c = rs.getClob(colIndex);
 244  0
             if (c != null) {
 245  0
                 value = read(c);
 246  
             }
 247  
             break;
 248  
         case Types.BIGINT:
 249  
         case Types.DECIMAL:
 250  
         case Types.DOUBLE:
 251  
         case Types.FLOAT:
 252  
         case Types.REAL:
 253  
         case Types.NUMERIC:
 254  0
             BigDecimal bd = rs.getBigDecimal(colIndex);
 255  0
             if (bd != null) {
 256  0
                 value = "" + bd.doubleValue();
 257  
             }
 258  
             break;
 259  
         case Types.INTEGER:
 260  
         case Types.TINYINT:
 261  
         case Types.SMALLINT:
 262  0
             int intValue = rs.getInt(colIndex);
 263  0
             if (!rs.wasNull()) {
 264  0
                 value = "" + intValue;
 265  
             }
 266  
             break;
 267  
         case Types.JAVA_OBJECT:
 268  0
             Object obj = rs.getObject(colIndex);
 269  0
             if (obj != null) {
 270  0
                 value = String.valueOf(obj);
 271  
             }
 272  
             break;
 273  
         case Types.DATE:
 274  0
             java.sql.Date date = rs.getDate(colIndex);
 275  0
             if (date != null) {
 276  0
                 value = DATE_FORMATTER.format(date);
 277  
                 ;
 278  
             }
 279  
             break;
 280  
         case Types.TIME:
 281  0
             Time t = rs.getTime(colIndex);
 282  0
             if (t != null) {
 283  0
                 value = t.toString();
 284  
             }
 285  
             break;
 286  
         case Types.TIMESTAMP:
 287  0
             Timestamp tstamp = rs.getTimestamp(colIndex);
 288  0
             if (tstamp != null) {
 289  0
                 value = TIMESTAMP_FORMATTER.format(tstamp);
 290  
             }
 291  
             break;
 292  
         case Types.LONGVARCHAR:
 293  
         case Types.VARCHAR:
 294  
         case Types.CHAR:
 295  0
             value = rs.getString(colIndex);
 296  0
             break;
 297  
         default:
 298  0
             value = "";
 299  
         }
 300  
 
 301  0
         if (value == null) {
 302  0
             value = "";
 303  
         }
 304  
 
 305  0
         return value;
 306  
 
 307  
     }
 308  
 
 309  
     private static String read(Clob c) throws SQLException, IOException {
 310  0
         StringBuffer sb = new StringBuffer((int) c.length());
 311  0
         Reader r = c.getCharacterStream();
 312  0
         char[] cbuf = new char[2048];
 313  0
         int n = 0;
 314  0
         while ((n = r.read(cbuf, 0, cbuf.length)) != -1) {
 315  0
             if (n > 0) {
 316  0
                 sb.append(cbuf, 0, n);
 317  
             }
 318  
         }
 319  0
         return sb.toString();
 320  
     }
 321  
 
 322  
     /**
 323  
      * Writes the next line to the file.
 324  
      * 
 325  
      * @param nextLine
 326  
      *            a string array with each comma-separated element as a separate entry.
 327  
      */
 328  
     public void writeNext(String[] nextLine) {
 329  
 
 330  0
         if (nextLine == null)
 331  0
             return;
 332  
 
 333  0
         StringBuffer sb = new StringBuffer();
 334  0
         for (int i = 0; i < nextLine.length; i++) {
 335  
 
 336  0
             if (i != 0) {
 337  0
                 sb.append(separator);
 338  
             }
 339  
 
 340  0
             String nextElement = nextLine[i];
 341  0
             if (nextElement == null)
 342  0
                 continue;
 343  0
             if (quotechar != NO_QUOTE_CHARACTER)
 344  0
                 sb.append(quotechar);
 345  0
             for (int j = 0; j < nextElement.length(); j++) {
 346  0
                 char nextChar = nextElement.charAt(j);
 347  0
                 if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
 348  0
                     sb.append(escapechar).append(nextChar);
 349  0
                 } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
 350  0
                     sb.append(escapechar).append(nextChar);
 351  
                 } else {
 352  0
                     sb.append(nextChar);
 353  
                 }
 354  
             }
 355  0
             if (quotechar != NO_QUOTE_CHARACTER)
 356  0
                 sb.append(quotechar);
 357  
         }
 358  
 
 359  0
         sb.append(lineEnd);
 360  0
         pw.write(sb.toString());
 361  
 
 362  0
     }
 363  
 
 364  
     /**
 365  
      * Flush underlying stream to writer.
 366  
      * 
 367  
      * @throws IOException
 368  
      *             if bad things happen
 369  
      */
 370  
     public void flush() throws IOException {
 371  
 
 372  0
         pw.flush();
 373  
 
 374  0
     }
 375  
 
 376  
     /**
 377  
      * Close the underlying stream writer flushing any buffered content.
 378  
      * 
 379  
      * @throws IOException
 380  
      *             if bad things happen
 381  
      * 
 382  
      */
 383  
     public void close() throws IOException {
 384  0
         pw.flush();
 385  0
         pw.close();
 386  0
         rawWriter.close();
 387  0
     }
 388  
 
 389  
 }