opencsv-2.3/0000755000175000017500000000000012146650024012363 5ustar ebourgebourgopencsv-2.3/examples/0000755000175000017500000000000012146650024014201 5ustar ebourgebourgopencsv-2.3/examples/JdbcExample.java0000644000175000017500000000142711551741341017230 0ustar ebourgebourg/* * * */ import au.com.bytecode.opencsv.CSVWriter; import java.io.StringWriter; import java.sql.ResultSet; import java.sql.SQLException; public class JdbcExample { public static void main(String[] args) { ResultSet rs = null; try { rs = getResultSet(); StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeAll(rs, false); writer.close(); System.out.println(sw); } catch (Exception ex) { ex.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ignore) { // ignore } } } } private static ResultSet getResultSet() { return new MockResultSet(10); } } opencsv-2.3/examples/MockResultSet.java0000644000175000017500000006735311551741341017630 0ustar ebourgebourgimport java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.Map; /** * * * mock ResultSet * * * */ public class MockResultSet implements ResultSet { private int currentRow = -1; private int rowCount = 0; private MockResultSetMetaData metadata; private long currentTime = System.currentTimeMillis(); public MockResultSet(int rows) { this(rows, MockResultSetMetaData.getDefaultMetaData()); } public MockResultSet(int rows, MockResultSetMetaData meta) { rowCount = rows; metadata = meta; } public MockResultSet() { metadata = MockResultSetMetaData.getDefaultMetaData(); } public int getRowCount() { return rowCount; } public boolean next() throws SQLException { if (currentRow + 1 >= rowCount) { return false; } else { currentRow++; return true; } } public void close() throws SQLException { } public boolean wasNull() throws SQLException { return false; } protected MockColumn getColumn(int columnIndex) { return metadata.getColumn(columnIndex); } public String getString(int columnIndex) throws SQLException { return "string-" + getCurrentRow(); } public boolean getBoolean(int columnIndex) throws SQLException { return ((getCurrentRow() % 2) == 0); } public byte getByte(int columnIndex) throws SQLException { return 0; } public short getShort(int columnIndex) throws SQLException { return (short) getCurrentRow(); } public int getInt(int columnIndex) throws SQLException { return getCurrentRow(); } public long getLong(int columnIndex) throws SQLException { return getCurrentRow(); } public float getFloat(int columnIndex) throws SQLException { return getCurrentRow() + 0.25f; } public double getDouble(int columnIndex) throws SQLException { return getCurrentRow() + 0.33d; } public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { return new BigDecimal(getCurrentRow() + 0.44d); } public byte[] getBytes(int columnIndex) throws SQLException { return "foo".getBytes(); } public Date getDate(int columnIndex) throws SQLException { return new Date(currentTime); } public Time getTime(int columnIndex) throws SQLException { return new java.sql.Time(currentTime); } public Timestamp getTimestamp(int columnIndex) throws SQLException { return new Timestamp(currentTime); } public InputStream getAsciiStream(int columnIndex) throws SQLException { return null; // todo } public InputStream getUnicodeStream(int columnIndex) throws SQLException { return null; } public InputStream getBinaryStream(int columnIndex) throws SQLException { return null; } public String getString(String columnName) throws SQLException { return columnName + getCurrentRow(); } public boolean getBoolean(String columnName) throws SQLException { return ((getCurrentRow() % 2) == 0); } public byte getByte(String columnName) throws SQLException { return 0; } public short getShort(String columnName) throws SQLException { return (short) getCurrentRow(); } public int getInt(String columnName) throws SQLException { return getCurrentRow(); } public long getLong(String columnName) throws SQLException { return (long) getCurrentRow(); } public float getFloat(String columnName) throws SQLException { return (float) getCurrentRow() + 0.01f; } public double getDouble(String columnName) throws SQLException { return (double) getCurrentRow() + 0.05d; } public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { return new java.math.BigDecimal(getCurrentRow() + 0.25); } public byte[] getBytes(String columnName) throws SQLException { return columnName.getBytes(); } public Date getDate(String columnName) throws SQLException { return new Date(currentTime); } public Time getTime(String columnName) throws SQLException { return new java.sql.Time(currentTime); } public Timestamp getTimestamp(String columnName) throws SQLException { return new Timestamp(currentTime); } public InputStream getAsciiStream(String columnName) throws SQLException { return null; } public InputStream getUnicodeStream(String columnName) throws SQLException { return null; } public InputStream getBinaryStream(String columnName) throws SQLException { return null; } public SQLWarning getWarnings() throws SQLException { return null; } public void clearWarnings() throws SQLException { } public String getCursorName() throws SQLException { return "CursorName"; } public ResultSetMetaData getMetaData() throws SQLException { return metadata; } public Object getObject(int columnIndex) throws SQLException { return new StringBuilder("Object[row " + getCurrentRow() + ", column " + columnIndex + "]"); } public Object getObject(String columnName) throws SQLException { return new StringBuilder("Object-" + getCurrentRow()); } public int findColumn(String columnName) throws SQLException { return 0; // todo ? } public Reader getCharacterStream(int columnIndex) throws SQLException { return null; // todo ? } public Reader getCharacterStream(String columnName) throws SQLException { return null; // todo ? } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { return new BigDecimal(getCurrentRow() + 0.25d); } public BigDecimal getBigDecimal(String columnName) throws SQLException { return new BigDecimal(getCurrentRow() + 0.25d); } public boolean isBeforeFirst() throws SQLException { return (getCurrentRow() < 0); } public boolean isAfterLast() throws SQLException { return (getCurrentRow() >= getRowCount()); } public boolean isFirst() throws SQLException { return (getCurrentRow() == 0); } public boolean isLast() throws SQLException { return (getCurrentRow() == (getRowCount() - 1)); } public void beforeFirst() throws SQLException { currentRow = -1; } public void afterLast() throws SQLException { throw new SQLException("not implemented"); } public boolean first() throws SQLException { currentRow = 0; return true; } public boolean last() throws SQLException { currentRow = getRowCount() - 1; return true; } public int getRow() throws SQLException { return currentRow; } public boolean absolute(int row) throws SQLException { throw new SQLException("not implemented"); } public boolean relative(int rows) throws SQLException { throw new SQLException("not implemented"); } public boolean previous() throws SQLException { throw new SQLException("not implemented"); } public void setFetchDirection(int direction) throws SQLException { throw new SQLException("not implemented"); } public int getFetchDirection() throws SQLException { throw new SQLException("not implemented"); } public void setFetchSize(int rows) throws SQLException { throw new SQLException("not implemented"); } public int getFetchSize() throws SQLException { throw new SQLException("not implemented"); } public int getType() throws SQLException { throw new SQLException("not implemented"); } public int getConcurrency() throws SQLException { throw new SQLException("not implemented"); } public boolean rowUpdated() throws SQLException { throw new SQLException("not implemented"); } public boolean rowInserted() throws SQLException { throw new SQLException("not implemented"); } public boolean rowDeleted() throws SQLException { throw new SQLException("not implemented"); } public void updateNull(int columnIndex) throws SQLException { throw new SQLException("not implemented"); } public void updateBoolean(int columnIndex, boolean x) throws SQLException { throw new SQLException("not implemented"); } public void updateByte(int columnIndex, byte x) throws SQLException { throw new SQLException("not implemented"); } public void updateShort(int columnIndex, short x) throws SQLException { throw new SQLException("not implemented"); } public void updateInt(int columnIndex, int x) throws SQLException { throw new SQLException("not implemented"); } public void updateLong(int columnIndex, long x) throws SQLException { throw new SQLException("not implemented"); } public void updateFloat(int columnIndex, float x) throws SQLException { throw new SQLException("not implemented"); } public void updateDouble(int columnIndex, double x) throws SQLException { throw new SQLException("not implemented"); } public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { throw new SQLException("not implemented"); } public void updateString(int columnIndex, String x) throws SQLException { throw new SQLException("not implemented"); } public void updateBytes(int columnIndex, byte[] x) throws SQLException { throw new SQLException("not implemented"); } public void updateDate(int columnIndex, Date x) throws SQLException { throw new SQLException("not implemented"); } public void updateTime(int columnIndex, Time x) throws SQLException { throw new SQLException("not implemented"); } public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { throw new SQLException("not implemented"); } public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("not implemented"); } public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("not implemented"); } public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { throw new SQLException("not implemented"); } public void updateObject(int columnIndex, Object x, int scale) throws SQLException { throw new SQLException("not implemented"); } public void updateObject(int columnIndex, Object x) throws SQLException { throw new SQLException("not implemented"); } public void updateNull(String columnName) throws SQLException { throw new SQLException("not implemented"); } public void updateBoolean(String columnName, boolean x) throws SQLException { throw new SQLException("not implemented"); } public void updateByte(String columnName, byte x) throws SQLException { throw new SQLException("not implemented"); } public void updateShort(String columnName, short x) throws SQLException { throw new SQLException("not implemented"); } public void updateInt(String columnName, int x) throws SQLException { throw new SQLException("not implemented"); } public void updateLong(String columnName, long x) throws SQLException { throw new SQLException("not implemented"); } public void updateFloat(String columnName, float x) throws SQLException { throw new SQLException("not implemented"); } public void updateDouble(String columnName, double x) throws SQLException { throw new SQLException("not implemented"); } public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { throw new SQLException("not implemented"); } public void updateString(String columnName, String x) throws SQLException { throw new SQLException("not implemented"); } public void updateBytes(String columnName, byte[] x) throws SQLException { throw new SQLException("not implemented"); } public void updateDate(String columnName, Date x) throws SQLException { throw new SQLException("not implemented"); } public void updateTime(String columnName, Time x) throws SQLException { throw new SQLException("not implemented"); } public void updateTimestamp(String columnName, Timestamp x) throws SQLException { throw new SQLException("not implemented"); } public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("not implemented"); } public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("not implemented"); } public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException { throw new SQLException("not implemented"); } public void updateObject(String columnName, Object x, int scale) throws SQLException { throw new SQLException("not implemented"); } public void updateObject(String columnName, Object x) throws SQLException { throw new SQLException("not implemented"); } public void insertRow() throws SQLException { throw new SQLException("not implemented"); } public void updateRow() throws SQLException { throw new SQLException("not implemented"); } public void deleteRow() throws SQLException { throw new SQLException("not implemented"); } public void refreshRow() throws SQLException { throw new SQLException("not implemented"); } public void cancelRowUpdates() throws SQLException { throw new SQLException("not implemented"); } public void moveToInsertRow() throws SQLException { throw new SQLException("not implemented"); } public void moveToCurrentRow() throws SQLException { throw new SQLException("not implemented"); } public Statement getStatement() throws SQLException { throw new SQLException("not implemented"); } public Object getObject(int arg0, Map> arg1) throws SQLException { throw new SQLException("not implemented"); } public Ref getRef(int i) throws SQLException { throw new SQLException("not implemented"); } public Blob getBlob(int i) throws SQLException { throw new SQLException("not implemented"); } public Clob getClob(int i) throws SQLException { // TODO Auto-generated method stub return null; } public Array getArray(int i) throws SQLException { throw new SQLException("not implemented"); } public Object getObject(String arg0, Map> arg1) throws SQLException { throw new SQLException("not implemented"); } public Ref getRef(String colName) throws SQLException { // TODO Auto-generated method stub return null; } public Blob getBlob(String colName) throws SQLException { throw new SQLException("not implemented"); } public Clob getClob(String colName) throws SQLException { // TODO Auto-generated method stub return null; } public Array getArray(String colName) throws SQLException { throw new SQLException("not implemented"); } public Date getDate(int columnIndex, Calendar cal) throws SQLException { return new Date(currentTime); } public Date getDate(String columnName, Calendar cal) throws SQLException { return new Date(currentTime); } public Time getTime(int columnIndex, Calendar cal) throws SQLException { return new Time(currentTime); } public Time getTime(String columnName, Calendar cal) throws SQLException { return new Time(currentTime); } public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { return new Timestamp(currentTime); } public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { return new Timestamp(currentTime); } public URL getURL(int columnIndex) throws SQLException { try { return new URL("http://www.google.com/"); } catch (MalformedURLException ex) { throw new SQLException(); } } public URL getURL(String columnName) throws SQLException { try { return new URL("http://www.google.com/"); } catch (MalformedURLException ex) { throw new SQLException(); } } public void updateRef(int columnIndex, Ref x) throws SQLException { throw new SQLException("not implemented"); } public void updateRef(String columnName, Ref x) throws SQLException { throw new SQLException("not implemented"); } public void updateBlob(int columnIndex, Blob x) throws SQLException { throw new SQLException("not implemented"); } public void updateBlob(String columnName, Blob x) throws SQLException { throw new SQLException("not implemented"); } public void updateClob(int columnIndex, Clob x) throws SQLException { throw new SQLException("not implemented"); } public void updateClob(String columnName, Clob x) throws SQLException { throw new SQLException("not implemented"); } public void updateArray(int columnIndex, Array x) throws SQLException { throw new SQLException("not implemented"); } public void updateArray(String columnName, Array x) throws SQLException { throw new SQLException("not implemented"); } protected int getCurrentRow() { return currentRow; } @Override public int getHoldability() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Reader getNCharacterStream(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Reader getNCharacterStream(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob getNClob(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob getNClob(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getNString(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getNString(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public RowId getRowId(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public RowId getRowId(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML getSQLXML(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML getSQLXML(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean isClosed() throws SQLException { // TODO Auto-generated method stub return false; } @Override public void updateAsciiStream(int arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(String arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(int arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(String arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(int arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(String arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(int arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(String arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(int arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(String arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(int arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(String arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(int arg0, NClob arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(String arg0, NClob arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNString(int arg0, String arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNString(String arg0, String arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateRowId(int arg0, RowId arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateRowId(String arg0, RowId arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateSQLXML(int arg0, SQLXML arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void updateSQLXML(String arg0, SQLXML arg1) throws SQLException { // TODO Auto-generated method stub } @Override public boolean isWrapperFor(Class arg0) throws SQLException { // TODO Auto-generated method stub return false; } @Override public T unwrap(Class arg0) throws SQLException { // TODO Auto-generated method stub return null; } } class MockColumn { private String columnName; private int type; public MockColumn(int type, String name) { this.columnName = name; this.type = type; } public int getDisplaySize() { return 10; } public String getName() { return this.columnName; } public int getType() { return type; } public String toString() { return this.getName(); } } class MockResultSetMetaData implements ResultSetMetaData { public static MockResultSetMetaData getDefaultMetaData() { MockResultSetMetaData meta = new MockResultSetMetaData(); meta.addColumn(new MockColumn(Types.VARCHAR, "VarcharColumn")); meta.addColumn(new MockColumn(Types.BOOLEAN, "BooleanColumn")); meta.addColumn(new MockColumn(Types.INTEGER, "IntegerColumn")); meta.addColumn(new MockColumn(Types.DOUBLE, "DoubleColumn")); meta.addColumn(new MockColumn(Types.TIME, "TimeColumn")); meta.addColumn(new MockColumn(Types.DATE, "DateColumn")); meta.addColumn(new MockColumn(Types.CHAR, "CharColumn")); meta.addColumn(new MockColumn(Types.JAVA_OBJECT, "JavaObjectColumn")); meta.addColumn(new MockColumn(Types.TIMESTAMP, "TimeStampColumn")); meta.addColumn(new MockColumn(Types.NUMERIC, "NumericColumn")); meta.addColumn(new MockColumn(Types.DECIMAL, "DecimalColumn")); meta.addColumn(new MockColumn(Types.BIGINT, "BigIntegerColumn")); return meta; } private ArrayList columns = new ArrayList(); public MockResultSetMetaData() { } public void clear() { columns.clear(); } public void addColumn(MockColumn c) { columns.add(c); } public int getColumnCount() throws SQLException { return columns.size(); } public boolean isAutoIncrement(int column) throws SQLException { return false; } public boolean isCaseSensitive(int column) throws SQLException { return false; } public boolean isSearchable(int column) throws SQLException { return false; } public boolean isCurrency(int column) throws SQLException { return false; } public int isNullable(int column) throws SQLException { return ResultSetMetaData.columnNoNulls; } public boolean isSigned(int column) throws SQLException { return false; } public MockColumn getColumn(int column) { return columns.get(column - 1); } public int getColumnDisplaySize(int column) throws SQLException { return getColumn(column).getDisplaySize(); } public String getColumnLabel(int column) throws SQLException { return this.getColumnName(column); } public String getColumnName(int column) throws SQLException { return getColumn(column).getName(); } public String getSchemaName(int column) throws SQLException { return "SchemaName"; } public int getPrecision(int column) throws SQLException { return 0; } public int getScale(int column) throws SQLException { return 0; } public String getTableName(int column) throws SQLException { return "Table" + column; } public String getCatalogName(int column) throws SQLException { return "Catalog" + column; } public int getColumnType(int column) throws SQLException { return getColumn(column).getType(); } public String getColumnTypeName(int column) throws SQLException { return "ColumnTypeName" + column; } public boolean isReadOnly(int column) throws SQLException { return false; } public boolean isWritable(int column) throws SQLException { return false; } public boolean isDefinitelyWritable(int column) throws SQLException { return false; } public String getColumnClassName(int column) throws SQLException { return "ColumnClassName" + column; } @Override public boolean isWrapperFor(Class arg0) throws SQLException { // TODO Auto-generated method stub return false; } @Override public T unwrap(Class arg0) throws SQLException { // TODO Auto-generated method stub return null; } } opencsv-2.3/examples/addresses.csv0000644000175000017500000000034711551741341016701 0ustar ebourgebourgJoe Demo,"2 Demo Street, Demoville, Australia. 2615",joe@someaddress.com Jim Sample,"3 Sample Street, Sampleville, Australia. 2615",jim@sample.com Jack Example,"1 Example Street, Exampleville, Australia. 2615",jack@example.comopencsv-2.3/examples/AddressExample.java0000644000175000017500000000311511551741341017747 0ustar ebourgebourgimport au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import java.io.FileReader; import java.io.IOException; import java.io.StringWriter; import java.util.List; /** Copyright 2005 Bytecode Pty Ltd. 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. */ public class AddressExample { private static final String ADDRESS_FILE="examples/addresses.csv"; public static void main(String[] args) throws IOException { CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE)); String [] nextLine; while ((nextLine = reader.readNext()) != null) { System.out.println("Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]"); } // Try writing it back out as CSV to the console CSVReader reader2 = new CSVReader(new FileReader(ADDRESS_FILE)); List allElements = reader2.readAll(); StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeAll(allElements); System.out.println("\n\nGenerated CSV File:\n\n"); System.out.println(sw.toString()); } } opencsv-2.3/pom.xml0000644000175000017500000001260411551741341013705 0ustar ebourgebourg 4.0.0 net.sf.opencsv opencsv jar 2.3 opencsv A simple library for reading and writing CSV in Java http://opencsv.sf.net Apache 2 http://www.apache.org/licenses/LICENSE-2.0.txt repo A business-friendly OSS license scm:svn:https://opencsv.svn.sourceforge.net/svnroot/opencsv/trunk scm:svn:https://opencsv.svn.sourceforge.net/svnroot/opencsv/trunk http://opencsv.svn.sourceforge.net/viewvc/opencsv/ glen-smith Glen Smith glen_a_smith@users.sourceforge.net http://blogs.bytecode.com.au/glen +10 sean-sullivan Sean Sullivan sullis@users.sourceforge.net scott_conway Scott Conway sconway@users.sourceforge.net Sourceforge http://sourceforge.net/tracker/?group_id=148905 src test maven-compiler-plugin 1.5 1.5 org.apache.maven.plugins maven-surefire-plugin **/Test*.java org.apache.maven.plugins maven-source-plugin attach-sources package jar org.apache.maven.plugins maven-javadoc-plugin attach-javadocs package jar maven-assembly-plugin project org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign org.apache.maven.plugins maven-enforcer-plugin 1.0-beta-1 enforce-versions install enforce [1.5,1.6) junit junit 4.7 test org.codehaus.mojo cobertura-maven-plugin 2.3 org.codehaus.mojo findbugs-maven-plugin 2.1 org.apache.maven.plugins maven-javadoc-plugin 2.6 org.apache.maven.plugins maven-jxr-plugin 2.1 org.apache.maven.plugins maven-site-plugin 2.0.1 doc/site sonatype-repo Sonatype Release Repo http://oss.sonatype.org/content/repositories/sourceforge-releases/ sonatype-repo Sonatype Snapshot Repo http://oss.sonatype.org/content/repositories/sourceforge-snapshots/ opencsv.sf.net scp://shell.sourceforge.net/home/groups/o/op/opencsv/htdocs opencsv-2.3/test/0000755000175000017500000000000012146650024013342 5ustar ebourgebourgopencsv-2.3/test/au/0000755000175000017500000000000012146650024013747 5ustar ebourgebourgopencsv-2.3/test/au/com/0000755000175000017500000000000012146650024014525 5ustar ebourgebourgopencsv-2.3/test/au/com/bytecode/0000755000175000017500000000000012146650024016323 5ustar ebourgebourgopencsv-2.3/test/au/com/bytecode/opencsv/0000755000175000017500000000000012146650024020000 5ustar ebourgebourgopencsv-2.3/test/au/com/bytecode/opencsv/TestUtilities.java0000644000175000017500000000167711551741341023473 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** * Created by IntelliJ IDEA. * User: scott * Date: 12/20/10 * Time: 2:56 PM * To change this template use File | Settings | File Templates. */ public class TestUtilities { public static String displayStringArray(String header, String[] stringArray) { StringBuffer sb = new StringBuffer(); sb.append(header); appendNewLine(sb); sb.append("Number of elements:"); appendTab(sb); sb.append(stringArray.length); appendNewLine(sb); for(int i = 0; i < stringArray.length; i++) { sb.append("element "); sb.append(i); sb.append(':'); appendTab(sb); sb.append(stringArray[i]); appendNewLine(sb); } return sb.toString(); } private static void appendTab(StringBuffer sb) { sb.append('\t'); } private static void appendNewLine(StringBuffer sb) { sb.append('\n'); } } opencsv-2.3/test/au/com/bytecode/opencsv/CSVParserTest.java0000644000175000017500000003634111551741341023324 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** * Created by IntelliJ IDEA. * User: Scott Conway * Date: Oct 7, 2009 * Time: 9:56:48 PM */ import org.junit.Before; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.*; public class CSVParserTest { CSVParser csvParser; @Before public void setUp() { csvParser = new CSVParser(); } @Test public void testParseLine() throws Exception { String nextItem[] = csvParser.parseLine("This, is, a, test."); assertEquals(4, nextItem.length); assertEquals("This", nextItem[0]); assertEquals(" is", nextItem[1]); assertEquals(" a", nextItem[2]); assertEquals(" test.", nextItem[3]); } @Test public void parseSimpleString() throws IOException { String[] nextLine = csvParser.parseLine("a,b,c"); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals("b", nextLine[1]); assertEquals("c", nextLine[2]); assertFalse(csvParser.isPending()); } /** * Tests quotes in the middle of an element. * * @throws IOException if bad things happen */ @Test public void testParsedLineWithInternalQuota() throws IOException { String[] nextLine = csvParser.parseLine("a,123\"4\"567,c"); assertEquals(3, nextLine.length); assertEquals("123\"4\"567", nextLine[1]); } @Test public void parseQuotedStringWithCommas() throws IOException { String[] nextLine = csvParser.parseLine("a,\"b,b,b\",c"); assertEquals("a", nextLine[0]); assertEquals("b,b,b", nextLine[1]); assertEquals("c", nextLine[2]); assertEquals(3, nextLine.length); } @Test public void parseQuotedStringWithDefinedSeperator() throws IOException { csvParser = new CSVParser(':'); String[] nextLine = csvParser.parseLine("a:\"b:b:b\":c"); assertEquals("a", nextLine[0]); assertEquals("b:b:b", nextLine[1]); assertEquals("c", nextLine[2]); assertEquals(3, nextLine.length); } @Test public void parseQuotedStringWithDefinedSeperatorAndQuote() throws IOException { csvParser = new CSVParser(':', '\''); String[] nextLine = csvParser.parseLine("a:'b:b:b':c"); assertEquals("a", nextLine[0]); assertEquals("b:b:b", nextLine[1]); assertEquals("c", nextLine[2]); assertEquals(3, nextLine.length); } @Test public void parseEmptyElements() throws IOException { String[] nextLine = csvParser.parseLine(",,"); assertEquals(3, nextLine.length); assertEquals("", nextLine[0]); assertEquals("", nextLine[1]); assertEquals("", nextLine[2]); } @Test public void parseMultiLinedQuoted() throws IOException { String[] nextLine = csvParser.parseLine("a,\"PO Box 123,\nKippax,ACT. 2615.\nAustralia\",d.\n"); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals("PO Box 123,\nKippax,ACT. 2615.\nAustralia", nextLine[1]); assertEquals("d.\n", nextLine[2]); } @Test public void testADoubleQuoteAsDataElement() throws IOException { String[] nextLine = csvParser.parseLine("a,\"\"\"\",c");// a,"""",c assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals(1, nextLine[1].length()); assertEquals("\"", nextLine[1]); assertEquals("c", nextLine[2]); } @Test public void testEscapedDoubleQuoteAsDataElement() throws IOException { String[] nextLine = csvParser.parseLine("\"test\",\"this,test,is,good\",\"\\\"test\\\"\",\"\\\"quote\\\"\""); // "test","this,test,is,good","\"test\",\"quote\"" assertEquals(4, nextLine.length); assertEquals("test", nextLine[0]); assertEquals("this,test,is,good", nextLine[1]); assertEquals("\"test\"", nextLine[2]); assertEquals("\"quote\"", nextLine[3]); } // @Test // public void testEscapingSeparator() throws IOException { // String[] nextLine = csvParser.parseLine("test,this\\,test\\,is\\,good"); // "test","this,test,is,good","\"test\",\"quote\"" // // assertEquals(2, nextLine.length); // // assertEquals("test", nextLine[0]); // assertEquals("this,test,is,good", nextLine[1]); // } @Test public void parseQuotedQuoteCharacters() throws IOException { String[] nextLine = csvParser.parseLineMulti("\"Glen \"\"The Man\"\" Smith\",Athlete,Developer\n"); assertEquals(3, nextLine.length); assertEquals("Glen \"The Man\" Smith", nextLine[0]); assertEquals("Athlete", nextLine[1]); assertEquals("Developer\n", nextLine[2]); } @Test public void parseMultipleQuotes() throws IOException { String[] nextLine = csvParser.parseLine("\"\"\"\"\"\",\"test\"\n"); // """""","test" representing: "", test assertEquals("\"\"", nextLine[0]); // check the tricky situation assertEquals("test\"\n", nextLine[1]); // make sure we didn't ruin the next field.. assertEquals(2, nextLine.length); } @Test public void parseTrickyString() throws IOException { String[] nextLine = csvParser.parseLine("\"a\nb\",b,\"\nd\",e\n"); assertEquals(4, nextLine.length); assertEquals("a\nb", nextLine[0]); assertEquals("b", nextLine[1]); assertEquals("\nd", nextLine[2]); assertEquals("e\n", nextLine[3]); } private String setUpMultiLineInsideQuotes() { StringBuffer sb = new StringBuffer(CSVParser.INITIAL_READ_SIZE); sb.append("Small test,\"This is a test across \ntwo lines.\""); return sb.toString(); } @Test public void testAMultiLineInsideQuotes() throws IOException { String testString = setUpMultiLineInsideQuotes(); String[] nextLine = csvParser.parseLine(testString); assertEquals(2, nextLine.length); assertEquals("Small test", nextLine[0]); assertEquals("This is a test across \ntwo lines.", nextLine[1]); assertFalse(csvParser.isPending()); } @Test public void testStrictQuoteSimple() throws IOException { csvParser = new CSVParser(',', '\"', '\\', true); String testString = "\"a\",\"b\",\"c\""; String[] nextLine = csvParser.parseLine(testString); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals("b", nextLine[1]); assertEquals("c", nextLine[2]); } @Test public void testStrictQuoteWithSpacesAndTabs() throws IOException { csvParser = new CSVParser(',', '\"', '\\', true); String testString = " \t \"a\",\"b\" \t , \"c\" "; String[] nextLine = csvParser.parseLine(testString); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals("b", nextLine[1]); assertEquals("c", nextLine[2]); } @Test public void testStrictQuoteWithGarbage() throws IOException { csvParser = new CSVParser(',', '\"', '\\', true); String testString = "abc',!@#\",\\\"\" xyz,"; String[] nextLine = csvParser.parseLine(testString); assertEquals(3, nextLine.length); assertEquals("", nextLine[0]); assertEquals(",\"", nextLine[1]); assertEquals("", nextLine[2]); } /** * Test issue 2263439 where an escaped quote was causing the parse to fail. *

* Special thanks to Chris Morris for fixing this (id 1979054) * * @throws IOException */ @Test public void testIssue2263439() throws IOException { csvParser = new CSVParser(',', '\''); String[] nextLine = csvParser.parseLine("865,0,'AmeriKKKa\\'s_Most_Wanted','',294,0,0,0.734338696798625,'20081002052147',242429208,18448"); assertEquals(11, nextLine.length); assertEquals("865", nextLine[0]); assertEquals("0", nextLine[1]); assertEquals("AmeriKKKa's_Most_Wanted", nextLine[2]); assertEquals("", nextLine[3]); assertEquals("18448", nextLine[10]); } /** * Test issue 2859181 where an escaped character before a character * that did not need escaping was causing the parse to fail. * * @throws IOException */ @Test public void testIssue2859181() throws IOException { csvParser = new CSVParser(';'); String[] nextLine = csvParser.parseLine("field1;\\=field2;\"\"\"field3\"\"\""); // field1;\=field2;"""field3""" assertEquals(3, nextLine.length); assertEquals("field1", nextLine[0]); assertEquals("=field2", nextLine[1]); assertEquals("\"field3\"", nextLine[2]); } /** * Test issue 2726363 *

* Data given: *

* "804503689","London",""London""shop","address","116.453182","39.918884" * "453074125","NewYork","brief","address"","121.514683","31.228511" */ @Test public void testIssue2726363() throws IOException { String[] nextLine = csvParser.parseLine("\"804503689\",\"London\",\"\"London\"shop\",\"address\",\"116.453182\",\"39.918884\""); assertEquals(6, nextLine.length); assertEquals("804503689", nextLine[0]); assertEquals("London", nextLine[1]); assertEquals("\"London\"shop", nextLine[2]); assertEquals("address", nextLine[3]); assertEquals("116.453182", nextLine[4]); assertEquals("39.918884", nextLine[5]); } @Test(expected = IOException.class) public void anIOExceptionThrownifStringEndsInsideAQuotedString() throws IOException { String[] nextLine = csvParser.parseLine("This,is a \"bad line to parse."); } @Test public void parseLineMultiAllowsQuotesAcrossMultipleLines() throws IOException { String[] nextLine = csvParser.parseLineMulti("This,\"is a \"good\" line\\\\ to parse"); assertEquals(1, nextLine.length); assertEquals("This", nextLine[0]); assertTrue(csvParser.isPending()); nextLine = csvParser.parseLineMulti("because we are using parseLineMulti.\""); assertEquals(1, nextLine.length); assertEquals("is a \"good\" line\\ to parse\nbecause we are using parseLineMulti.", nextLine[0]); assertFalse(csvParser.isPending()); } @Test public void pendingIsClearedAfterCallToParseLine() throws IOException { String[] nextLine = csvParser.parseLineMulti("This,\"is a \"good\" line\\\\ to parse"); assertEquals(1, nextLine.length); assertEquals("This", nextLine[0]); assertTrue(csvParser.isPending()); nextLine = csvParser.parseLine("because we are using parseLineMulti."); assertEquals(1, nextLine.length); assertEquals("because we are using parseLineMulti.", nextLine[0]); assertFalse(csvParser.isPending()); } @Test public void returnPendingIfNullIsPassedIntoParseLineMulti() throws IOException { String[] nextLine = csvParser.parseLineMulti("This,\"is a \"goo\\d\" line\\\\ to parse\\"); assertEquals(1, nextLine.length); assertEquals("This", nextLine[0]); assertTrue(csvParser.isPending()); nextLine = csvParser.parseLineMulti(null); assertEquals(1, nextLine.length); assertEquals("is a \"good\" line\\ to parse\n", nextLine[0]); assertFalse(csvParser.isPending()); } @Test public void spacesAtEndOfQuotedStringDoNotCountIfStrictQuotesIsTrue() throws IOException { CSVParser parser = new CSVParser(CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, true); String[] nextLine = parser.parseLine("\"Line with\", \"spaces at end\" "); assertEquals(2, nextLine.length); assertEquals("Line with", nextLine[0]); assertEquals("spaces at end", nextLine[1]); } @Test public void returnNullWhenNullPassedIn() throws IOException { String[] nextLine = csvParser.parseLine(null); assertNull(nextLine); } private static final String ESCAPE_TEST_STRING = "\\\\1\\2\\\"3\\"; // \\1\2\"\ @Test public void validateEscapeStringBeforeRealTest() { assertNotNull(ESCAPE_TEST_STRING); assertEquals(9, ESCAPE_TEST_STRING.length()); } @Test public void whichCharactersAreEscapable() { assertTrue(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, true, 0)); assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, false, 0)); // Second character is not escapable because there is a non quote or non slash after it. assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, true, 1)); assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, false, 1)); // Fourth character is not escapable because there is a non quote or non slash after it. assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, true, 3)); assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, false, 3)); assertTrue(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, true, 5)); assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, false, 5)); int lastChar = ESCAPE_TEST_STRING.length() - 1; assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, true, lastChar)); assertFalse(csvParser.isNextCharacterEscapable(ESCAPE_TEST_STRING, false, lastChar)); } @Test public void whitespaceBeforeEscape() throws IOException { String[] nextItem = csvParser.parseLine("\"this\", \"is\",\"a test\""); //"this", "is","a test" assertEquals("this", nextItem[0]); assertEquals("is", nextItem[1]); assertEquals("a test", nextItem[2]); } @Test public void testIssue2958242WithoutQuotes() throws IOException { CSVParser testParser = new CSVParser('\t'); String[] nextItem = testParser.parseLine("zo\"\"har\"\"at\t10-04-1980\t29\tC:\\\\foo.txt"); assertEquals(4, nextItem.length); assertEquals("zo\"har\"at", nextItem[0]); assertEquals("10-04-1980", nextItem[1]); assertEquals("29", nextItem[2]); assertEquals("C:\\foo.txt", nextItem[3]); } @Test(expected = UnsupportedOperationException.class) public void quoteAndEscapeCannotBeTheSame() { CSVParser p = new CSVParser(CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_QUOTE_CHARACTER); } @Test public void quoteAndEscapeCanBeTheSameIfNull() { CSVParser p = new CSVParser(CSVParser.DEFAULT_SEPARATOR, CSVParser.NULL_CHARACTER, CSVParser.NULL_CHARACTER); } @Test(expected = UnsupportedOperationException.class) public void separatorCharacterCannotBeNull() { CSVParser p = new CSVParser(CSVParser.NULL_CHARACTER); } @Test(expected = UnsupportedOperationException.class) public void separatorAndEscapeCannotBeTheSame() { CSVParser p = new CSVParser(CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_SEPARATOR); } @Test(expected = UnsupportedOperationException.class) public void separatorAndQuoteCannotBeTheSame() { CSVParser p = new CSVParser(CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_ESCAPE_CHARACTER); } }opencsv-2.3/test/au/com/bytecode/opencsv/bean/0000755000175000017500000000000012146650024020705 5ustar ebourgebourgopencsv-2.3/test/au/com/bytecode/opencsv/bean/ColumnPositionMappingStrategyTest.java0000644000175000017500000000757211551741341030446 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; /** Copyright 2007 Kyle Miller. 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. */ import org.junit.Before; import org.junit.Test; import java.io.StringReader; import java.util.List; import static org.junit.Assert.*; public class ColumnPositionMappingStrategyTest { private ColumnPositionMappingStrategy strat; @Before public void setUp() throws Exception { strat = new ColumnPositionMappingStrategy(); strat.setType(MockBean.class); } @Test public void testParse() { String s = "" + "kyle,123456,emp123,1\n" + "jimmy,abcnum,cust09878,2"; String[] columns = new String[]{"name", "orderNumber", "id", "num"}; strat.setColumnMapping(columns); CsvToBean csv = new CsvToBean(); List list = csv.parse(strat, new StringReader(s)); assertNotNull(list); assertTrue(list.size() == 2); MockBean bean = list.get(0); assertEquals("kyle", bean.getName()); assertEquals("123456", bean.getOrderNumber()); assertEquals("emp123", bean.getId()); assertEquals(1, bean.getNum()); } @Test public void testParseWithTrailingSpaces() { String s = "" + "kyle ,123456 ,emp123 , 1 \n" + "jimmy,abcnum,cust09878,2 "; String[] columns = new String[]{"name", "orderNumber", "id", "num"}; strat.setColumnMapping(columns); CsvToBean csv = new CsvToBean(); List list = csv.parse(strat, new StringReader(s)); assertNotNull(list); assertTrue(list.size() == 2); MockBean bean = list.get(0); assertEquals("kyle ", bean.getName()); assertEquals("123456 ", bean.getOrderNumber()); assertEquals("emp123 ", bean.getId()); assertEquals(1, bean.getNum()); } @Test public void testGetColumnMapping() { String[] columnMapping = strat.getColumnMapping(); assertNotNull(columnMapping); assertEquals(0, columnMapping.length); String[] columns = new String[]{"name", "orderNumber", "id"}; strat.setColumnMapping(columns); columnMapping = strat.getColumnMapping(); assertNotNull(columnMapping); assertEquals(3, columnMapping.length); assertArrayEquals(columns, columnMapping); } @Test public void testGetColumnNames() { String[] columns = new String[]{"name", null, "id"}; strat.setColumnMapping(columns); assertEquals("name", strat.getColumnName(0)); assertEquals(null, strat.getColumnName(1)); assertEquals("id", strat.getColumnName(2)); assertEquals(null, strat.getColumnName(3)); } @Test public void testGetColumnNamesArray() { String[] columns = new String[]{"name", null, "id"}; strat.setColumnMapping(columns); String[] mapping = strat.getColumnMapping(); assertEquals(3, mapping.length); assertEquals("name", mapping[0]); assertEquals(null, mapping[1]); assertEquals("id", mapping[2]); } @Test public void getColumnNamesHandlesNull() { strat.setColumnMapping(null); assertEquals(null, strat.getColumnName(0)); assertEquals(null, strat.getColumnName(1)); assertNull(strat.getColumnMapping()); } } opencsv-2.3/test/au/com/bytecode/opencsv/bean/CsvToBeanTest.java0000644000175000017500000000273511551741341024245 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; import au.com.bytecode.opencsv.CSVReader; import org.junit.Test; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.StringReader; public class CsvToBeanTest { private static final String TEST_STRING = "name,orderNumber,num\n" + "kyle,abc123456,123\n" + "jimmy,def098765,456 "; private CSVReader createReader() { StringReader reader = new StringReader(TEST_STRING); return new CSVReader(reader); } private MappingStrategy createErrorMappingStrategy() { return new MappingStrategy() { public PropertyDescriptor findDescriptor(int col) throws IntrospectionException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object createBean() throws InstantiationException, IllegalAccessException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void captureHeader(CSVReader reader) throws IOException { throw new IOException("This is the test exception"); } }; } @Test(expected = RuntimeException.class) public void throwRuntimeExceptionWhenExceptionIsThrown() { CsvToBean bean = new CsvToBean(); bean.parse(createErrorMappingStrategy(), createReader()); } } opencsv-2.3/test/au/com/bytecode/opencsv/bean/MockBean.java0000644000175000017500000000254711551741341023241 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; /** Copyright 2007 Kyle Miller. 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. */ public class MockBean { private String name; private String id; private String orderNumber; private int num; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } }opencsv-2.3/test/au/com/bytecode/opencsv/bean/HeaderColumnNameTranslateMappingStrategyTest.java0000644000175000017500000000701511551741341032501 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; /** Copyright 2007 Kyle Miller. 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. */ import org.junit.Test; import java.io.StringReader; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; public class HeaderColumnNameTranslateMappingStrategyTest { @Test public void testParse() { String s = "n,o,foo\n" + "kyle,123456,emp123\n" + "jimmy,abcnum,cust09878"; HeaderColumnNameTranslateMappingStrategy strat = new HeaderColumnNameTranslateMappingStrategy(); strat.setType(MockBean.class); Map map = new HashMap(); map.put("n", "name"); map.put("o", "orderNumber"); map.put("foo", "id"); strat.setColumnMapping(map); CsvToBean csv = new CsvToBean(); List list = csv.parse(strat, new StringReader(s)); assertNotNull(list); assertTrue(list.size() == 2); MockBean bean = list.get(0); assertEquals("kyle", bean.getName()); assertEquals("123456", bean.getOrderNumber()); assertEquals("emp123", bean.getId()); } @Test public void getColumnNameReturnsNullIfColumnNumberIsTooLarge() { String s = "n,o,foo\n" + "kyle,123456,emp123\n" + "jimmy,abcnum,cust09878"; HeaderColumnNameTranslateMappingStrategy strat = new HeaderColumnNameTranslateMappingStrategy(); strat.setType(MockBean.class); Map map = new HashMap(); map.put("n", "name"); map.put("o", "orderNumber"); map.put("foo", "id"); strat.setColumnMapping(map); CsvToBean csv = new CsvToBean(); List list = csv.parse(strat, new StringReader(s)); assertEquals("name", strat.getColumnName(0)); assertEquals("orderNumber", strat.getColumnName(1)); assertEquals("id", strat.getColumnName(2)); assertNull(strat.getColumnName(3)); } @Test public void columnNameMappingShouldBeCaseInsensitive() { String s = "n,o,Foo\n" + "kyle,123456,emp123\n" + "jimmy,abcnum,cust09878"; HeaderColumnNameTranslateMappingStrategy strat = new HeaderColumnNameTranslateMappingStrategy(); strat.setType(MockBean.class); Map map = new HashMap(); map.put("n", "name"); map.put("o", "orderNumber"); map.put("foo", "id"); strat.setColumnMapping(map); assertNotNull(strat.getColumnMapping()); CsvToBean csv = new CsvToBean(); List list = csv.parse(strat, new StringReader(s)); assertEquals("name", strat.getColumnName(0)); assertEquals("orderNumber", strat.getColumnName(1)); assertEquals("id", strat.getColumnName(2)); assertNull(strat.getColumnName(3)); } } opencsv-2.3/test/au/com/bytecode/opencsv/bean/HeaderColumnNameMappingStrategyTest.java0000644000175000017500000000533311551741341030624 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; /** Copyright 2007 Kyle Miller. 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. */ import au.com.bytecode.opencsv.CSVReader; import org.junit.Test; import java.beans.IntrospectionException; import java.io.IOException; import java.io.StringReader; import java.util.List; import static org.junit.Assert.*; public class HeaderColumnNameMappingStrategyTest { private static final String TEST_STRING = "name,orderNumber,num\n" + "kyle,abc123456,123\n" + "jimmy,def098765,456"; private List createTestParseResult() { HeaderColumnNameMappingStrategy strat = new HeaderColumnNameMappingStrategy(); strat.setType(MockBean.class); CsvToBean csv = new CsvToBean(); return csv.parse(strat, new StringReader(TEST_STRING)); } @Test public void testParse() { List list = createTestParseResult(); assertNotNull(list); assertTrue(list.size() == 2); MockBean bean = list.get(0); assertEquals("kyle", bean.getName()); assertEquals("abc123456", bean.getOrderNumber()); assertEquals(123, bean.getNum()); } @Test public void testParseWithSpacesInHeader() { List list = createTestParseResult(); assertNotNull(list); assertTrue(list.size() == 2); MockBean bean = list.get(0); assertEquals("kyle", bean.getName()); assertEquals("abc123456", bean.getOrderNumber()); assertEquals(123, bean.getNum()); } @Test public void verifyColumnNames() throws IOException, IntrospectionException { HeaderColumnNameMappingStrategy strat = new HeaderColumnNameMappingStrategy(); strat.setType(MockBean.class); assertNull(strat.getColumnName(0)); assertNull(strat.findDescriptor(0)); StringReader reader = new StringReader(TEST_STRING); CSVReader csvReader = new CSVReader(reader); strat.captureHeader(csvReader); assertEquals("name", strat.getColumnName(0)); assertEquals(strat.findDescriptor(0), strat.findDescriptor("name")); assertTrue(strat.matches("name", strat.findDescriptor("name"))); } } opencsv-2.3/test/au/com/bytecode/opencsv/UniCodeTest.java0000644000175000017500000001174011551741341023036 0ustar ebourgebourgpackage au.com.bytecode.opencsv; import org.junit.Test; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class UniCodeTest { CSVParser csvParser; private static final String COMPOUND_STRING = "??,??"; private static final String COMPOUND_STRING_WITH_QUOTES = "\"??\",\"??\""; private static final String FIRST_STRING = "??"; private static final String SECOND_STRING = "??"; private static final String[] UNICODE_ARRAY = {FIRST_STRING, SECOND_STRING}; private static final String[] MIXED_ARRAY = {"eins, 1", "ichi",FIRST_STRING, SECOND_STRING}; private static final String[] ASCII_ARRAY = {"foo", "bar"}; private static final String ASCII_STRING_WITH_QUOTES = "\"foo\",\"bar\""; @Test public void canParseUnicode() throws IOException { csvParser = new CSVParser(); String simpleString = COMPOUND_STRING; String[] items = csvParser.parseLine(simpleString); assertEquals(2, items.length); assertEquals(FIRST_STRING, items[0]); assertEquals(SECOND_STRING, items[1]); assertArrayEquals(UNICODE_ARRAY, items); } @Test public void readerTest() throws IOException { BufferedReader reader = new BufferedReader(new StringReader(FIRST_STRING)); String testString = reader.readLine(); assertEquals(FIRST_STRING, testString); } @Test public void writerTest(){ StringWriter sw = new StringWriter(); sw.write(FIRST_STRING); assertEquals(FIRST_STRING, sw.toString()); } @Test public void runUniCodeThroughCSVReader() throws IOException { CSVReader reader = new CSVReader(new StringReader(COMPOUND_STRING)); String[] items = reader.readNext(); assertEquals(2, items.length); assertEquals(FIRST_STRING, items[0]); assertEquals(SECOND_STRING, items[1]); assertArrayEquals(UNICODE_ARRAY, items); } @Test public void runUniCodeThroughCSVWriter() { StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeNext(UNICODE_ARRAY); assertEquals(COMPOUND_STRING_WITH_QUOTES.trim(), sw.toString().trim()); } @Test public void runASCIIThroughCSVWriter() { StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeNext(ASCII_ARRAY); assertEquals(ASCII_STRING_WITH_QUOTES.trim(), sw.toString().trim()); } @Test public void writeThenReadAscii() throws IOException { StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeNext(ASCII_ARRAY); CSVReader reader = new CSVReader(new StringReader(sw.toString())); String[] items = reader.readNext(); assertEquals(2, items.length); assertArrayEquals(ASCII_ARRAY, items); } @Test public void writeThenReadTwiceAscii() throws IOException { StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeNext(ASCII_ARRAY); writer.writeNext(ASCII_ARRAY); CSVReader reader = new CSVReader(new StringReader(sw.toString())); List lines = reader.readAll(); assertEquals(2, lines.size()); String[] items = lines.get(0); assertEquals(2, items.length); assertArrayEquals(ASCII_ARRAY, items); items = lines.get(1); assertEquals(2, items.length); assertArrayEquals(ASCII_ARRAY, items); } @Test public void writeThenReadTwiceUnicode() throws IOException { StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeNext(UNICODE_ARRAY); writer.writeNext(UNICODE_ARRAY); CSVReader reader = new CSVReader(new StringReader(sw.toString())); List lines = reader.readAll(); assertEquals(2, lines.size()); String[] items = lines.get(0); assertEquals(2, items.length); assertArrayEquals(UNICODE_ARRAY, items); items = lines.get(1); assertEquals(2, items.length); assertArrayEquals(UNICODE_ARRAY, items); } @Test public void writeThenReadTwiceMixedUnicode() throws IOException { StringWriter sw = new StringWriter(); CSVWriter writer = new CSVWriter(sw); writer.writeNext(MIXED_ARRAY); writer.writeNext(MIXED_ARRAY); CSVReader reader = new CSVReader(new StringReader(sw.toString())); List lines = reader.readAll(); assertEquals(2, lines.size()); String[] items = lines.get(0); assertEquals(4, items.length); assertArrayEquals(MIXED_ARRAY, items); items = lines.get(1); assertEquals(4, items.length); assertArrayEquals(MIXED_ARRAY, items); } } opencsv-2.3/test/au/com/bytecode/opencsv/MockResultSetMetaData.java0000644000175000017500000001137411551741341025020 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * Created by IntelliJ IDEA. * User: scott * Date: Dec 13, 2009 * Time: 10:27:13 PM * To change this template use File | Settings | File Templates. */ public class MockResultSetMetaData implements ResultSetMetaData { String[] columnNames; int[] columnTypes; public void setColumnNames(String[] names) { columnNames = names; } public void setColumnTypes(int[] types) { columnTypes = types; } public int getColumnCount() throws SQLException { return columnNames.length; } public boolean isAutoIncrement(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isCaseSensitive(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isSearchable(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isCurrency(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public int isNullable(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean isSigned(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public int getColumnDisplaySize(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public String getColumnLabel(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getColumnName(int i) throws SQLException { return columnNames[i-1]; //To change body of implemented methods use File | Settings | File Templates. } public String getSchemaName(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public int getPrecision(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int getScale(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public String getTableName(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getCatalogName(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public int getColumnType(int i) throws SQLException { return columnTypes[i-1]; } public String getColumnTypeName(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isReadOnly(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isWritable(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isDefinitelyWritable(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public String getColumnClassName(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public T unwrap(Class tClass) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isWrapperFor(Class aClass) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } } opencsv-2.3/test/au/com/bytecode/opencsv/OpencsvTest.java0000644000175000017500000000361511551741341023127 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import static org.junit.Assert.assertTrue; public class OpencsvTest { private File tempFile = null; private CSVWriter writer = null; private CSVReader reader = null; @Before public void setUp() throws IOException { tempFile = File.createTempFile("csvWriterTest", ".csv"); tempFile.deleteOnExit(); } /** * Test the full cycle of write-read * */ @Test public void testWriteRead() throws IOException { final String[][] data = new String[][]{{"hello, a test", "one nested \" test"}, {"\"\"", "test", null, "8"}}; writer = new CSVWriter(new FileWriter(tempFile)); for (String[] aData : data) { writer.writeNext(aData); } writer.close(); reader = new CSVReader(new FileReader(tempFile)); String[] line; for (int row = 0; (line = reader.readNext()) != null; row++) { assertTrue(line.length == data[row].length); for (int col = 0; col < line.length; col++) { if (data[row][col] == null) { assertTrue(line[col].equals("")); } else { assertTrue(line[col].equals(data[row][col])); } } } reader.close(); } } opencsv-2.3/test/au/com/bytecode/opencsv/MockResultSet.java0000644000175000017500000007465011551741341023425 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.util.Calendar; import java.util.Map; /** * Created by IntelliJ IDEA. * User: scott * Date: Dec 12, 2009 * Time: 10:15:03 AM * To change this template use File | Settings | File Templates. */ public class MockResultSet implements ResultSet { private int numberOfResults = 0; private ResultSetMetaData metaData; private String[] columnValues; private boolean lastValueReadNull; private void setLastValueReadNull(String value){ lastValueReadNull = (value == null); } public void setColumnValues(String[] values) { columnValues = values; } public void setNumberOfResults(int results){ numberOfResults = results; } public void setMetaData(ResultSetMetaData data) { metaData = data; } public boolean next() throws SQLException { return numberOfResults-- > 0; //To change body of implemented methods use File | Settings | File Templates. } public void close() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public boolean wasNull() throws SQLException { return lastValueReadNull; //To change body of implemented methods use File | Settings | File Templates. } public String getString(int i) throws SQLException { return columnValues[i-1]; } public boolean getBoolean(int i) throws SQLException { return Boolean.valueOf(columnValues[i-1]); //To change body of implemented methods use File | Settings | File Templates. } public byte getByte(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public short getShort(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int getInt(int i) throws SQLException { setLastValueReadNull(columnValues[i-1]); return columnValues[i-1] == null ? 0 : Integer.valueOf(columnValues[i-1]); } public long getLong(int i) throws SQLException { setLastValueReadNull(columnValues[i-1]); return columnValues[i-1] == null ? 0 : Long.valueOf(columnValues[i-1]); } public float getFloat(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public double getDouble(int i) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public BigDecimal getBigDecimal(int i, int i1) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public byte[] getBytes(int i) throws SQLException { return new byte[0]; //To change body of implemented methods use File | Settings | File Templates. } public Date getDate(int i) throws SQLException { return columnValues[i-1] == null ? null : new Date(Long.valueOf(columnValues[i-1])); } public Time getTime(int i) throws SQLException { return columnValues[i-1] == null ? null : new Time(Long.valueOf(columnValues[i-1])); } public Timestamp getTimestamp(int i) throws SQLException { return columnValues[i-1] == null ? null : new Timestamp(Long.valueOf(columnValues[i-1])); } public InputStream getAsciiStream(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public InputStream getUnicodeStream(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public InputStream getBinaryStream(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getString(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean getBoolean(String s) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public byte getByte(String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public short getShort(String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int getInt(String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public long getLong(String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public float getFloat(String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public double getDouble(String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public BigDecimal getBigDecimal(String s, int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public byte[] getBytes(String s) throws SQLException { return new byte[0]; //To change body of implemented methods use File | Settings | File Templates. } public Date getDate(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Time getTime(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Timestamp getTimestamp(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public InputStream getAsciiStream(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public InputStream getUnicodeStream(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public InputStream getBinaryStream(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public SQLWarning getWarnings() throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void clearWarnings() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public String getCursorName() throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public ResultSetMetaData getMetaData() throws SQLException { return metaData; } public Object getObject(int i) throws SQLException { setLastValueReadNull(columnValues[i-1]); return columnValues[i-1]; //To change body of implemented methods use File | Settings | File Templates. } public Object getObject(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public int findColumn(String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public Reader getCharacterStream(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Reader getCharacterStream(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public BigDecimal getBigDecimal(int i) throws SQLException { setLastValueReadNull(columnValues[i-1]); return columnValues[i-1] == null ? null : new BigDecimal(columnValues[i-1]); } public BigDecimal getBigDecimal(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isBeforeFirst() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isAfterLast() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isFirst() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isLast() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public void beforeFirst() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void afterLast() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public boolean first() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean last() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public int getRow() throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean absolute(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean relative(int i) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean previous() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public void setFetchDirection(int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public int getFetchDirection() throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public void setFetchSize(int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public int getFetchSize() throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int getType() throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int getConcurrency() throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean rowUpdated() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean rowInserted() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean rowDeleted() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public void updateNull(int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBoolean(int i, boolean b) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateByte(int i, byte b) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateShort(int i, short s) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateInt(int i, int i1) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateLong(int i, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateFloat(int i, float v) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateDouble(int i, double v) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBigDecimal(int i, BigDecimal bigDecimal) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateString(int i, String s) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBytes(int i, byte[] bytes) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateDate(int i, Date date) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateTime(int i, Time time) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateTimestamp(int i, Timestamp timestamp) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateAsciiStream(int i, InputStream inputStream, int i1) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBinaryStream(int i, InputStream inputStream, int i1) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateCharacterStream(int i, Reader reader, int i1) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateObject(int i, Object o, int i1) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateObject(int i, Object o) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNull(String s) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBoolean(String s, boolean b) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateByte(String s, byte b) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateShort(String s, short i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateInt(String s, int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateLong(String s, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateFloat(String s, float v) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateDouble(String s, double v) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBigDecimal(String s, BigDecimal bigDecimal) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateString(String s, String s1) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBytes(String s, byte[] bytes) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateDate(String s, Date date) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateTime(String s, Time time) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateTimestamp(String s, Timestamp timestamp) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateAsciiStream(String s, InputStream inputStream, int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBinaryStream(String s, InputStream inputStream, int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateCharacterStream(String s, Reader reader, int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateObject(String s, Object o, int i) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateObject(String s, Object o) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void insertRow() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateRow() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void deleteRow() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void refreshRow() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void cancelRowUpdates() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void moveToInsertRow() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void moveToCurrentRow() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public Statement getStatement() throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object getObject(int i, Map> stringClassMap) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Ref getRef(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Blob getBlob(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Clob getClob(int i) throws SQLException { return columnValues[i-1] == null ? null : new MockClob(columnValues[i-1]); } public Array getArray(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Object getObject(String s, Map> stringClassMap) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Ref getRef(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Blob getBlob(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Clob getClob(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Array getArray(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Date getDate(int i, Calendar calendar) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Date getDate(String s, Calendar calendar) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Time getTime(int i, Calendar calendar) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Time getTime(String s, Calendar calendar) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Timestamp getTimestamp(int i, Calendar calendar) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Timestamp getTimestamp(String s, Calendar calendar) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public URL getURL(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public URL getURL(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void updateRef(int i, Ref ref) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateRef(String s, Ref ref) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBlob(int i, Blob blob) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBlob(String s, Blob blob) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateClob(int i, Clob clob) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateClob(String s, Clob clob) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateArray(int i, Array array) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateArray(String s, Array array) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public int getHoldability() throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean isClosed() throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } public void updateNString(int i, String s) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNString(String s, String s1) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public String getNString(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public String getNString(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Reader getNCharacterStream(int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Reader getNCharacterStream(String s) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void updateNCharacterStream(int i, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNCharacterStream(String s, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateAsciiStream(int i, InputStream inputStream, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBinaryStream(int i, InputStream inputStream, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateCharacterStream(int i, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateAsciiStream(String s, InputStream inputStream, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBinaryStream(String s, InputStream inputStream, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateCharacterStream(String s, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBlob(int i, InputStream inputStream, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBlob(String s, InputStream inputStream, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateClob(int i, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateClob(String s, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNClob(int i, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNClob(String s, Reader reader, long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNCharacterStream(int i, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNCharacterStream(String s, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateAsciiStream(int i, InputStream inputStream) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBinaryStream(int i, InputStream inputStream) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateCharacterStream(int i, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateAsciiStream(String s, InputStream inputStream) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBinaryStream(String s, InputStream inputStream) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateCharacterStream(String s, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBlob(int i, InputStream inputStream) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateBlob(String s, InputStream inputStream) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateClob(int i, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateClob(String s, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNClob(int i, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void updateNClob(String s, Reader reader) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public T unwrap(Class tClass) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isWrapperFor(Class aClass) throws SQLException { return false; //To change body of implemented methods use File | Settings | File Templates. } } opencsv-2.3/test/au/com/bytecode/opencsv/CSVWriterTest.java0000644000175000017500000003244111551741341023341 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import org.junit.Test; import java.io.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class CSVWriterTest { /** * Test routine for converting output to a string. * * @param args * the elements of a line of the cvs file * @return a String version * @throws IOException * if there are problems writing */ private String invokeWriter(String[] args) throws IOException { StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw,',','\''); csvw.writeNext(args); return sw.toString(); } private String invokeNoEscapeWriter(String[] args) throws IOException { StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw,CSVWriter.DEFAULT_SEPARATOR,'\'', CSVWriter.NO_ESCAPE_CHARACTER); csvw.writeNext(args); return sw.toString(); } @Test public void correctlyParseNullString(){ StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw,',','\''); csvw.writeNext(null); assertEquals(0, sw.toString().length()); } /** * Tests parsing individual lines. * * @throws IOException * if the reader fails. */ @Test public void testParseLine() throws IOException { // test normal case String[] normal = { "a", "b", "c" }; String output = invokeWriter(normal); assertEquals("'a','b','c'\n", output); // test quoted commas String[] quoted = { "a", "b,b,b", "c" }; output = invokeWriter(quoted); assertEquals("'a','b,b,b','c'\n", output); // test empty elements String[] empty = { , }; output = invokeWriter(empty); assertEquals("\n", output); // test multiline quoted String[] multiline = { "This is a \n multiline entry", "so is \n this" }; output = invokeWriter(multiline); assertEquals("'This is a \n multiline entry','so is \n this'\n", output); // test quoted line String[] quoteLine = { "This is a \" multiline entry", "so is \n this" }; output = invokeWriter(quoteLine); assertEquals("'This is a \"\" multiline entry','so is \n this'\n", output); } @Test public void parseLineWithBothEscapeAndQuoteChar() throws IOException { // test quoted line String[] quoteLine = { "This is a 'multiline' entry", "so is \n this" }; String output = invokeWriter(quoteLine); assertEquals("'This is a \"'multiline\"' entry','so is \n this'\n", output); } /** * Tests parsing individual lines. * * @throws IOException * if the reader fails. */ @Test public void testParseLineWithNoEscapeChar() throws IOException { // test normal case String[] normal = { "a", "b", "c" }; String output = invokeNoEscapeWriter(normal); assertEquals("'a','b','c'\n", output); // test quoted commas String[] quoted = { "a", "b,b,b", "c" }; output = invokeNoEscapeWriter(quoted); assertEquals("'a','b,b,b','c'\n", output); // test empty elements String[] empty = { , }; output = invokeNoEscapeWriter(empty); assertEquals("\n", output); // test multiline quoted String[] multiline = { "This is a \n multiline entry", "so is \n this" }; output = invokeNoEscapeWriter(multiline); assertEquals("'This is a \n multiline entry','so is \n this'\n", output); } @Test public void parseLineWithNoEscapeCharAndQuotes() throws IOException { String[] quoteLine = { "This is a \" 'multiline' entry", "so is \n this" }; String output = invokeNoEscapeWriter(quoteLine); assertEquals("'This is a \" 'multiline' entry','so is \n this'\n", output); } /** * Test parsing from to a list. * * @throws IOException * if the reader fails. */ @Test public void testParseAll() throws IOException { List allElements = new ArrayList(); String[] line1 = "Name#Phone#Email".split("#"); String[] line2 = "Glen#1234#glen@abcd.com".split("#"); String[] line3 = "John#5678#john@efgh.com".split("#"); allElements.add(line1); allElements.add(line2); allElements.add(line3); StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw); csvw.writeAll(allElements); String result = sw.toString(); String[] lines = result.split("\n"); assertEquals(3, lines.length); } /** * Tests the option of having omitting quotes in the output stream. * * @throws IOException if bad things happen */ @Test public void testNoQuoteChars() throws IOException { String[] line = {"Foo","Bar","Baz"}; StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); csvw.writeNext(line); String result = sw.toString(); assertEquals("Foo,Bar,Baz\n",result); } /** * Tests the option of having omitting quotes in the output stream. * * @throws IOException if bad things happen */ @Test public void testNoQuoteCharsAndNoEscapeChars() throws IOException { String[] line = {"Foo","Bar","Baz"}; StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER); csvw.writeNext(line); String result = sw.toString(); assertEquals("Foo,Bar,Baz\n",result); } /** * Test null values. * * @throws IOException if bad things happen */ @Test public void testNullValues() throws IOException { String[] line = {"Foo",null,"Bar","baz"}; StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw); csvw.writeNext(line); String result = sw.toString(); assertEquals("\"Foo\",,\"Bar\",\"baz\"\n",result); } @Test public void testStreamFlushing() throws IOException { String WRITE_FILE = "myfile.csv"; String[] nextLine = new String[]{"aaaa", "bbbb","cccc","dddd"}; FileWriter fileWriter = new FileWriter(WRITE_FILE); CSVWriter writer = new CSVWriter(fileWriter); writer.writeNext(nextLine); // If this line is not executed, it is not written in the file. writer.close(); } @Test public void testAlternateEscapeChar() { String[] line = {"Foo","bar's"}; StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw,CSVWriter.DEFAULT_SEPARATOR,CSVWriter.DEFAULT_QUOTE_CHARACTER,'\''); csvw.writeNext(line); assertEquals("\"Foo\",\"bar''s\"\n",sw.toString()); } @Test public void testNoQuotingNoEscaping() { String[] line = {"\"Foo\",\"Bar\""}; StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw,CSVWriter.DEFAULT_SEPARATOR,CSVWriter.NO_QUOTE_CHARACTER,CSVWriter.NO_ESCAPE_CHARACTER); csvw.writeNext(line); assertEquals("\"Foo\",\"Bar\"\n",sw.toString()); } @Test public void testNestedQuotes(){ String[] data = new String[]{"\"\"", "test"}; String oracle = new String("\"\"\"\"\"\",\"test\"\n"); CSVWriter writer=null; File tempFile=null; FileWriter fwriter=null; try{ tempFile = File.createTempFile("csvWriterTest", ".csv"); tempFile.deleteOnExit(); fwriter = new FileWriter(tempFile); writer = new CSVWriter(fwriter); }catch(IOException e){ fail(); } // write the test data: writer.writeNext(data); try{ writer.close(); }catch(IOException e){ fail(); } try{ // assert that the writer was also closed. fwriter.flush(); fail(); }catch(IOException e){ // we should go through here.. } // read the data and compare. FileReader in=null; try{ in = new FileReader(tempFile); }catch(FileNotFoundException e){ fail(); } StringBuilder fileContents = new StringBuilder(CSVWriter.INITIAL_STRING_SIZE); try{ int ch; while((ch = in.read()) != -1){ fileContents.append((char)ch); } in.close(); }catch(IOException e){ fail(); } assertTrue(oracle.equals(fileContents.toString())); } @Test public void testAlternateLineFeeds() { String[] line = {"Foo","Bar","baz"}; StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, "\r"); csvw.writeNext(line); String result = sw.toString(); assertTrue(result.endsWith("\r")); } @Test public void testResultSetWithHeaders() throws SQLException, IOException { String[] header = {"Foo","Bar","baz"}; String[] value = {"v1", "v2", "v3"}; MockResultSetHelper mockHelperService = new MockResultSetHelper(header, value); StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw); csvw.setResultService(mockHelperService); MockResultSet rs = new MockResultSet(); rs.setNumberOfResults(1); csvw.writeAll(rs, true); // don't need a result set since I am mocking the result. assertFalse(csvw.checkError()); String result = sw.toString(); assertNotNull(result); assertEquals("\"Foo\",\"Bar\",\"baz\"\n\"v1\",\"v2\",\"v3\"\n", result); } @Test public void testMultiLineResultSetWithHeaders() throws SQLException, IOException { String[] header = {"Foo","Bar","baz"}; String[] value = {"v1", "v2", "v3"}; MockResultSetHelper mockHelperService = new MockResultSetHelper(header, value); StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw); csvw.setResultService(mockHelperService); MockResultSet rs = new MockResultSet(); rs.setNumberOfResults(3); csvw.writeAll(rs, true); // don't need a result set since I am mocking the result. assertFalse(csvw.checkError()); String result = sw.toString(); assertNotNull(result); assertEquals("\"Foo\",\"Bar\",\"baz\"\n\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n", result); } @Test public void testResultSetWithoutHeaders() throws SQLException, IOException { String[] header = {"Foo","Bar","baz"}; String[] value = {"v1", "v2", "v3"}; MockResultSetHelper mockHelperService = new MockResultSetHelper(header, value); StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw); csvw.setResultService(mockHelperService); MockResultSet rs = new MockResultSet(); rs.setNumberOfResults(1); csvw.writeAll(rs, false); // don't need a result set since I am mocking the result. assertFalse(csvw.checkError()); String result = sw.toString(); assertNotNull(result); assertEquals("\"v1\",\"v2\",\"v3\"\n", result); } @Test public void testMultiLineResultSetWithoutHeaders() throws SQLException, IOException { String[] header = {"Foo","Bar","baz"}; String[] value = {"v1", "v2", "v3"}; MockResultSetHelper mockHelperService = new MockResultSetHelper(header, value); StringWriter sw = new StringWriter(); CSVWriter csvw = new CSVWriter(sw); csvw.setResultService(mockHelperService); MockResultSet rs = new MockResultSet(); rs.setNumberOfResults(3); csvw.writeAll(rs, false); // don't need a result set since I am mocking the result. assertFalse(csvw.checkError()); String result = sw.toString(); assertNotNull(result); assertEquals("\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n", result); } } opencsv-2.3/test/au/com/bytecode/opencsv/MockClob.java0000644000175000017500000000615011551741341022340 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.*; import java.sql.Clob; import java.sql.SQLException; /** * Created by IntelliJ IDEA. * User: scott * Date: Dec 15, 2009 * Time: 10:10:02 PM * To change this template use File | Settings | File Templates. */ public class MockClob implements Clob { private String clobValue; public MockClob(String value) { clobValue = value; } public long length() throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public String getSubString(long l, int i) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Reader getCharacterStream() throws SQLException { return new StringReader(clobValue); //To change body of implemented methods use File | Settings | File Templates. } public InputStream getAsciiStream() throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public long position(String s, long l) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public long position(Clob clob, long l) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int setString(long l, String s) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public int setString(long l, String s, int i, int i1) throws SQLException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public OutputStream setAsciiStream(long l) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public Writer setCharacterStream(long l) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } public void truncate(long l) throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public void free() throws SQLException { //To change body of implemented methods use File | Settings | File Templates. } public Reader getCharacterStream(long l, long l1) throws SQLException { return null; //To change body of implemented methods use File | Settings | File Templates. } } opencsv-2.3/test/au/com/bytecode/opencsv/MockResultSetHelper.java0000644000175000017500000000250011551741341024546 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by IntelliJ IDEA. * User: scott * Date: Dec 12, 2009 * Time: 9:54:50 AM * To change this template use File | Settings | File Templates. */ public class MockResultSetHelper implements ResultSetHelper { private String[] columnNames; private String[] columnValues; public MockResultSetHelper(String[] names, String[] values) { columnNames = names; columnValues = values; } public String[] getColumnNames(ResultSet rs) throws SQLException { return columnNames; } public String[] getColumnValues(ResultSet rs) throws SQLException, IOException { return columnValues; } } opencsv-2.3/test/au/com/bytecode/opencsv/CSVReaderTest.java0000644000175000017500000003531511551741341023272 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.StringReader; import static org.junit.Assert.*; public class CSVReaderTest { CSVReader csvr; /** * Setup the test. */ @Before public void setUp() throws Exception { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,b,c").append("\n"); // standard case sb.append("a,\"b,b,b\",c").append("\n"); // quoted elements sb.append(",,").append("\n"); // empty elements sb.append("a,\"PO Box 123,\nKippax,ACT. 2615.\nAustralia\",d.\n"); sb.append("\"Glen \"\"The Man\"\" Smith\",Athlete,Developer\n"); // Test quoted quote chars sb.append("\"\"\"\"\"\",\"test\"\n"); // """""","test" representing: "", test sb.append("\"a\nb\",b,\"\nd\",e\n"); csvr = new CSVReader(new StringReader(sb.toString())); } /** * Tests iterating over a reader. * * @throws IOException if the reader fails. */ @Test public void testParseLine() throws IOException { // test normal case String[] nextLine = csvr.readNext(); assertEquals("a", nextLine[0]); assertEquals("b", nextLine[1]); assertEquals("c", nextLine[2]); // test quoted commas nextLine = csvr.readNext(); assertEquals("a", nextLine[0]); assertEquals("b,b,b", nextLine[1]); assertEquals("c", nextLine[2]); // test empty elements nextLine = csvr.readNext(); assertEquals(3, nextLine.length); // test multiline quoted nextLine = csvr.readNext(); assertEquals(3, nextLine.length); // test quoted quote chars nextLine = csvr.readNext(); assertEquals("Glen \"The Man\" Smith", nextLine[0]); nextLine = csvr.readNext(); assertEquals("\"\"", nextLine[0]); // check the tricky situation assertEquals("test", nextLine[1]); // make sure we didn't ruin the next field.. nextLine = csvr.readNext(); assertEquals(4, nextLine.length); //test end of stream assertNull(csvr.readNext()); } @Test public void testParseLineStrictQuote() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,b,c").append("\n"); // standard case sb.append("a,\"b,b,b\",c").append("\n"); // quoted elements sb.append(",,").append("\n"); // empty elements sb.append("a,\"PO Box 123,\nKippax,ACT. 2615.\nAustralia\",d.\n"); sb.append("\"Glen \"\"The Man\"\" Smith\",Athlete,Developer\n"); // Test quoted quote chars sb.append("\"\"\"\"\"\",\"test\"\n"); // """""","test" representing: "", test sb.append("\"a\nb\",b,\"\nd\",e\n"); csvr = new CSVReader(new StringReader(sb.toString()), ',', '\"', true); // test normal case String[] nextLine = csvr.readNext(); assertEquals("", nextLine[0]); assertEquals("", nextLine[1]); assertEquals("", nextLine[2]); // test quoted commas nextLine = csvr.readNext(); assertEquals("", nextLine[0]); assertEquals("b,b,b", nextLine[1]); assertEquals("", nextLine[2]); // test empty elements nextLine = csvr.readNext(); assertEquals(3, nextLine.length); // test multiline quoted nextLine = csvr.readNext(); assertEquals(3, nextLine.length); // test quoted quote chars nextLine = csvr.readNext(); assertEquals("Glen \"The Man\" Smith", nextLine[0]); nextLine = csvr.readNext(); assertTrue(nextLine[0].equals("\"\"")); // check the tricky situation assertTrue(nextLine[1].equals("test")); // make sure we didn't ruin the next field.. nextLine = csvr.readNext(); assertEquals(4, nextLine.length); assertEquals("a\nb", nextLine[0]); assertEquals("", nextLine[1]); assertEquals("\nd", nextLine[2]); assertEquals("", nextLine[3]); //test end of stream assertNull(csvr.readNext()); } /** * Test parsing to a list. * * @throws IOException if the reader fails. */ @Test public void testParseAll() throws IOException { assertEquals(7, csvr.readAll().size()); } /** * Tests constructors with optional delimiters and optional quote char. * * @throws IOException if the reader fails. */ @Test public void testOptionalConstructors() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a\tb\tc").append("\n"); // tab separated case sb.append("a\t'b\tb\tb'\tc").append("\n"); // single quoted elements CSVReader c = new CSVReader(new StringReader(sb.toString()), '\t', '\''); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); nextLine = c.readNext(); assertEquals(3, nextLine.length); } @Test public void parseQuotedStringWithDefinedSeperator() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a\tb\tc").append("\n"); // tab separated case CSVReader c = new CSVReader(new StringReader(sb.toString()), '\t'); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); } /** * Tests option to skip the first few lines of a file. * * @throws IOException if bad things happen */ @Test public void testSkippingLines() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("Skip this line\t with tab").append("\n"); // should skip this sb.append("And this line too").append("\n"); // and this sb.append("a\t'b\tb\tb'\tc").append("\n"); // single quoted elements CSVReader c = new CSVReader(new StringReader(sb.toString()), '\t', '\'', 2); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); } /** * Tests option to skip the first few lines of a file. * * @throws IOException if bad things happen */ @Test public void testSkippingLinesWithDifferentEscape() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("Skip this line?t with tab").append("\n"); // should skip this sb.append("And this line too").append("\n"); // and this sb.append("a\t'b\tb\tb'\t'c'").append("\n"); // single quoted elements CSVReader c = new CSVReader(new StringReader(sb.toString()), '\t', '\'', '?', 2); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals("c", nextLine[2]); } /** * Test a normal non quoted line with three elements * * @throws IOException */ @Test public void testNormalParsedLine() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,1234567,c").append("\n");// a,1234,c CSVReader c = new CSVReader(new StringReader(sb.toString())); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals("1234567", nextLine[1]); assertEquals("c", nextLine[2]); } /** * Same as testADoubleQuoteAsDataElement but I changed the quotechar to a * single quote. * * @throws IOException */ @Test public void testASingleQuoteAsDataElement() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,'''',c").append("\n");// a,',c CSVReader c = new CSVReader(new StringReader(sb.toString()), ',', '\''); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals(1, nextLine[1].length()); assertEquals("\'", nextLine[1]); assertEquals("c", nextLine[2]); } /** * Same as testADoubleQuoteAsDataElement but I changed the quotechar to a * single quote. Also the middle field is empty. * * @throws IOException */ @Test public void testASingleQuoteAsDataElementWithEmptyField() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,'',c").append("\n");// a,,c CSVReader c = new CSVReader(new StringReader(sb.toString()), ',', '\''); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals(0, nextLine[1].length()); assertEquals("", nextLine[1]); assertEquals("c", nextLine[2]); } @Test public void testSpacesAtEndOfString() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("\"a\",\"b\",\"c\" "); CSVReader c = new CSVReader(new StringReader(sb.toString()), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, true); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals("b", nextLine[1]); assertEquals("c", nextLine[2]); } @Test public void testEscapedQuote() throws IOException { StringBuffer sb = new StringBuffer(); sb.append("a,\"123\\\"4567\",c").append("\n");// a,123"4",c CSVReader c = new CSVReader(new StringReader(sb.toString())); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("123\"4567", nextLine[1]); } @Test public void testEscapedEscape() throws IOException { StringBuffer sb = new StringBuffer(); sb.append("a,\"123\\\\4567\",c").append("\n");// a,123"4",c CSVReader c = new CSVReader(new StringReader(sb.toString())); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("123\\4567", nextLine[1]); } /** * Test a line where one of the elements is two single quotes and the * quote character is the default double quote. The expected result is two * single quotes. * * @throws IOException */ @Test public void testSingleQuoteWhenDoubleQuoteIsQuoteChar() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,'',c").append("\n");// a,'',c CSVReader c = new CSVReader(new StringReader(sb.toString())); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals(2, nextLine[1].length()); assertEquals("''", nextLine[1]); assertEquals("c", nextLine[2]); } /** * Test a normal line with three elements and all elements are quoted * * @throws IOException */ @Test public void testQuotedParsedLine() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("\"a\",\"1234567\",\"c\"").append("\n"); // "a","1234567","c" CSVReader c = new CSVReader(new StringReader(sb.toString()), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, true); String[] nextLine = c.readNext(); assertEquals(3, nextLine.length); assertEquals("a", nextLine[0]); assertEquals(1, nextLine[0].length()); assertEquals("1234567", nextLine[1]); assertEquals("c", nextLine[2]); } @Test public void testIssue2992134OutOfPlaceQuotes() throws IOException { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,b,c,ddd\\\"eee\nf,g,h,\"iii,jjj\""); CSVReader c = new CSVReader(new StringReader(sb.toString())); String[] nextLine = c.readNext(); assertEquals("a", nextLine[0]); assertEquals("b", nextLine[1]); assertEquals("c", nextLine[2]); assertEquals("ddd\"eee", nextLine[3]); } @Test(expected = UnsupportedOperationException.class) public void quoteAndEscapeMustBeDifferent() { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,b,c,ddd\\\"eee\nf,g,h,\"iii,jjj\""); CSVReader c = new CSVReader(new StringReader(sb.toString()), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVReader.DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE); } @Test(expected = UnsupportedOperationException.class) public void separatorAndEscapeMustBeDifferent() { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,b,c,ddd\\\"eee\nf,g,h,\"iii,jjj\""); CSVReader c = new CSVReader(new StringReader(sb.toString()), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_SEPARATOR, CSVReader.DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE); } @Test(expected = UnsupportedOperationException.class) public void separatorAndQuoteMustBeDifferent() { StringBuilder sb = new StringBuilder(CSVParser.INITIAL_READ_SIZE); sb.append("a,b,c,ddd\\\"eee\nf,g,h,\"iii,jjj\""); CSVReader c = new CSVReader(new StringReader(sb.toString()), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_ESCAPE_CHARACTER, CSVReader.DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE); } } opencsv-2.3/test/au/com/bytecode/opencsv/ResultSetHelperServiceTest.java0000644000175000017500000003442611551741341026131 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import org.junit.Test; import java.io.IOException; import java.sql.*; import java.text.SimpleDateFormat; import static org.junit.Assert.assertArrayEquals; /** * Created by IntelliJ IDEA. * User: scott * Date: Dec 13, 2009 * Time: 12:34:58 AM * To change this template use File | Settings | File Templates. */ public class ResultSetHelperServiceTest { private static final String BUILDSTRING = "abcdefghijklmnopqrstuvwxyz"; @Test public void canPrintColumnNames() throws SQLException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"name1", "name2", "name3"}; metaData.setColumnNames(expectedNames); resultSet.setMetaData(metaData); ResultSetHelperService service = new ResultSetHelperService(); String[] columnNames = service.getColumnNames(resultSet); assertArrayEquals(expectedNames, columnNames); } @Test public void getObjectFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"object", "Null Object"}; String[] realValues = {"foo", null}; String[] expectedValues = {"foo", ""}; int[] expectedTypes = {Types.JAVA_OBJECT,Types.JAVA_OBJECT}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getBitFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"bit", "Null bit"}; String[] realValues = {"1", null}; String[] expectedValues = {"1", ""}; int[] expectedTypes = {Types.BIT,Types.BIT}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getBooleanFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"true", "false", "TRUE", "FALSE", "Null"}; String[] realValues = {"true", "false", "TRUE", "FALSE", null}; String[] expectedValues = {"true", "false", "true", "false", "false"}; int[] expectedTypes = {Types.BOOLEAN,Types.BOOLEAN,Types.BOOLEAN,Types.BOOLEAN,Types.BOOLEAN}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getBigIntFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"BigInt", "Null BigInt"}; String[] realValues = {"100", null}; String[] expectedValues = {"100", ""}; int[] expectedTypes = {Types.BIGINT,Types.BIGINT}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getBigDecimalFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"Decimal", "double", "float", "real", "numeric", "Null"}; String[] realValues = {"1.1", "2.2", "3.3", "4.4", "5.5", null}; String[] expectedValues = {"1.1", "2.2", "3.3", "4.4", "5.5", ""}; int[] expectedTypes = {Types.DECIMAL,Types.DOUBLE,Types.FLOAT,Types.REAL,Types.NUMERIC,Types.DECIMAL}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getIntegerFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"Integer", "tinyint", "smallint", "Null"}; String[] realValues = {"1", "2", "3", null}; String[] expectedValues = {"1", "2", "3", ""}; int[] expectedTypes = {Types.INTEGER,Types.TINYINT,Types.SMALLINT,Types.INTEGER}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getCharFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"longvarchar", "varchar", "char", "Null"}; String[] realValues = {"a", "b", "c", null}; String[] expectedValues = {"a", "b", "c", ""}; int[] expectedTypes = {Types.LONGVARCHAR,Types.VARCHAR,Types.CHAR,Types.CHAR}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getUnsupportedFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String[] expectedNames = {"Array", "Null"}; String[] realValues = {"1", null}; String[] expectedValues = {"", ""}; int[] expectedTypes = {Types.ARRAY,Types.ARRAY}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getDateFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); Date date = new Date(109, 11, 15); // 12/15/2009 long dateInMilliSeconds = date.getTime(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy"); String[] expectedNames = {"Date", "Null"}; String[] realValues = {Long.toString(dateInMilliSeconds), null}; String[] expectedValues = {dateFormat.format(date), ""}; int[] expectedTypes = {Types.DATE,Types.DATE}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getTimeFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); Time time = new Time(12, 0, 0); // noon long dateInMilliSeconds = time.getTime(); String[] expectedNames = {"Time", "Null"}; String[] realValues = {Long.toString(dateInMilliSeconds), null}; String[] expectedValues = {time.toString(), ""}; int[] expectedTypes = {Types.TIME,Types.TIME}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getTimestampFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); Timestamp date = new Timestamp(109, 11, 15, 12, 0, 0, 0); // 12/15/2009 noon long dateInMilliSeconds = date.getTime(); SimpleDateFormat timeFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); String[] expectedNames = {"Timestamp", "Null"}; String[] realValues = {Long.toString(dateInMilliSeconds), null}; String[] expectedValues = {timeFormat.format(date), ""}; int[] expectedTypes = {Types.TIMESTAMP,Types.TIMESTAMP}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getClobFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String clobString = buildClobString(20); String[] expectedNames = {"Clob", "Null"}; String[] realValues = {clobString, null}; String[] expectedValues = {clobString, ""}; int[] expectedTypes = {Types.CLOB,Types.CLOB}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getEmptyClobFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String clobString = buildClobString(0); String[] expectedNames = {"Clob", "Null"}; String[] realValues = {clobString, null}; String[] expectedValues = {clobString, ""}; int[] expectedTypes = {Types.CLOB,Types.CLOB}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } @Test public void getLargeClobFromResultSet() throws SQLException, IOException { MockResultSet resultSet = new MockResultSet(); MockResultSetMetaData metaData = new MockResultSetMetaData(); String clobString = buildClobString(ResultSetHelperService.CLOBBUFFERSIZE + 1); String[] expectedNames = {"Clob", "Null"}; String[] realValues = {clobString, null}; String[] expectedValues = {clobString, ""}; int[] expectedTypes = {Types.CLOB,Types.CLOB}; metaData.setColumnNames(expectedNames); metaData.setColumnTypes(expectedTypes); resultSet.setMetaData(metaData); resultSet.setColumnValues(realValues); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); } private String buildClobString(int clobsize) { int iterations = clobsize / BUILDSTRING.length(); int substrsize = clobsize % BUILDSTRING.length(); StringBuilder sb = new StringBuilder(clobsize); for (int i = 0; i < iterations; i++) { sb.append(BUILDSTRING); } if (substrsize > 0) { sb.append(BUILDSTRING.substring(0, substrsize)); } return sb.toString(); } } opencsv-2.3/test/au/com/bytecode/opencsv/TestUtilitiesTest.java0000644000175000017500000000122411551741341024317 0ustar ebourgebourgpackage au.com.bytecode.opencsv; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by IntelliJ IDEA. * User: scott * Date: 12/20/10 * Time: 2:57 PM * To change this template use File | Settings | File Templates. */ public class TestUtilitiesTest { @Test public void displayStringArray() { String[] stringArray = new String[3]; stringArray[0] = "a"; stringArray[1] = "b"; stringArray[2] = "c"; assertEquals("Header\nNumber of elements:\t3\nelement 0:\ta\nelement 1:\tb\nelement 2:\tc\n", TestUtilities.displayStringArray("Header", stringArray)); } } opencsv-2.3/test/integrationTest/0000755000175000017500000000000012146650024016525 5ustar ebourgebourgopencsv-2.3/test/integrationTest/issue2153020/0000755000175000017500000000000012146650024020412 5ustar ebourgebourgopencsv-2.3/test/integrationTest/issue2153020/Sample.csv0000644000175000017500000000112511551741341022351 0ustar ebourgebourgPresentation Catalog,Presentation Table,Presentation Column,Business Model,Derived logical table,Derived logical column,Expression,Logical Table,Logical Column,Logical Table Source,Expression,Initialization Block,Variable,Database,Physical Catalog,Physical Schema,Physical Table,Alias,Physical Column Accounts Payable Quickstart,Accounts Payable Measures,Transaction Number,NF DWH Quickstart,,,,CAP Accounts Payable Overview,Transaction Number,CAP_ACCNTS_PAYABLE_OVERVIEW,QSDB."".QS_DWH.CAP_ACCNTS_PAYABLE_OVERVIEW.TRANSACTION_NUMBER,,,QSDB,,QS_DWH,CAP_ACCNTS_PAYABLE_OVERVIEW,,TRANSACTION_NUMBER opencsv-2.3/test/integrationTest/issue2153020/DataReader.java0000644000175000017500000000142211551741341023252 0ustar ebourgebourg/** * */ package integrationTest.issue2153020; import au.com.bytecode.opencsv.CSVReader; import java.io.FileReader; import java.io.IOException; /** * @author scott * */ public class DataReader { private static final String ADDRESS_FILE="test/integrationTest/issue2153020/Sample.csv"; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE)); String [] nextLine; while ((nextLine = reader.readNext()) != null) { int numLines = nextLine.length; System.out.println("Number of Data Items: " + numLines); for (int i = 0; i < numLines; i++) { System.out.println(" nextLine[" + i + "]: " + nextLine[i]); } } } } opencsv-2.3/test/integrationTest/issue2564366/0000755000175000017500000000000012146650024020435 5ustar ebourgebourgopencsv-2.3/test/integrationTest/issue2564366/data.csv0000644000175000017500000000046211551741341022067 0ustar ebourgebourg"CompanyName","CompanyNumber","ClientName","ClientFirstName","ClientLastName","ClientId","ClientGroupId","Logon","LogonPW","PublishKey","HiddenKey","PublishEncryptMode","LanFolderId","StaffId" "MLBInc","4","Art Walk","","Art Walk","",',"artwalk","artwalk","art1publishkey","art1workkey","1","012345678","" opencsv-2.3/test/integrationTest/issue2564366/DataReader.java0000644000175000017500000000226311551741341023301 0ustar ebourgebourg/** * */ package integrationTest.issue2564366; import au.com.bytecode.opencsv.CSVReader; import java.io.FileReader; import java.io.IOException; /** * @author scott * */ public class DataReader { private static final String ADDRESS_FILE="test/integrationTest/issue2564366/data.csv"; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE)); String [] nextLine; while ((nextLine = reader.readNext()) != null) { System.out.println("CompanyName: [" + nextLine[0] + "]\nCompanyNumber: [" + nextLine[1] + "]\nClientName: [" + nextLine[2] + "]"); System.out.println("ClientFirstName: [" + nextLine[3] + "]\nClientLastName: [" + nextLine[4] + "]\nClientId: [" + nextLine[5] + "]"); System.out.println("ClientGroupId: [" + nextLine[6] + "]\nLogon: [" + nextLine[7] + "]\nLogonPW: [" + nextLine[8] + "]"); System.out.println("PublishKey: [" + nextLine[9] + "]\nHiddenKey: [" + nextLine[10] + "]\nPublishEncryptMode: [" + nextLine[11] + "]"); System.out.println("LanFolderId: [" + nextLine[12] + "]\nStaffId: [" + nextLine[13] + "]\n"); } } } opencsv-2.3/test/integrationTest/issue3189428/0000755000175000017500000000000012146650024020440 5ustar ebourgebourgopencsv-2.3/test/integrationTest/issue3189428/CsvSample.java0000644000175000017500000001424411551741341023207 0ustar ebourgebourgpackage integrationTest.issue3189428; import au.com.bytecode.opencsv.CSVParser; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy; import au.com.bytecode.opencsv.bean.CsvToBean; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.List; public class CsvSample { String filePath = "test/integrationTest/issue3189428/mysample.csv"; public static void main(String[] args) throws Exception { CsvSample sample = new CsvSample(); sample.doSample(); } public CsvSample() { } public void doSample() throws Exception { // First write String[] fields = new String[5]; fields[0] = "field1"; fields[1] = "3.0"; fields[2] = "3,147.25"; fields[3] = "$3,147.26"; // failing string fields[4] = "Joe said, \"This is a test of a \nlong broken string,\" and Sally said, \"I bet it won't work.\" "; // working string // fields[4] = "Joe said, \"This is a test of a \nlong broken string,\" and Sally said, \"I bet it won't work.\""; CSVWriter writer = new CSVWriter(new FileWriter(filePath)); writer.writeNext(fields); // let's make 3 rows so we can see it cleanly in Excel. writer.writeNext(fields); writer.writeNext(fields); writer.close(); testRawCsvRead(fields[4]); testMappingStrategyRead(fields[4]); System.out.println("\nComplete. File written out to " + filePath); } /** * This approach seems to work correctly, even with embedded newlines. * * @param originalCommentText * @throws FileNotFoundException * @throws IOException */ protected void testRawCsvRead(String originalCommentText) throws FileNotFoundException, IOException { CSVReader reader = new CSVReader(new FileReader(filePath)); String[] nextLine = null; int count = 0; while ((nextLine = reader.readNext()) != null) { if (!nextLine[0].equals("field1")) { System.out.println("RawCsvRead Assert Error: Name is wrong."); } if (!nextLine[1].equals("3.0")) { System.out.println("RawCsvRead Assert Error: Value is wrong."); } if (!nextLine[2].equals("3,147.25")) { System.out.println("RawCsvRead Assert Error: Amount1 is wrong."); } if (!nextLine[3].equals("$3,147.26")) { System.out.println("RawCsvRead Assert Error: Currency is wrong."); } System.out.println("Field 4 read: " + nextLine[4]); if (!nextLine[4].equals(originalCommentText)) { System.out.println("RawCsvRead Assert Error: Comment is wrong."); } count++; } if (count != 3) { System.out.println("RawCsvRead Assert Error: Count of lines is wrong."); } } /** * This approach seems to fail with embedded newlines; that might be a weakness of * the mapping strategy support classes. * * @param originalCommentText * @throws FileNotFoundException */ protected void testMappingStrategyRead(String originalCommentText) throws FileNotFoundException { ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy(); mappingStrategy.setType(MyBean.class); String[] columns = new String[]{"name", "value", "amount1", "currency", "comments"}; // the fields to bind to in your JavaBean mappingStrategy.setColumnMapping(columns); CsvToBean csv = new CsvToBean(); CSVReader reader = new CSVReader(new FileReader(filePath), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, 0, false, false); List list = csv.parse(mappingStrategy, reader); if (list.size() != 3) { System.out.println("Error - list size is wrong."); } MyBean myBean = list.get(2); if (!myBean.getName().equals("field1")) { System.out.println("MappingStrategy Assert Error: Name is wrong."); } if (!myBean.getValue().equals("3.0")) { System.out.println("MappingStrategy Assert Error: Value is wrong."); } if (!myBean.getAmount1().equals("3,147.25")) { System.out.println("MappingStrategy Assert Error: Amount1 is wrong."); } if (!myBean.getCurrency().equals("$3,147.26")) { System.out.println("MappingStrategy Assert Error: Currency is wrong."); } printfield("MyBeanComments: ", myBean.getComments()); printfield("OriginalCommentText: ", originalCommentText); if (!myBean.getComments().equals(originalCommentText)) { System.out.println("MappingStrategy Assert Error: Comment is wrong."); } } private void printfield(String header, String field) { System.out.println(header + field); System.out.println("fieldlen: " + field.length()); } public static class MyBean { String name; String value; String amount1; String currency; String comments; public MyBean() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getAmount1() { return amount1; } public void setAmount1(String amount1) { this.amount1 = amount1; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } } } opencsv-2.3/src/0000755000175000017500000000000012146650024013152 5ustar ebourgebourgopencsv-2.3/src/au/0000755000175000017500000000000012146650024013557 5ustar ebourgebourgopencsv-2.3/src/au/com/0000755000175000017500000000000012146650024014335 5ustar ebourgebourgopencsv-2.3/src/au/com/bytecode/0000755000175000017500000000000012146650024016133 5ustar ebourgebourgopencsv-2.3/src/au/com/bytecode/opencsv/0000755000175000017500000000000012146650024017610 5ustar ebourgebourgopencsv-2.3/src/au/com/bytecode/opencsv/ResultSetHelper.java0000644000175000017500000000162011551741341023546 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; /** * * * * * */ public interface ResultSetHelper { public String[] getColumnNames(ResultSet rs) throws SQLException; public String[] getColumnValues(ResultSet rs) throws SQLException, IOException; } opencsv-2.3/src/au/com/bytecode/opencsv/bean/0000755000175000017500000000000012146650024020515 5ustar ebourgebourgopencsv-2.3/src/au/com/bytecode/opencsv/bean/ColumnPositionMappingStrategy.java0000644000175000017500000000252311551741341027405 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; import au.com.bytecode.opencsv.CSVReader; import java.io.IOException; /** Copyright 2007 Kyle Miller. 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. */ public class ColumnPositionMappingStrategy extends HeaderColumnNameMappingStrategy { private String[] columnMapping = new String[] {}; public void captureHeader(CSVReader reader) throws IOException { //do nothing, first line is not header } protected String getColumnName(int col) { return (null != columnMapping && col < columnMapping.length) ? columnMapping[col] : null ; } public String[] getColumnMapping() { return columnMapping != null ? columnMapping.clone() : null; } public void setColumnMapping(String[] columnMapping) { this.columnMapping = columnMapping != null ? columnMapping.clone() : null; } } opencsv-2.3/src/au/com/bytecode/opencsv/bean/CsvToBean.java0000644000175000017500000000760211551741341023213 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; /** Copyright 2007 Kyle Miller. 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. */ import au.com.bytecode.opencsv.CSVReader; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.io.Reader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CsvToBean { private Map, PropertyEditor> editorMap = null; public CsvToBean() { } public List parse(MappingStrategy mapper, Reader reader) { return parse(mapper, new CSVReader(reader)); } public List parse(MappingStrategy mapper, CSVReader csv) { try { mapper.captureHeader(csv); String[] line; List list = new ArrayList(); while (null != (line = csv.readNext())) { T obj = processLine(mapper, line); list.add(obj); // TODO: (Kyle) null check object } return list; } catch (Exception e) { throw new RuntimeException("Error parsing CSV!", e); } } protected T processLine(MappingStrategy mapper, String[] line) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException { T bean = mapper.createBean(); for (int col = 0; col < line.length; col++) { PropertyDescriptor prop = mapper.findDescriptor(col); if (null != prop) { String value = checkForTrim(line[col], prop); Object obj = convertValue(value, prop); prop.getWriteMethod().invoke(bean, obj); } } return bean; } private String checkForTrim(String s, PropertyDescriptor prop) { return trimmableProperty(prop) ? s.trim() : s; } private boolean trimmableProperty(PropertyDescriptor prop) { return !prop.getPropertyType().getName().contains("String"); } protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException, IllegalAccessException { PropertyEditor editor = getPropertyEditor(prop); Object obj = value; if (null != editor) { editor.setAsText(value); obj = editor.getValue(); } return obj; } private PropertyEditor getPropertyEditorValue(Class cls) { if (editorMap == null) { editorMap = new HashMap, PropertyEditor>(); } PropertyEditor editor = editorMap.get(cls); if (editor == null) { editor = PropertyEditorManager.findEditor(cls); addEditorToMap(cls, editor); } return editor; } private void addEditorToMap(Class cls, PropertyEditor editor) { if (editor != null) { editorMap.put(cls, editor); } } /* * Attempt to find custom property editor on descriptor first, else try the propery editor manager. */ protected PropertyEditor getPropertyEditor(PropertyDescriptor desc) throws InstantiationException, IllegalAccessException { Class cls = desc.getPropertyEditorClass(); if (null != cls) return (PropertyEditor) cls.newInstance(); return getPropertyEditorValue(desc.getPropertyType()); } } opencsv-2.3/src/au/com/bytecode/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java0000644000175000017500000000240611551741341031450 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; import java.util.HashMap; import java.util.Map; /** Copyright 2007,2010 Kyle Miller. 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. */ public class HeaderColumnNameTranslateMappingStrategy extends HeaderColumnNameMappingStrategy { private Map columnMapping = new HashMap(); protected String getColumnName(int col) { return col < header.length ? columnMapping.get(header[col].toUpperCase()) : null; } public Map getColumnMapping() { return columnMapping; } public void setColumnMapping(Map columnMapping) { for (String key : columnMapping.keySet()) { this.columnMapping.put(key.toUpperCase(), columnMapping.get(key)); } } } opencsv-2.3/src/au/com/bytecode/opencsv/bean/HeaderColumnNameMappingStrategy.java0000644000175000017500000000557111551741341027600 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; import au.com.bytecode.opencsv.CSVReader; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Copyright 2007 Kyle Miller. *

* 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. */ public class HeaderColumnNameMappingStrategy implements MappingStrategy { protected String[] header; protected Map descriptorMap = null; protected Class type; public void captureHeader(CSVReader reader) throws IOException { header = reader.readNext(); } public PropertyDescriptor findDescriptor(int col) throws IntrospectionException { String columnName = getColumnName(col); return (null != columnName && columnName.trim().length() > 0) ? findDescriptor(columnName) : null; } protected String getColumnName(int col) { return (null != header && col < header.length) ? header[col] : null; } protected PropertyDescriptor findDescriptor(String name) throws IntrospectionException { if (null == descriptorMap) descriptorMap = loadDescriptorMap(getType()); //lazy load descriptors return descriptorMap.get(name.toUpperCase().trim()); } protected boolean matches(String name, PropertyDescriptor desc) { return desc.getName().equals(name.trim()); } protected Map loadDescriptorMap(Class cls) throws IntrospectionException { Map map = new HashMap(); PropertyDescriptor[] descriptors; descriptors = loadDescriptors(getType()); for (PropertyDescriptor descriptor : descriptors) { map.put(descriptor.getName().toUpperCase().trim(), descriptor); } return map; } private PropertyDescriptor[] loadDescriptors(Class cls) throws IntrospectionException { BeanInfo beanInfo = Introspector.getBeanInfo(cls); return beanInfo.getPropertyDescriptors(); } public T createBean() throws InstantiationException, IllegalAccessException { return type.newInstance(); } public Class getType() { return type; } public void setType(Class type) { this.type = type; } } opencsv-2.3/src/au/com/bytecode/opencsv/bean/MappingStrategy.java0000644000175000017500000000306611551741341024505 0ustar ebourgebourgpackage au.com.bytecode.opencsv.bean; /** Copyright 2007 Kyle Miller. 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. */ import au.com.bytecode.opencsv.CSVReader; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.IOException; public interface MappingStrategy { /** * Implementation will have to return a property descriptor from a bean based on the current column. * @param col the column to find the description for * @throws java.beans.IntrospectionException * @return the related PropertyDescriptor */ public abstract PropertyDescriptor findDescriptor(int col) throws IntrospectionException; public abstract T createBean() throws InstantiationException, IllegalAccessException; /** * Implementation of this method can grab the header line before parsing begins to use to map columns * to bean properties. * @param reader the CSVReader to use for header parsing * @throws java.io.IOException if parsing fails */ public void captureHeader(CSVReader reader) throws IOException; }opencsv-2.3/src/au/com/bytecode/opencsv/bean/package.html0000644000175000017500000000041311551741341022776 0ustar ebourgebourg

A simple bean binding interface for use with opencsv.


opencsv.sourceforge.net opencsv-2.3/src/au/com/bytecode/opencsv/CSVParser.java0000644000175000017500000002726711551741341022303 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * A very simple CSV parser released under a commercial-friendly license. * This just implements splitting a single line into fields. * * @author Glen Smith * @author Rainer Pruy */ public class CSVParser { private final char separator; private final char quotechar; private final char escape; private final boolean strictQuotes; private String pending; private boolean inField = false; private final boolean ignoreLeadingWhiteSpace; /** * The default separator to use if none is supplied to the constructor. */ public static final char DEFAULT_SEPARATOR = ','; public static final int INITIAL_READ_SIZE = 128; /** * The default quote character to use if none is supplied to the * constructor. */ public static final char DEFAULT_QUOTE_CHARACTER = '"'; /** * The default escape character to use if none is supplied to the * constructor. */ public static final char DEFAULT_ESCAPE_CHARACTER = '\\'; /** * The default strict quote behavior to use if none is supplied to the * constructor */ public static final boolean DEFAULT_STRICT_QUOTES = false; /** * The default leading whitespace behavior to use if none is supplied to the * constructor */ public static final boolean DEFAULT_IGNORE_LEADING_WHITESPACE = true; /** * This is the "null" character - if a value is set to this then it is ignored. * I.E. if the quote character is set to null then there is no quote character. */ public static final char NULL_CHARACTER = '\0'; /** * Constructs CSVParser using a comma for the separator. */ public CSVParser() { this(DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER); } /** * Constructs CSVParser with supplied separator. * * @param separator the delimiter to use for separating entries. */ public CSVParser(char separator) { this(separator, DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER); } /** * Constructs CSVParser with supplied separator and quote char. * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements */ public CSVParser(char separator, char quotechar) { this(separator, quotechar, DEFAULT_ESCAPE_CHARACTER); } /** * Constructs CSVReader with supplied separator and quote char. * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements * @param escape the character to use for escaping a separator or quote */ public CSVParser(char separator, char quotechar, char escape) { this(separator, quotechar, escape, DEFAULT_STRICT_QUOTES); } /** * Constructs CSVReader with supplied separator and quote char. * Allows setting the "strict quotes" flag * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements * @param escape the character to use for escaping a separator or quote * @param strictQuotes if true, characters outside the quotes are ignored */ public CSVParser(char separator, char quotechar, char escape, boolean strictQuotes) { this(separator, quotechar, escape, strictQuotes, DEFAULT_IGNORE_LEADING_WHITESPACE); } /** * Constructs CSVReader with supplied separator and quote char. * Allows setting the "strict quotes" and "ignore leading whitespace" flags * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements * @param escape the character to use for escaping a separator or quote * @param strictQuotes if true, characters outside the quotes are ignored * @param ignoreLeadingWhiteSpace if true, white space in front of a quote in a field is ignored */ public CSVParser(char separator, char quotechar, char escape, boolean strictQuotes, boolean ignoreLeadingWhiteSpace) { if (anyCharactersAreTheSame(separator, quotechar, escape)) { throw new UnsupportedOperationException("The separator, quote, and escape characters must be different!"); } if (separator == NULL_CHARACTER) { throw new UnsupportedOperationException("The separator character must be defined!"); } this.separator = separator; this.quotechar = quotechar; this.escape = escape; this.strictQuotes = strictQuotes; this.ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace; } private boolean anyCharactersAreTheSame(char separator, char quotechar, char escape) { return isSameCharacter(separator, quotechar) || isSameCharacter(separator, escape) || isSameCharacter(quotechar, escape); } private boolean isSameCharacter(char c1, char c2) { return c1 != NULL_CHARACTER && c1 == c2; } /** * @return true if something was left over from last call(s) */ public boolean isPending() { return pending != null; } public String[] parseLineMulti(String nextLine) throws IOException { return parseLine(nextLine, true); } public String[] parseLine(String nextLine) throws IOException { return parseLine(nextLine, false); } /** * Parses an incoming String and returns an array of elements. * * @param nextLine the string to parse * @param multi * @return the comma-tokenized list of elements, or null if nextLine is null * @throws IOException if bad things happen during the read */ private String[] parseLine(String nextLine, boolean multi) throws IOException { if (!multi && pending != null) { pending = null; } if (nextLine == null) { if (pending != null) { String s = pending; pending = null; return new String[]{s}; } else { return null; } } List tokensOnThisLine = new ArrayList(); StringBuilder sb = new StringBuilder(INITIAL_READ_SIZE); boolean inQuotes = false; if (pending != null) { sb.append(pending); pending = null; inQuotes = true; } for (int i = 0; i < nextLine.length(); i++) { char c = nextLine.charAt(i); if (c == this.escape) { if (isNextCharacterEscapable(nextLine, inQuotes || inField, i)) { sb.append(nextLine.charAt(i + 1)); i++; } } else if (c == quotechar) { if (isNextCharacterEscapedQuote(nextLine, inQuotes || inField, i)) { sb.append(nextLine.charAt(i + 1)); i++; } else { //inQuotes = !inQuotes; // the tricky case of an embedded quote in the middle: a,bc"d"ef,g if (!strictQuotes) { if (i > 2 //not on the beginning of the line && nextLine.charAt(i - 1) != this.separator //not at the beginning of an escape sequence && nextLine.length() > (i + 1) && nextLine.charAt(i + 1) != this.separator //not at the end of an escape sequence ) { if (ignoreLeadingWhiteSpace && sb.length() > 0 && isAllWhiteSpace(sb)) { sb.setLength(0); //discard white space leading up to quote } else { sb.append(c); //continue; } } } inQuotes = !inQuotes; } inField = !inField; } else if (c == separator && !inQuotes) { tokensOnThisLine.add(sb.toString()); sb.setLength(0); // start work on next token inField = false; } else { if (!strictQuotes || inQuotes) { sb.append(c); inField = true; } } } // line is done - check status if (inQuotes) { if (multi) { // continuing a quoted section, re-append newline sb.append("\n"); pending = sb.toString(); sb = null; // this partial content is not to be added to field list yet } else { throw new IOException("Un-terminated quoted field at end of CSV line"); } } if (sb != null) { tokensOnThisLine.add(sb.toString()); } return tokensOnThisLine.toArray(new String[tokensOnThisLine.size()]); } /** * precondition: the current character is a quote or an escape * * @param nextLine the current line * @param inQuotes true if the current context is quoted * @param i current index in line * @return true if the following character is a quote */ private boolean isNextCharacterEscapedQuote(String nextLine, boolean inQuotes, int i) { return inQuotes // we are in quotes, therefore there can be escaped quotes in here. && nextLine.length() > (i + 1) // there is indeed another character to check. && nextLine.charAt(i + 1) == quotechar; } /** * precondition: the current character is an escape * * @param nextLine the current line * @param inQuotes true if the current context is quoted * @param i current index in line * @return true if the following character is a quote */ protected boolean isNextCharacterEscapable(String nextLine, boolean inQuotes, int i) { return inQuotes // we are in quotes, therefore there can be escaped quotes in here. && nextLine.length() > (i + 1) // there is indeed another character to check. && (nextLine.charAt(i + 1) == quotechar || nextLine.charAt(i + 1) == this.escape); } /** * precondition: sb.length() > 0 * * @param sb A sequence of characters to examine * @return true if every character in the sequence is whitespace */ protected boolean isAllWhiteSpace(CharSequence sb) { boolean result = true; for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if (!Character.isWhitespace(c)) { return false; } } return result; } } opencsv-2.3/src/au/com/bytecode/opencsv/ResultSetHelperService.java0000644000175000017500000001230611551741341025072 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.sql.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * * * helper class for processing JDBC ResultSet objects * * */ public class ResultSetHelperService implements ResultSetHelper { public static final int CLOBBUFFERSIZE = 2048; // note: we want to maintain compatibility with Java 5 VM's // These types don't exist in Java 5 private static final int NVARCHAR = -9; private static final int NCHAR = -15; private static final int LONGNVARCHAR = -16; private static final int NCLOB = 2011; public String[] getColumnNames(ResultSet rs) throws SQLException { List names = new ArrayList(); ResultSetMetaData metadata = rs.getMetaData(); for (int i = 0; i < metadata.getColumnCount(); i++) { names.add(metadata.getColumnName(i+1)); } String[] nameArray = new String[names.size()]; return names.toArray(nameArray); } public String[] getColumnValues(ResultSet rs) throws SQLException, IOException { List values = new ArrayList(); ResultSetMetaData metadata = rs.getMetaData(); for (int i = 0; i < metadata.getColumnCount(); i++) { values.add(getColumnValue(rs, metadata.getColumnType(i + 1), i + 1)); } String[] valueArray = new String[values.size()]; return values.toArray(valueArray); } private String handleObject(Object obj){ return obj == null ? "" : String.valueOf(obj); } private String handleBigDecimal(BigDecimal decimal) { return decimal == null ? "" : decimal.toString(); } private String handleLong(ResultSet rs, int columnIndex) throws SQLException { long lv = rs.getLong(columnIndex); return rs.wasNull() ? "" : Long.toString(lv); } private String handleInteger(ResultSet rs, int columnIndex) throws SQLException { int i = rs.getInt(columnIndex); return rs.wasNull() ? "" : Integer.toString(i); } private String handleDate(ResultSet rs, int columnIndex) throws SQLException { java.sql.Date date = rs.getDate(columnIndex); String value = null; if (date != null) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy"); value = dateFormat.format(date); } return value; } private String handleTime(Time time) { return time == null ? null : time.toString(); } private String handleTimestamp(Timestamp timestamp) { SimpleDateFormat timeFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); return timestamp == null ? null : timeFormat.format(timestamp); } private String getColumnValue(ResultSet rs, int colType, int colIndex) throws SQLException, IOException { String value = ""; switch (colType) { case Types.BIT: case Types.JAVA_OBJECT: value = handleObject(rs.getObject(colIndex)); break; case Types.BOOLEAN: boolean b = rs.getBoolean(colIndex); value = Boolean.valueOf(b).toString(); break; case NCLOB: // todo : use rs.getNClob case Types.CLOB: Clob c = rs.getClob(colIndex); if (c != null) { value = read(c); } break; case Types.BIGINT: value = handleLong(rs, colIndex); break; case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.REAL: case Types.NUMERIC: value = handleBigDecimal(rs.getBigDecimal(colIndex)); break; case Types.INTEGER: case Types.TINYINT: case Types.SMALLINT: value = handleInteger(rs, colIndex); break; case Types.DATE: value = handleDate(rs, colIndex); break; case Types.TIME: value = handleTime(rs.getTime(colIndex)); break; case Types.TIMESTAMP: value = handleTimestamp(rs.getTimestamp(colIndex)); break; case NVARCHAR: // todo : use rs.getNString case NCHAR: // todo : use rs.getNString case LONGNVARCHAR: // todo : use rs.getNString case Types.LONGVARCHAR: case Types.VARCHAR: case Types.CHAR: value = rs.getString(colIndex); break; default: value = ""; } if (value == null) { value = ""; } return value; } private static String read(Clob c) throws SQLException, IOException { StringBuilder sb = new StringBuilder( (int) c.length()); Reader r = c.getCharacterStream(); char[] cbuf = new char[CLOBBUFFERSIZE]; int n; while ((n = r.read(cbuf, 0, cbuf.length)) != -1) { sb.append(cbuf, 0, n); } return sb.toString(); } } opencsv-2.3/src/au/com/bytecode/opencsv/CSVReader.java0000644000175000017500000002274211551741341022242 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; /** * A very simple CSV reader released under a commercial-friendly license. * * @author Glen Smith * */ public class CSVReader implements Closeable { private BufferedReader br; private boolean hasNext = true; private CSVParser parser; private int skipLines; private boolean linesSkiped; /** * The default line to start reading. */ public static final int DEFAULT_SKIP_LINES = 0; /** * Constructs CSVReader using a comma for the separator. * * @param reader * the reader to an underlying CSV source. */ public CSVReader(Reader reader) { this(reader, CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER); } /** * Constructs CSVReader with supplied separator. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries. */ public CSVReader(Reader reader, char separator) { this(reader, separator, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER); } /** * Constructs CSVReader with supplied separator and quote char. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements */ public CSVReader(Reader reader, char separator, char quotechar) { this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES); } /** * Constructs CSVReader with supplied separator, quote char and quote handling * behavior. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param strictQuotes * sets if characters outside the quotes are ignored */ public CSVReader(Reader reader, char separator, char quotechar, boolean strictQuotes) { this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, DEFAULT_SKIP_LINES, strictQuotes); } /** * Constructs CSVReader with supplied separator and quote char. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param escape * the character to use for escaping a separator or quote */ public CSVReader(Reader reader, char separator, char quotechar, char escape) { this(reader, separator, quotechar, escape, DEFAULT_SKIP_LINES, CSVParser.DEFAULT_STRICT_QUOTES); } /** * Constructs CSVReader with supplied separator and quote char. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param line * the line number to skip for start reading */ public CSVReader(Reader reader, char separator, char quotechar, int line) { this(reader, separator, quotechar, CSVParser.DEFAULT_ESCAPE_CHARACTER, line, CSVParser.DEFAULT_STRICT_QUOTES); } /** * Constructs CSVReader with supplied separator and quote char. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param escape * the character to use for escaping a separator or quote * @param line * the line number to skip for start reading */ public CSVReader(Reader reader, char separator, char quotechar, char escape, int line) { this(reader, separator, quotechar, escape, line, CSVParser.DEFAULT_STRICT_QUOTES); } /** * Constructs CSVReader with supplied separator and quote char. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param escape * the character to use for escaping a separator or quote * @param line * the line number to skip for start reading * @param strictQuotes * sets if characters outside the quotes are ignored */ public CSVReader(Reader reader, char separator, char quotechar, char escape, int line, boolean strictQuotes) { this(reader, separator, quotechar, escape, line, strictQuotes, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE); } /** * Constructs CSVReader with supplied separator and quote char. * * @param reader * the reader to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param escape * the character to use for escaping a separator or quote * @param line * the line number to skip for start reading * @param strictQuotes * sets if characters outside the quotes are ignored * @param ignoreLeadingWhiteSpace * it true, parser should ignore white space before a quote in a field */ public CSVReader(Reader reader, char separator, char quotechar, char escape, int line, boolean strictQuotes, boolean ignoreLeadingWhiteSpace) { this.br = new BufferedReader(reader); this.parser = new CSVParser(separator, quotechar, escape, strictQuotes, ignoreLeadingWhiteSpace); this.skipLines = line; } /** * Reads the entire file into a List with each element being a String[] of * tokens. * * @return a List of String[], with each String[] representing a line of the * file. * * @throws IOException * if bad things happen during the read */ public List readAll() throws IOException { List allElements = new ArrayList(); while (hasNext) { String[] nextLineAsTokens = readNext(); if (nextLineAsTokens != null) allElements.add(nextLineAsTokens); } return allElements; } /** * Reads the next line from the buffer and converts to a string array. * * @return a string array with each comma-separated element as a separate * entry. * * @throws IOException * if bad things happen during the read */ public String[] readNext() throws IOException { String[] result = null; do { String nextLine = getNextLine(); if (!hasNext) { return result; // should throw if still pending? } String[] r = parser.parseLineMulti(nextLine); if (r.length > 0) { if (result == null) { result = r; } else { String[] t = new String[result.length+r.length]; System.arraycopy(result, 0, t, 0, result.length); System.arraycopy(r, 0, t, result.length, r.length); result = t; } } } while (parser.isPending()); return result; } /** * Reads the next line from the file. * * @return the next line from the file without trailing newline * @throws IOException * if bad things happen during the read */ private String getNextLine() throws IOException { if (!this.linesSkiped) { for (int i = 0; i < skipLines; i++) { br.readLine(); } this.linesSkiped = true; } String nextLine = br.readLine(); if (nextLine == null) { hasNext = false; } return hasNext ? nextLine : null; } /** * Closes the underlying reader. * * @throws IOException if the close fails */ public void close() throws IOException{ br.close(); } } opencsv-2.3/src/au/com/bytecode/opencsv/CSVWriter.java0000644000175000017500000002177511551741341022321 0ustar ebourgebourgpackage au.com.bytecode.opencsv; /** Copyright 2005 Bytecode Pty Ltd. 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. */ import java.io.Closeable; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * A very simple CSV writer released under a commercial-friendly license. * * @author Glen Smith * */ public class CSVWriter implements Closeable { public static final int INITIAL_STRING_SIZE = 128; private Writer rawWriter; private PrintWriter pw; private char separator; private char quotechar; private char escapechar; private String lineEnd; /** The character used for escaping quotes. */ public static final char DEFAULT_ESCAPE_CHARACTER = '"'; /** The default separator to use if none is supplied to the constructor. */ public static final char DEFAULT_SEPARATOR = ','; /** * The default quote character to use if none is supplied to the * constructor. */ public static final char DEFAULT_QUOTE_CHARACTER = '"'; /** The quote constant to use when you wish to suppress all quoting. */ public static final char NO_QUOTE_CHARACTER = '\u0000'; /** The escape constant to use when you wish to suppress all escaping. */ public static final char NO_ESCAPE_CHARACTER = '\u0000'; /** Default line terminator uses platform encoding. */ public static final String DEFAULT_LINE_END = "\n"; private ResultSetHelper resultService = new ResultSetHelperService(); /** * Constructs CSVWriter using a comma for the separator. * * @param writer * the writer to an underlying CSV source. */ public CSVWriter(Writer writer) { this(writer, DEFAULT_SEPARATOR); } /** * Constructs CSVWriter with supplied separator. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries. */ public CSVWriter(Writer writer, char separator) { this(writer, separator, DEFAULT_QUOTE_CHARACTER); } /** * Constructs CSVWriter with supplied separator and quote char. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements */ public CSVWriter(Writer writer, char separator, char quotechar) { this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER); } /** * Constructs CSVWriter with supplied separator and quote char. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param escapechar * the character to use for escaping quotechars or escapechars */ public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) { this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END); } /** * Constructs CSVWriter with supplied separator and quote char. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param lineEnd * the line feed terminator to use */ public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) { this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); } /** * Constructs CSVWriter with supplied separator, quote char, escape char and line ending. * * @param writer * the writer to an underlying CSV source. * @param separator * the delimiter to use for separating entries * @param quotechar * the character to use for quoted elements * @param escapechar * the character to use for escaping quotechars or escapechars * @param lineEnd * the line feed terminator to use */ public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) { this.rawWriter = writer; this.pw = new PrintWriter(writer); this.separator = separator; this.quotechar = quotechar; this.escapechar = escapechar; this.lineEnd = lineEnd; } /** * Writes the entire list to a CSV file. The list is assumed to be a * String[] * * @param allLines * a List of String[], with each String[] representing a line of * the file. */ public void writeAll(List allLines) { for (String[] line : allLines) { writeNext(line); } } protected void writeColumnNames(ResultSet rs) throws SQLException { writeNext(resultService.getColumnNames(rs)); } /** * Writes the entire ResultSet to a CSV file. * * The caller is responsible for closing the ResultSet. * * @param rs the recordset to write * @param includeColumnNames true if you want column names in the output, false otherwise * * @throws java.io.IOException thrown by getColumnValue * @throws java.sql.SQLException thrown by getColumnValue */ public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws SQLException, IOException { if (includeColumnNames) { writeColumnNames(rs); } while (rs.next()) { writeNext(resultService.getColumnValues(rs)); } } /** * Writes the next line to the file. * * @param nextLine * a string array with each comma-separated element as a separate * entry. */ public void writeNext(String[] nextLine) { if (nextLine == null) return; StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); for (int i = 0; i < nextLine.length; i++) { if (i != 0) { sb.append(separator); } String nextElement = nextLine[i]; if (nextElement == null) continue; if (quotechar != NO_QUOTE_CHARACTER) sb.append(quotechar); sb.append(stringContainsSpecialCharacters(nextElement) ? processLine(nextElement) : nextElement); if (quotechar != NO_QUOTE_CHARACTER) sb.append(quotechar); } sb.append(lineEnd); pw.write(sb.toString()); } private boolean stringContainsSpecialCharacters(String line) { return line.indexOf(quotechar) != -1 || line.indexOf(escapechar) != -1; } protected StringBuilder processLine(String nextElement) { StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); for (int j = 0; j < nextElement.length(); j++) { char nextChar = nextElement.charAt(j); if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) { sb.append(escapechar).append(nextChar); } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) { sb.append(escapechar).append(nextChar); } else { sb.append(nextChar); } } return sb; } /** * Flush underlying stream to writer. * * @throws IOException if bad things happen */ public void flush() throws IOException { pw.flush(); } /** * Close the underlying stream writer flushing any buffered content. * * @throws IOException if bad things happen * */ public void close() throws IOException { flush(); pw.close(); rawWriter.close(); } /** * Checks to see if the there has been an error in the printstream. */ public boolean checkError() { return pw.checkError(); } public void setResultService(ResultSetHelper resultService) { this.resultService = resultService; } } opencsv-2.3/src/au/com/bytecode/opencsv/package.html0000644000175000017500000000044511551741341022076 0ustar ebourgebourg

A very simple CSV parser for Java released under a commercial-friendly license.


opencsv.sourceforge.net opencsv-2.3/myfile.csv0000644000175000017500000000003411551741341014364 0ustar ebourgebourg"aaaa","bbbb","cccc","dddd"