diff --git a/.project b/.project index 2c20d1e5..f814688a 100644 --- a/.project +++ b/.project @@ -1,11 +1,11 @@ - - - super-csv-parent - - - - - - - - + + + super-csv-parent + + + + + + + + diff --git a/pom.xml b/pom.xml index 50bdc658..ea42c19d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,481 +1,481 @@ - - - - 4.0.0 - - - - org.sonatype.oss - oss-parent - 7 - - - net.sf.supercsv - super-csv-parent - 2.0.2-SNAPSHOT - pom - http://supercsv.sourceforge.net - Super CSV - Super CSV parent project - 2007 - - - super-csv - super-csv-dozer - super-csv-distribution - - - - UTF-8 - - - - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - 1.9 - - - org.apache.maven.plugins - maven-ant-plugin - 2.3 - - - org.apache.maven.plugins - maven-assembly-plugin - 2.4 - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - - - org.codehaus.mojo - cobertura-maven-plugin - 2.5.1 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.0 - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.9 - - - org.codehaus.mojo - findbugs-maven-plugin - 2.5.2 - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - - - org.apache.maven.plugins - maven-pmd-plugin - 2.7.1 - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - org.apache.maven.plugins - maven-release-plugin - 2.3.2 - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - org.apache.maven.plugins - maven-site-plugin - 3.2 - - - - org.apache.maven.wagon - wagon-ssh - 2.2 - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12.4 - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.12.4 - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.supercsv.* - - - - - bundle-manifest - process-classes - - manifest - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - - org.apache.maven.plugins - maven-site-plugin - - - - - org.apache.maven.plugins - maven-eclipse-plugin - - true - true - true - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5 - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - - org.codehaus.mojo - cobertura-maven-plugin - - - xml - html - - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - - - org.apache.maven.plugins - maven-release-plugin - - true - clean verify - deploy - v@{project.version} - - - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - - - org.codehaus.mojo.signature - java15 - 1.0 - - - - - check-java15-compatability - test - - check - - - - - - - - - - - - net.sf.supercsv - super-csv - ${project.version} - - - net.sf.supercsv - super-csv-dozer - ${project.version} - - - - - - - junit - junit - 4.10 - test - - - - - - - Kasper Graversen - kbg - - Project Lead/Founder - - +1 - - - James Bassett - jamesbassett - james.bassett@gmail.com - +10 - - Developer (current) - - - - Dominique De Vito - ddv36a78 - - Developer (past) - - - - - - - - Alf Richter (Haskell2000) - - - John Gibson (noredshadow) - - - Lubor Vágenknecht (lubor) - - - Pete Lichten (boneshaker335) - - - Thor Michael Støre (thormick) - - - - - Super CSV - http://supercsv.sourceforge.net/ - - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - index - dependencies - project-team - issue-tracking - license - - - - - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.5.1 - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.12.4 - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - true - - http://java.sun.com/j2se/1.5.0/docs/api - http://dozer.sourceforge.net/apidocs - - - - - - javadoc - - - - - - - - org.apache.maven.plugins - maven-pmd-plugin - 2.7.1 - - 1.5 - - - - - - org.codehaus.mojo - findbugs-maven-plugin - 2.5.2 - - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - - - - - - Sourceforge - https://sourceforge.net/p/supercsv/bugs/ - - - - - supercsv.sourceforge.net - scp://shell.sourceforge.net/home/project-web/supercsv/htdocs - - - - - scm:svn:https://svn.code.sf.net/p/supercsv/code/trunk - scm:svn:svn+ssh://jamesbassett@svn.code.sf.net/p/supercsv/code/trunk - https://sourceforge.net/p/supercsv/code/ - + + + + 4.0.0 + + + + org.sonatype.oss + oss-parent + 7 + + + net.sf.supercsv + super-csv-parent + 2.0.2-SNAPSHOT + pom + http://supercsv.sourceforge.net + Super CSV + Super CSV parent project + 2007 + + + super-csv + super-csv-dozer + super-csv-distribution + + + + UTF-8 + + + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.9 + + + org.apache.maven.plugins + maven-ant-plugin + 2.3 + + + org.apache.maven.plugins + maven-assembly-plugin + 2.4 + + + org.apache.felix + maven-bundle-plugin + 2.3.7 + + + org.codehaus.mojo + cobertura-maven-plugin + 2.5.1 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.0 + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.9 + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.2 + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + + org.apache.maven.plugins + maven-pmd-plugin + 2.7.1 + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + org.apache.maven.plugins + maven-release-plugin + 2.3.2 + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + org.apache.maven.plugins + maven-site-plugin + 3.2 + + + + org.apache.maven.wagon + wagon-ssh + 2.2 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12.4 + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.12.4 + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + + org.apache.felix + maven-bundle-plugin + true + + + org.supercsv.* + + + + + bundle-manifest + process-classes + + manifest + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + + org.apache.maven.plugins + maven-site-plugin + + + + + org.apache.maven.plugins + maven-eclipse-plugin + + true + true + true + + + org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5 + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + + org.codehaus.mojo + cobertura-maven-plugin + + + xml + html + + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + attach-javadocs + + jar + + + + + + + + org.apache.maven.plugins + maven-release-plugin + + true + clean verify + deploy + v@{project.version} + + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + + + org.codehaus.mojo.signature + java15 + 1.0 + + + + + check-java15-compatability + test + + check + + + + + + + + + + + + net.sf.supercsv + super-csv + ${project.version} + + + net.sf.supercsv + super-csv-dozer + ${project.version} + + + + + + + junit + junit + 4.10 + test + + + + + + + Kasper Graversen + kbg + + Project Lead/Founder + + +1 + + + James Bassett + jamesbassett + james.bassett@gmail.com + +10 + + Developer (current) + + + + Dominique De Vito + ddv36a78 + + Developer (past) + + + + + + + + Alf Richter (Haskell2000) + + + John Gibson (noredshadow) + + + Lubor Vágenknecht (lubor) + + + Pete Lichten (boneshaker335) + + + Thor Michael Støre (thormick) + + + + + Super CSV + http://supercsv.sourceforge.net/ + + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + index + dependencies + project-team + issue-tracking + license + + + + + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.5.1 + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.12.4 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + true + + http://java.sun.com/j2se/1.5.0/docs/api + http://dozer.sourceforge.net/apidocs + + + + + + javadoc + + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + 2.7.1 + + 1.5 + + + + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.2 + + + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + + + + + Sourceforge + https://sourceforge.net/p/supercsv/bugs/ + + + + + supercsv.sourceforge.net + scp://shell.sourceforge.net/home/project-web/supercsv/htdocs + + + + + scm:svn:https://svn.code.sf.net/p/supercsv/code/trunk + scm:svn:svn+ssh://jamesbassett@svn.code.sf.net/p/supercsv/code/trunk + https://sourceforge.net/p/supercsv/code/ + \ No newline at end of file diff --git a/src/site/apt/cell_processors.apt b/src/site/apt/cell_processors.apt index 1a373f4f..1e35190e 100644 --- a/src/site/apt/cell_processors.apt +++ b/src/site/apt/cell_processors.apt @@ -1,112 +1,112 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - --------------- - Cell Processors - --------------- - -Cell processors - - Cell processors are an integral part of reading and writing with Super CSV - they automate the data type conversions, and enforce constraints. - They implement the design pattern - each processor has a single, well-defined purpose and can be chained - together with other processors to fully automate all of the required conversions and constraint validation for a single CSV column. - - A typical CellProcessor configuration for reading the following CSV file - -+-----------------------------------+ -name,birthDate,weight -John,25/12/1946,83.5 -Alice,06/08/1958, -Bob,01/03/1984,65.0, -+-----------------------------------+ - - might look like the following: - -+---------------------------------------------------------------------------------------------------------------------------------------------+ -public static final CellProcessor[] PROCESSORS = new CellProcessor[] { - null, - new ParseDate("dd/MM/yyyy"), - new Optional(new ParseDouble()) }; -+---------------------------------------------------------------------------------------------------------------------------------------------+ - - The number of elements in the CellProcessor array must match up with the number of columns to be processed - the file has 3 columns, - so the CellProcessor array has 3 elements. - - [[1]] The first processor (for the name column) is <<>>, which indicates that (the String is used unchanged). - Semantically, it might have been better to replace that with <<>>, which means the same thing. - If we wanted to guarantee that name was supplied (i.e. it's mandatory), then we could have used <<>> instead - (which works because empty String (<<<"">>>) is converted to <<>> when reading). - - [[2]] The second processor (for the birthDate column) is <<>>, which indicates that that column is mandatory, - and should be parsed as a Date using the supplied format. - - [[3]] The third processor (for the weight column) is <<>>, which indicates that the column is optional - (the value will be <<>> if the column is empty), but if it's supplied then parse it as a Double. - -* Cell processor overview - - * processors are similar to servlet filters in JEE - they can be chained together, and they can modify the data that's passed along the chain - - * processors are executed from (but yes, the processor's constructors are invoked from right to left!) - - * the number of elements in the CellProcessor array must match up with the number of columns to be processed - - * a <<>> processor means - - * most processors expect input to be non-null - if it's an optional column then chain an <<>> processor before it, e.g. - <<>>. Further processing (processors chained after <<>>) will be skipped if the value to be read/written is <<>>. - - * all processors throw <<>> if they encounter data they cannot process (this shouldn't normally happen if your processor configuration is correct) - - * constraint-validating processors throw <<>> if the value does not satisfy the constraint - -* Available cell processors - - The examples above just touch the surface of what's possible with cell processors. - The following table shows all of the processors available for reading, writing, and constraint validation. - -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - <> || Writing || Reading / Writing || Constraints -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - {{{./apidocs/org/supercsv/cellprocessor/ParseBigDecimal.html}ParseBigDecimal}} | {{{./apidocs/org/supercsv/cellprocessor/FmtBool.html}FmtBool}} | {{{./apidocs/org/supercsv/cellprocessor/ConvertNullTo.html}ConvertNullTo}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/DMinMax.html}DMinMax}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - {{{./apidocs/org/supercsv/cellprocessor/ParseBool.html}ParseBool}} | {{{./apidocs/org/supercsv/cellprocessor/FmtDate.html}FmtDate}} | {{{./apidocs/org/supercsv/cellprocessor/HashMapper.html}HashMapper}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/Equals.html}Equals}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - {{{./apidocs/org/supercsv/cellprocessor/ParseChar.html}ParseChar}} | {{{./apidocs/org/supercsv/cellprocessor/FmtNumber.html}FmtNumber}} | {{{./apidocs/org/supercsv/cellprocessor/Optional.html}Optional}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/ForbidSubStr.html}ForbidSubStr}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - {{{./apidocs/org/supercsv/cellprocessor/ParseDate.html}ParseDate}} | | {{{./apidocs/org/supercsv/cellprocessor/StrReplace.html}StrReplace}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/IsIncludedIn.html}IsIncludedIn}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - {{{./apidocs/org/supercsv/cellprocessor/ParseDouble.html}ParseDouble}} | | {{{./apidocs/org/supercsv/cellprocessor/Token.html}Token}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/LMinMax.html}LMinMax}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - {{{./apidocs/org/supercsv/cellprocessor/ParseInt.html}ParseInt}} | | {{{./apidocs/org/supercsv/cellprocessor/Trim.html}Trim}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/NotNull.html}NotNull}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - {{{./apidocs/org/supercsv/cellprocessor/ParseLong.html}ParseLong}} | | {{{./apidocs/org/supercsv/cellprocessor/Truncate.html}Truncate}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/RequireHashCode.html}RequireHashCode}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/RequireSubStr.html}RequireSubStr}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/Strlen.html}Strlen}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/StrMinMax.html}StrMinMax}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/StrNotNullOrEmpty.html}StrNotNullOrEmpty}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/StrRegEx.html}StrRegEx}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/Unique.html}Unique}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/UniqueHashCode.html}UniqueHashCode}} -*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* - - +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + --------------- + Cell Processors + --------------- + +Cell processors + + Cell processors are an integral part of reading and writing with Super CSV - they automate the data type conversions, and enforce constraints. + They implement the design pattern - each processor has a single, well-defined purpose and can be chained + together with other processors to fully automate all of the required conversions and constraint validation for a single CSV column. + + A typical CellProcessor configuration for reading the following CSV file + ++-----------------------------------+ +name,birthDate,weight +John,25/12/1946,83.5 +Alice,06/08/1958, +Bob,01/03/1984,65.0, ++-----------------------------------+ + + might look like the following: + ++---------------------------------------------------------------------------------------------------------------------------------------------+ +public static final CellProcessor[] PROCESSORS = new CellProcessor[] { + null, + new ParseDate("dd/MM/yyyy"), + new Optional(new ParseDouble()) }; ++---------------------------------------------------------------------------------------------------------------------------------------------+ + + The number of elements in the CellProcessor array must match up with the number of columns to be processed - the file has 3 columns, + so the CellProcessor array has 3 elements. + + [[1]] The first processor (for the name column) is <<>>, which indicates that (the String is used unchanged). + Semantically, it might have been better to replace that with <<>>, which means the same thing. + If we wanted to guarantee that name was supplied (i.e. it's mandatory), then we could have used <<>> instead + (which works because empty String (<<<"">>>) is converted to <<>> when reading). + + [[2]] The second processor (for the birthDate column) is <<>>, which indicates that that column is mandatory, + and should be parsed as a Date using the supplied format. + + [[3]] The third processor (for the weight column) is <<>>, which indicates that the column is optional + (the value will be <<>> if the column is empty), but if it's supplied then parse it as a Double. + +* Cell processor overview + + * processors are similar to servlet filters in JEE - they can be chained together, and they can modify the data that's passed along the chain + + * processors are executed from (but yes, the processor's constructors are invoked from right to left!) + + * the number of elements in the CellProcessor array must match up with the number of columns to be processed + + * a <<>> processor means + + * most processors expect input to be non-null - if it's an optional column then chain an <<>> processor before it, e.g. + <<>>. Further processing (processors chained after <<>>) will be skipped if the value to be read/written is <<>>. + + * all processors throw <<>> if they encounter data they cannot process (this shouldn't normally happen if your processor configuration is correct) + + * constraint-validating processors throw <<>> if the value does not satisfy the constraint + +* Available cell processors + + The examples above just touch the surface of what's possible with cell processors. + The following table shows all of the processors available for reading, writing, and constraint validation. + +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + <> || Writing || Reading / Writing || Constraints +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + {{{./apidocs/org/supercsv/cellprocessor/ParseBigDecimal.html}ParseBigDecimal}} | {{{./apidocs/org/supercsv/cellprocessor/FmtBool.html}FmtBool}} | {{{./apidocs/org/supercsv/cellprocessor/ConvertNullTo.html}ConvertNullTo}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/DMinMax.html}DMinMax}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + {{{./apidocs/org/supercsv/cellprocessor/ParseBool.html}ParseBool}} | {{{./apidocs/org/supercsv/cellprocessor/FmtDate.html}FmtDate}} | {{{./apidocs/org/supercsv/cellprocessor/HashMapper.html}HashMapper}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/Equals.html}Equals}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + {{{./apidocs/org/supercsv/cellprocessor/ParseChar.html}ParseChar}} | {{{./apidocs/org/supercsv/cellprocessor/FmtNumber.html}FmtNumber}} | {{{./apidocs/org/supercsv/cellprocessor/Optional.html}Optional}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/ForbidSubStr.html}ForbidSubStr}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + {{{./apidocs/org/supercsv/cellprocessor/ParseDate.html}ParseDate}} | | {{{./apidocs/org/supercsv/cellprocessor/StrReplace.html}StrReplace}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/IsIncludedIn.html}IsIncludedIn}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + {{{./apidocs/org/supercsv/cellprocessor/ParseDouble.html}ParseDouble}} | | {{{./apidocs/org/supercsv/cellprocessor/Token.html}Token}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/LMinMax.html}LMinMax}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + {{{./apidocs/org/supercsv/cellprocessor/ParseInt.html}ParseInt}} | | {{{./apidocs/org/supercsv/cellprocessor/Trim.html}Trim}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/NotNull.html}NotNull}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + {{{./apidocs/org/supercsv/cellprocessor/ParseLong.html}ParseLong}} | | {{{./apidocs/org/supercsv/cellprocessor/Truncate.html}Truncate}} | {{{./apidocs/org/supercsv/cellprocessor/constraint/RequireHashCode.html}RequireHashCode}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/RequireSubStr.html}RequireSubStr}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/Strlen.html}Strlen}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/StrMinMax.html}StrMinMax}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/StrNotNullOrEmpty.html}StrNotNullOrEmpty}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/StrRegEx.html}StrRegEx}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/Unique.html}Unique}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + | | | {{{./apidocs/org/supercsv/cellprocessor/constraint/UniqueHashCode.html}UniqueHashCode}} +*----------------------------------------------------------------------------------*---------------------------------------------------------------------*-----------------------------------------------------------------------------*-----------------------------------------------------------------------------------------------* + + diff --git a/src/site/apt/csv_specification.apt b/src/site/apt/csv_specification.apt index cf6a372c..402379e6 100644 --- a/src/site/apt/csv_specification.apt +++ b/src/site/apt/csv_specification.apt @@ -1,138 +1,138 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ------------ - What is CSV? - ------------ - -What is CSV? - - The comma-separated values (CSV) format is a widely used text file format often used to exchange data between applications. - It contains multiple records (one per line), and each field is delimited by a comma. - {{{http://en.wikipedia.org/wiki/Comma-separated_values}Wikipedia}} has a good explanation of the CSV format and its history. - - There is no definitive standard for CSV, however the most commonly accepted definition is {{{http://tools.ietf.org/html/rfc4180}RFC 4180}} - - the MIME type definition for CSV. Super CSV is 100% compliant with RFC 4180, while still allowing some flexibility where CSV files deviate from the definition. - - The following shows each rule defined in RFC 4180, and how it is treated by Super CSV. - -* Rule 1 - ------------------------------------------------------------------------------------ -1. Each record is located on a separate line, delimited by a line - break (CRLF). For example: - - aaa,bbb,ccc CRLF - zzz,yyy,xxx CRLF ------------------------------------------------------------------------------------ - - Super CSV accepts all line breaks (Windows, Mac or Unix) when reading CSV files, - and uses the end of line symbols specified by the user (via the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object) when writing CSV files. - -* Rule 2 - ------------------------------------------------------------------------------------ -2. The last record in the file may or may not have an ending line - break. For example: - - aaa,bbb,ccc CRLF - zzz,yyy,xxx ------------------------------------------------------------------------------------ - - Super CSV add a line break when writing the last line of a CSV file, but a line break on the last line is optional when reading. - -* Rule 3 - ------------------------------------------------------------------------------------ -3. There maybe an optional header line appearing as the first line - of the file with the same format as normal record lines. This - header will contain names corresponding to the fields in the file - and should contain the same number of fields as the records in - the rest of the file (the presence or absence of the header line - should be indicated via the optional "header" parameter of this - MIME type). For example: - - field_name,field_name,field_name CRLF - aaa,bbb,ccc CRLF - zzz,yyy,xxx CRLF ------------------------------------------------------------------------------------ - - Super CSV provides methods for reading and writing headers, if required. - It also makes use of the header for mapping between CSV and POJOs (see {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}}/{{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}}). - -* Rule 4 - ------------------------------------------------------------------------------------ -4. Within the header and each record, there may be one or more - fields, separated by commas. Each line should contain the same - number of fields throughout the file. Spaces are considered part - of a field and should not be ignored. The last field in the - record must not be followed by a comma. For example: - - aaa,bbb,ccc ------------------------------------------------------------------------------------ - - The delimiter in Super CSV is configurable via the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object, though it is typically a comma. - - Super CSV expects each line to contain the same number of fields (including the header). - In cases where the number of fields varies, {{{./apidocs/org/supercsv/io/CsvListReader.html}CsvListReader}}/{{{./apidocs/org/supercsv/io/CsvListWriter.html}CsvListWriter}} should be used, as they contain methods for reading/writing lines of arbitrary length. - - By default, Super CSV considers spaces part of a field. However, if you require that surrounding spaces should not be part of the field - (unless within double quotes), then you can enable in your {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object. This will ensure that surrounding spaces are trimmed when reading - (if not within double quotes), and that quotes are applied to a field with surrounding spaces when writing. - -* Rule 5 - ------------------------------------------------------------------------------------ -5. Each field may or may not be enclosed in double quotes (however - some programs, such as Microsoft Excel, do not use double quotes - at all). If fields are not enclosed with double quotes, then - double quotes may not appear inside the fields. For example: - - "aaa","bbb","ccc" CRLF - zzz,yyy,xxx ------------------------------------------------------------------------------------ - - Super CSV only encloses fields in double quotes when they require escaping (see Rule 6). - - The quote character is configurable via the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object, though is typically a double quote (<<<">>>). - -* Rule 6 - ------------------------------------------------------------------------------------ -6. Fields containing line breaks (CRLF), double quotes, and commas - should be enclosed in double-quotes. For example: - - "aaa","b CRLF - bb","ccc" CRLF - zzz,yyy,xxx ------------------------------------------------------------------------------------ - - Super CSV handles multi-line fields (as long as they're enclosed in quotes) when reading, - and encloses a field in quotes when writing if it contains a newline, quote character or delimiter (defined in the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object). - -* Rule 7 - ------------------------------------------------------------------------------------ -7. If double-quotes are used to enclose fields, then a double-quote - appearing inside a field must be escaped by preceding it with - another double quote. For example: - - "aaa","b""bb","ccc" ------------------------------------------------------------------------------------ - - Super CSV escapes double-quotes with a preceding double-quote. Please note that the sometimes-used convention of escaping double-quotes as <<<\">>> (instead of <<<"">>>) - is <>. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ------------ + What is CSV? + ------------ + +What is CSV? + + The comma-separated values (CSV) format is a widely used text file format often used to exchange data between applications. + It contains multiple records (one per line), and each field is delimited by a comma. + {{{http://en.wikipedia.org/wiki/Comma-separated_values}Wikipedia}} has a good explanation of the CSV format and its history. + + There is no definitive standard for CSV, however the most commonly accepted definition is {{{http://tools.ietf.org/html/rfc4180}RFC 4180}} - + the MIME type definition for CSV. Super CSV is 100% compliant with RFC 4180, while still allowing some flexibility where CSV files deviate from the definition. + + The following shows each rule defined in RFC 4180, and how it is treated by Super CSV. + +* Rule 1 + +----------------------------------------------------------------------------------- +1. Each record is located on a separate line, delimited by a line + break (CRLF). For example: + + aaa,bbb,ccc CRLF + zzz,yyy,xxx CRLF +----------------------------------------------------------------------------------- + + Super CSV accepts all line breaks (Windows, Mac or Unix) when reading CSV files, + and uses the end of line symbols specified by the user (via the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object) when writing CSV files. + +* Rule 2 + +----------------------------------------------------------------------------------- +2. The last record in the file may or may not have an ending line + break. For example: + + aaa,bbb,ccc CRLF + zzz,yyy,xxx +----------------------------------------------------------------------------------- + + Super CSV add a line break when writing the last line of a CSV file, but a line break on the last line is optional when reading. + +* Rule 3 + +----------------------------------------------------------------------------------- +3. There maybe an optional header line appearing as the first line + of the file with the same format as normal record lines. This + header will contain names corresponding to the fields in the file + and should contain the same number of fields as the records in + the rest of the file (the presence or absence of the header line + should be indicated via the optional "header" parameter of this + MIME type). For example: + + field_name,field_name,field_name CRLF + aaa,bbb,ccc CRLF + zzz,yyy,xxx CRLF +----------------------------------------------------------------------------------- + + Super CSV provides methods for reading and writing headers, if required. + It also makes use of the header for mapping between CSV and POJOs (see {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}}/{{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}}). + +* Rule 4 + +----------------------------------------------------------------------------------- +4. Within the header and each record, there may be one or more + fields, separated by commas. Each line should contain the same + number of fields throughout the file. Spaces are considered part + of a field and should not be ignored. The last field in the + record must not be followed by a comma. For example: + + aaa,bbb,ccc +----------------------------------------------------------------------------------- + + The delimiter in Super CSV is configurable via the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object, though it is typically a comma. + + Super CSV expects each line to contain the same number of fields (including the header). + In cases where the number of fields varies, {{{./apidocs/org/supercsv/io/CsvListReader.html}CsvListReader}}/{{{./apidocs/org/supercsv/io/CsvListWriter.html}CsvListWriter}} should be used, as they contain methods for reading/writing lines of arbitrary length. + + By default, Super CSV considers spaces part of a field. However, if you require that surrounding spaces should not be part of the field + (unless within double quotes), then you can enable in your {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object. This will ensure that surrounding spaces are trimmed when reading + (if not within double quotes), and that quotes are applied to a field with surrounding spaces when writing. + +* Rule 5 + +----------------------------------------------------------------------------------- +5. Each field may or may not be enclosed in double quotes (however + some programs, such as Microsoft Excel, do not use double quotes + at all). If fields are not enclosed with double quotes, then + double quotes may not appear inside the fields. For example: + + "aaa","bbb","ccc" CRLF + zzz,yyy,xxx +----------------------------------------------------------------------------------- + + Super CSV only encloses fields in double quotes when they require escaping (see Rule 6). + + The quote character is configurable via the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object, though is typically a double quote (<<<">>>). + +* Rule 6 + +----------------------------------------------------------------------------------- +6. Fields containing line breaks (CRLF), double quotes, and commas + should be enclosed in double-quotes. For example: + + "aaa","b CRLF + bb","ccc" CRLF + zzz,yyy,xxx +----------------------------------------------------------------------------------- + + Super CSV handles multi-line fields (as long as they're enclosed in quotes) when reading, + and encloses a field in quotes when writing if it contains a newline, quote character or delimiter (defined in the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} object). + +* Rule 7 + +----------------------------------------------------------------------------------- +7. If double-quotes are used to enclose fields, then a double-quote + appearing inside a field must be escaped by preceding it with + another double quote. For example: + + "aaa","b""bb","ccc" +----------------------------------------------------------------------------------- + + Super CSV escapes double-quotes with a preceding double-quote. Please note that the sometimes-used convention of escaping double-quotes as <<<\">>> (instead of <<<"">>>) + is <>. \ No newline at end of file diff --git a/src/site/apt/downloading.apt.vm b/src/site/apt/downloading.apt.vm index 56655ed0..242b06ff 100644 --- a/src/site/apt/downloading.apt.vm +++ b/src/site/apt/downloading.apt.vm @@ -1,71 +1,71 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - --------------------- - Downloading Super CSV - --------------------- - -Downloading Super CSV - -* Prerequisites - - [Java 1.5+] Super CSV is compiled for Java 1.5 - -* Maven users - - If you are using Maven, simply copy the following dependency into your pom.xml file. - The artifact is hosted at {{{http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22net.sf.supercsv%22}Maven Central}}, and is standalone (no dependencies). - -+-------------------------------------+ - - ${project.groupId} - super-csv - ${project.version} - -+-------------------------------------+ - - If you wish to use the new Dozer extension (with deep mapping and index-based mapping support), - then you will also need the following: - -+-------------------------------------+ - - ${project.groupId} - super-csv-dozer - ${project.version} - -+-------------------------------------+ - -* Everyone else - - You can download the latest distribution zip file from {{{https://sourceforge.net/projects/supercsv/files/latest/download?source=files}SourceForge}}, - which contains: - -*----------------------------------------------------------------+---------------------------------------------------------------------+ - <> || Description -*----------------------------------------------------------------+---------------------------------------------------------------------+ - super-csv/super-csv-${project.version}.jar | Super CSV ${project.version} (compiled classes only) -*----------------------------------------------------------------+---------------------------------------------------------------------+ - super-csv/super-csv-${project.version}-sources.jar | The Super CSV source code -*----------------------------------------------------------------+---------------------------------------------------------------------+ - super-csv/super-csv-${project.version}-javadoc.jar | The Super CSV Javadoc documentation -*----------------------------------------------------------------+---------------------------------------------------------------------+ - super-csv-dozer/super-csv-dozer-${project.version}.jar | Super CSV Dozer extension ${project.version} (compiled classes only) -*----------------------------------------------------------------+---------------------------------------------------------------------+ - super-csv-dozer/super-csv-dozer-${project.version}-sources.jar | The Super CSV Dozer extension source code -*----------------------------------------------------------------+---------------------------------------------------------------------+ - super-csv-dozer/super-csv-dozer-${project.version}-javadoc.jar | The Super CSV Dozer extension Javadoc documentation -*----------------------------------------------------------------+---------------------------------------------------------------------+ - super-csv-dozer/lib | The Super CSV Dozer extension's dependencies (including Dozer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + --------------------- + Downloading Super CSV + --------------------- + +Downloading Super CSV + +* Prerequisites + + [Java 1.5+] Super CSV is compiled for Java 1.5 + +* Maven users + + If you are using Maven, simply copy the following dependency into your pom.xml file. + The artifact is hosted at {{{http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22net.sf.supercsv%22}Maven Central}}, and is standalone (no dependencies). + ++-------------------------------------+ + + ${project.groupId} + super-csv + ${project.version} + ++-------------------------------------+ + + If you wish to use the new Dozer extension (with deep mapping and index-based mapping support), + then you will also need the following: + ++-------------------------------------+ + + ${project.groupId} + super-csv-dozer + ${project.version} + ++-------------------------------------+ + +* Everyone else + + You can download the latest distribution zip file from {{{https://sourceforge.net/projects/supercsv/files/latest/download?source=files}SourceForge}}, + which contains: + +*----------------------------------------------------------------+---------------------------------------------------------------------+ + <> || Description +*----------------------------------------------------------------+---------------------------------------------------------------------+ + super-csv/super-csv-${project.version}.jar | Super CSV ${project.version} (compiled classes only) +*----------------------------------------------------------------+---------------------------------------------------------------------+ + super-csv/super-csv-${project.version}-sources.jar | The Super CSV source code +*----------------------------------------------------------------+---------------------------------------------------------------------+ + super-csv/super-csv-${project.version}-javadoc.jar | The Super CSV Javadoc documentation +*----------------------------------------------------------------+---------------------------------------------------------------------+ + super-csv-dozer/super-csv-dozer-${project.version}.jar | Super CSV Dozer extension ${project.version} (compiled classes only) +*----------------------------------------------------------------+---------------------------------------------------------------------+ + super-csv-dozer/super-csv-dozer-${project.version}-sources.jar | The Super CSV Dozer extension source code +*----------------------------------------------------------------+---------------------------------------------------------------------+ + super-csv-dozer/super-csv-dozer-${project.version}-javadoc.jar | The Super CSV Dozer extension Javadoc documentation +*----------------------------------------------------------------+---------------------------------------------------------------------+ + super-csv-dozer/lib | The Super CSV Dozer extension's dependencies (including Dozer) *----------------------------------------------------------------+---------------------------------------------------------------------+ \ No newline at end of file diff --git a/src/site/apt/dozer.apt b/src/site/apt/dozer.apt index 93674e2d..6b91440b 100644 --- a/src/site/apt/dozer.apt +++ b/src/site/apt/dozer.apt @@ -1,165 +1,165 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ------------------------- - Super CSV Dozer extension - ------------------------- - -Super CSV Dozer extension - - The {{{./super-csv-dozer/index.html}Super CSV Dozer extension}} integrates Super CSV with {{{http://dozer.sourceforge.net}Dozer}}, - a powerful Javabean mapping library. - Typically, Dozer requires lots of XML configuration but the addition of - {{{http://dozer.sourceforge.net/documentation/apimappings.html}API mapping}} allows Super CSV to set up Dozer mappings dynamically. - - The use of Dozer allows {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanReader.html}CsvDozerBeanReader}} and - {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanWriter.html}CsvDozerBeanWriter}} to map simple fields - (the same as {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}} and - {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}}), - but to also perform deep mapping and index-based mapping as well! - - Check out the {{{./examples_dozer.html}examples}}, or read on for more information. - -* Deep mapping - - {{{http://dozer.sourceforge.net/documentation/deepmapping.html}Deep mapping}} allows you to make use of the relationships - between your classes. - - For example, if your class had an <<
>> field, you could utilize deep mapping as follows - (assuming there are valid getters/setters defined for <<
>>, <<>> and <<>> in the 3 involved classes): - ------------------------- -address.city.name ------------------------- - -* Indexed-based mapping - - {{{http://dozer.sourceforge.net/documentation/indexmapping.html}Index-based mapping}} allows you to access elements of arrays and - Collections by their index. - - For example, if your class had a collection of Addresses, you could utilize index-based mapping - to access the first one as follows: - ------------------------- -addresses[0] ------------------------- - - You can even combine index-based mapping with deep mapping: - ------------------------- -addresses[0].city.name ------------------------- - -* Logging - - Dozer uses {{{http://www.slf4j.org}SLF4J}} for logging. By default it will use a no-operation implementation (i.e. no logging), - but you can use any of the supported implementations (logback, log4j, slf4j-simple) by placing the appropriate binding jar on the classpath. - - See the {{{http://www.slf4j.org/manual.html}SLF4J manual}} for more details. - -* Reference Mapping XML Configuration - - Most of the time you'll want to let Super CSV take care of the dozer configuration by simply calling the <<>> method. - However, you might want to make use of the advanced features of Dozer (such as custom converters, bean factories, etc). - In this case, you can supply Super CSV with a pre-configured DozerBeanMapper. - - The following XML is provided as a reference - it's the XML configuration used in the project's unit tests. - The <<>> class is used internally as the input/output of any Dozer mapping (each indexed column represents a column of CSV). - At a minimum, you should replace the <<>> with the class you're mapping, - and update the field mappings as appropriate (but try not to change the XML attributes, as they're important!). - -+---------------------------------------------------------------------------------------------------+ - - - - - org.supercsv.io.dozer.CsvDozerBeanData - org.supercsv.mock.dozer.SurveyResponse - - columns[0] - age - - - columns[1] - consentGiven - - - columns[2] - answers[0].questionNo - - - columns[3] - answers[0].answer - - - columns[4] - answers[1].questionNo - - - columns[5] - answers[1].answer - - - columns[6] - answers[2].questionNo - - - columns[7] - answers[2].answer - - - - - - org.supercsv.mock.dozer.SurveyResponse - org.supercsv.io.dozer.CsvDozerBeanData - - age - columns[0] - - - consentGiven - columns[1] - - - answers[0].questionNo - columns[2] - - - answers[0].answer - columns[3] - - - answers[1].questionNo - columns[4] - - - answers[1].answer - columns[5] - - - answers[2].questionNo - columns[6] - - - answers[2].answer - columns[7] - - - - +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ------------------------- + Super CSV Dozer extension + ------------------------- + +Super CSV Dozer extension + + The {{{./super-csv-dozer/index.html}Super CSV Dozer extension}} integrates Super CSV with {{{http://dozer.sourceforge.net}Dozer}}, + a powerful Javabean mapping library. + Typically, Dozer requires lots of XML configuration but the addition of + {{{http://dozer.sourceforge.net/documentation/apimappings.html}API mapping}} allows Super CSV to set up Dozer mappings dynamically. + + The use of Dozer allows {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanReader.html}CsvDozerBeanReader}} and + {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanWriter.html}CsvDozerBeanWriter}} to map simple fields + (the same as {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}} and + {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}}), + but to also perform deep mapping and index-based mapping as well! + + Check out the {{{./examples_dozer.html}examples}}, or read on for more information. + +* Deep mapping + + {{{http://dozer.sourceforge.net/documentation/deepmapping.html}Deep mapping}} allows you to make use of the relationships + between your classes. + + For example, if your class had an <<
>> field, you could utilize deep mapping as follows + (assuming there are valid getters/setters defined for <<
>>, <<>> and <<>> in the 3 involved classes): + +------------------------ +address.city.name +------------------------ + +* Indexed-based mapping + + {{{http://dozer.sourceforge.net/documentation/indexmapping.html}Index-based mapping}} allows you to access elements of arrays and + Collections by their index. + + For example, if your class had a collection of Addresses, you could utilize index-based mapping + to access the first one as follows: + +------------------------ +addresses[0] +------------------------ + + You can even combine index-based mapping with deep mapping: + +------------------------ +addresses[0].city.name +------------------------ + +* Logging + + Dozer uses {{{http://www.slf4j.org}SLF4J}} for logging. By default it will use a no-operation implementation (i.e. no logging), + but you can use any of the supported implementations (logback, log4j, slf4j-simple) by placing the appropriate binding jar on the classpath. + + See the {{{http://www.slf4j.org/manual.html}SLF4J manual}} for more details. + +* Reference Mapping XML Configuration + + Most of the time you'll want to let Super CSV take care of the dozer configuration by simply calling the <<>> method. + However, you might want to make use of the advanced features of Dozer (such as custom converters, bean factories, etc). + In this case, you can supply Super CSV with a pre-configured DozerBeanMapper. + + The following XML is provided as a reference - it's the XML configuration used in the project's unit tests. + The <<>> class is used internally as the input/output of any Dozer mapping (each indexed column represents a column of CSV). + At a minimum, you should replace the <<>> with the class you're mapping, + and update the field mappings as appropriate (but try not to change the XML attributes, as they're important!). + ++---------------------------------------------------------------------------------------------------+ + + + + + org.supercsv.io.dozer.CsvDozerBeanData + org.supercsv.mock.dozer.SurveyResponse + + columns[0] + age + + + columns[1] + consentGiven + + + columns[2] + answers[0].questionNo + + + columns[3] + answers[0].answer + + + columns[4] + answers[1].questionNo + + + columns[5] + answers[1].answer + + + columns[6] + answers[2].questionNo + + + columns[7] + answers[2].answer + + + + + + org.supercsv.mock.dozer.SurveyResponse + org.supercsv.io.dozer.CsvDozerBeanData + + age + columns[0] + + + consentGiven + columns[1] + + + answers[0].questionNo + columns[2] + + + answers[0].answer + columns[3] + + + answers[1].questionNo + columns[4] + + + answers[1].answer + columns[5] + + + answers[2].questionNo + columns[6] + + + answers[2].answer + columns[7] + + + + +---------------------------------------------------------------------------------------------------+ \ No newline at end of file diff --git a/src/site/apt/examples_dozer.apt b/src/site/apt/examples_dozer.apt index a7c0f159..593664e4 100644 --- a/src/site/apt/examples_dozer.apt +++ b/src/site/apt/examples_dozer.apt @@ -1,189 +1,189 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ---------------------------------------- - Reading and writing CSV files with Dozer - ---------------------------------------- - -Reading and writing CSV files with Dozer - - This page contains some examples of reading and writing CSV files using Super CSV and Dozer. - For a closer look, refer to the {{{./xref-test/org/supercsv/example/dozer/Reading.html}reading}} and - {{{./xref-test/org/supercsv/example/dozer/Writing.html}writing}} example source. - - If you haven't already, check out the {{{./dozer.html}background}} on the Super CSV Dozer extension. - -* Example CSV file - - Here is an example CSV file that represents responses to a survey (we'll be using this in the following reading examples). - It has a header and 3 rows of data, all with 8 columns. - ---------------------------------------------------------------------------------------------------------------- -age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3 -18,Y,1,Twelve,2,Albert Einstein,3,Big Bang Theory -,Y,1,Thirteen,2,Nikola Tesla,3,Stargate -42,N,1,,2,Carl Sagan,3,Star Wars ---------------------------------------------------------------------------------------------------------------- - -* Reading with CsvDozerBeanReader - - {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanReader.html}CsvDozerBeanReader}} is the most powerful CSV reader. - The example reads each row from the example CSV file into a {{{./xref-test/org/supercsv/mock/dozer/SurveyResponse.html}SurveyResponse}} bean - , which has a Collection of {{{./xref-test/org/supercsv/mock/dozer/Answer.html}Answer}}s. - - To do this requires the following field mapping (notice that the first two mappings are the same as you'd have for - CsvBeanReader, but the rest use indexed and deep mapping). - -+-------------------------------------------------------------------------------------------------------------+ -private static final String[] FIELD_MAPPING = new String[] { - "age", // simple field mapping (like CsvBeanReader) - "consentGiven", // as above - "answers[0].questionNo", // indexed (first element) + deep mapping - "answers[0].answer", - "answers[1].questionNo", // indexed (second element) + deep mapping - "answers[1].answer", - "answers[2].questionNo", - "answers[2].answer" }; -+-------------------------------------------------------------------------------------------------------------+ - - If you are familiar with the standard CsvBeanReader, you'll notice that using CsvDozerBeanReader is very similar. - The main difference is that CsvDozerBeanReader requires you to configure it (with the <<>> method) - prior to reading. You can still use the result of <<>> as your field mapping, but you'll have to supply - your own if you want to use deep mapping or index-based mapping. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of reading using CsvDozerBeanReader. - */ -private static void readWithCsvDozerBeanReader() throws Exception { - - final CellProcessor[] processors = new CellProcessor[] { - new Optional(new ParseInt()), // age - new ParseBool(), // consent - new ParseInt(), // questionNo 1 - new Optional(), // answer 1 - new ParseInt(), // questionNo 2 - new Optional(), // answer 2 - new ParseInt(), // questionNo 3 - new Optional() // answer 3 - }; - - ICsvDozerBeanReader beanReader = null; - try { - beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - beanReader.getHeader(true); // ignore the header - beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); - - SurveyResponse surveyResponse; - while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(), - beanReader.getRowNumber(), surveyResponse)); - } - - } - finally { - if( beanReader != null ) { - beanReader.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -lineNo=2, rowNo=2, surveyResponse=SurveyResponse [age=18, consentGiven=true, answers=[Answer [questionNo=1, answer=Twelve], Answer [questionNo=2, answer=Albert Einstein], Answer [questionNo=3, answer=Big Bang Theory]]] -lineNo=3, rowNo=3, surveyResponse=SurveyResponse [age=null, consentGiven=true, answers=[Answer [questionNo=1, answer=Thirteen], Answer [questionNo=2, answer=Nikola Tesla], Answer [questionNo=3, answer=Stargate]]] -lineNo=4, rowNo=4, surveyResponse=SurveyResponse [age=42, consentGiven=false, answers=[Answer [questionNo=1, answer=null], Answer [questionNo=2, answer=Carl Sagan], Answer [questionNo=3, answer=Star Wars]]] ---------------------------------------------------------------------------------------------------------------- - -* Partial reading with CsvDozerBeanReader - - Partial reading with CsvDozerBeanReader is virtually identical to CsvBeanReader. - See the partial reading example in the {{{./xref-test/org/supercsv/example/dozer/Reading.html}reading example source}}. - -* Writing with CsvDozerBeanWriter - - {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanWriter.html}CsvDozerBeanWriter}} is the most powerful CSV writer. - The example writes each CSV row from a {{{./xref-test/org/supercsv/mock/dozer/SurveyResponse.html}SurveyResponse}} bean - , which has a Collection of {{{./xref-test/org/supercsv/mock/dozer/Answer.html}Answer}}s. - - It uses exactly the same field mapping as the reading example above, and once again you'll notice that CsvDozerBeanWriter - requires you to configure it (with the <<>> method) prior to writing. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of writing using CsvDozerBeanWriter. - */ -private static void writeWithDozerCsvBeanWriter() throws Exception { - - final CellProcessor[] processors = new CellProcessor[] { - new Optional(), // age - new FmtBool("Y", "N"), // consent - new NotNull(), // questionNo 1 - new Optional(), // answer 1 - new NotNull(), // questionNo 2 - new Optional(), // answer 2 - new NotNull(), // questionNo 3 - new Optional() }; // answer 4 - - // create the survey responses to write - SurveyResponse response1 = new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, - "Albert Einstein"), new Answer(3, "Big Bang Theory"))); - SurveyResponse response2 = new SurveyResponse(null, true, Arrays.asList(new Answer(1, "Thirteen"), new Answer(2, - "Nikola Tesla"), new Answer(3, "Stargate"))); - SurveyResponse response3 = new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2, - "Carl Sagan"), new Answer(3, "Star Wars"))); - final List surveyResponses = Arrays.asList(response1, response2, response3); - - ICsvDozerBeanWriter beanWriter = null; - try { - beanWriter = new CsvDozerBeanWriter(new FileWriter("target/writeWithCsvDozerBeanWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // configure the mapping from the fields to the CSV columns - beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); - - // write the header - beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", - "questionNo3", "answer3"); - - // write the beans - for( final SurveyResponse surveyResponse : surveyResponses ) { - beanWriter.write(surveyResponse, processors); - } - - } - finally { - if( beanWriter != null ) { - beanWriter.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -lineNo=2, rowNo=2, surveyResponse=SurveyResponse [age=18, consentGiven=true, answers=[Answer [questionNo=1, answer=Twelve], Answer [questionNo=2, answer=Albert Einstein], Answer [questionNo=3, answer=Big Bang Theory]]] -lineNo=3, rowNo=3, surveyResponse=SurveyResponse [age=null, consentGiven=true, answers=[Answer [questionNo=1, answer=Thirteen], Answer [questionNo=2, answer=Nikola Tesla], Answer [questionNo=3, answer=Stargate]]] -lineNo=4, rowNo=4, surveyResponse=SurveyResponse [age=42, consentGiven=false, answers=[Answer [questionNo=1, answer=null], Answer [questionNo=2, answer=Carl Sagan], Answer [questionNo=3, answer=Star Wars]]] ---------------------------------------------------------------------------------------------------------------- - -* Partial writing with CsvDozerBeanWriter - - Partial writing with CsvDozerBeanWriter is virtually identical to CsvBeanWriter. - See the partial writing example in the {{{./xref-test/org/supercsv/example/dozer/Writing.html}writing example source}}. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ---------------------------------------- + Reading and writing CSV files with Dozer + ---------------------------------------- + +Reading and writing CSV files with Dozer + + This page contains some examples of reading and writing CSV files using Super CSV and Dozer. + For a closer look, refer to the {{{./xref-test/org/supercsv/example/dozer/Reading.html}reading}} and + {{{./xref-test/org/supercsv/example/dozer/Writing.html}writing}} example source. + + If you haven't already, check out the {{{./dozer.html}background}} on the Super CSV Dozer extension. + +* Example CSV file + + Here is an example CSV file that represents responses to a survey (we'll be using this in the following reading examples). + It has a header and 3 rows of data, all with 8 columns. + +--------------------------------------------------------------------------------------------------------------- +age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3 +18,Y,1,Twelve,2,Albert Einstein,3,Big Bang Theory +,Y,1,Thirteen,2,Nikola Tesla,3,Stargate +42,N,1,,2,Carl Sagan,3,Star Wars +--------------------------------------------------------------------------------------------------------------- + +* Reading with CsvDozerBeanReader + + {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanReader.html}CsvDozerBeanReader}} is the most powerful CSV reader. + The example reads each row from the example CSV file into a {{{./xref-test/org/supercsv/mock/dozer/SurveyResponse.html}SurveyResponse}} bean + , which has a Collection of {{{./xref-test/org/supercsv/mock/dozer/Answer.html}Answer}}s. + + To do this requires the following field mapping (notice that the first two mappings are the same as you'd have for + CsvBeanReader, but the rest use indexed and deep mapping). + ++-------------------------------------------------------------------------------------------------------------+ +private static final String[] FIELD_MAPPING = new String[] { + "age", // simple field mapping (like CsvBeanReader) + "consentGiven", // as above + "answers[0].questionNo", // indexed (first element) + deep mapping + "answers[0].answer", + "answers[1].questionNo", // indexed (second element) + deep mapping + "answers[1].answer", + "answers[2].questionNo", + "answers[2].answer" }; ++-------------------------------------------------------------------------------------------------------------+ + + If you are familiar with the standard CsvBeanReader, you'll notice that using CsvDozerBeanReader is very similar. + The main difference is that CsvDozerBeanReader requires you to configure it (with the <<>> method) + prior to reading. You can still use the result of <<>> as your field mapping, but you'll have to supply + your own if you want to use deep mapping or index-based mapping. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of reading using CsvDozerBeanReader. + */ +private static void readWithCsvDozerBeanReader() throws Exception { + + final CellProcessor[] processors = new CellProcessor[] { + new Optional(new ParseInt()), // age + new ParseBool(), // consent + new ParseInt(), // questionNo 1 + new Optional(), // answer 1 + new ParseInt(), // questionNo 2 + new Optional(), // answer 2 + new ParseInt(), // questionNo 3 + new Optional() // answer 3 + }; + + ICsvDozerBeanReader beanReader = null; + try { + beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + beanReader.getHeader(true); // ignore the header + beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); + + SurveyResponse surveyResponse; + while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(), + beanReader.getRowNumber(), surveyResponse)); + } + + } + finally { + if( beanReader != null ) { + beanReader.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +lineNo=2, rowNo=2, surveyResponse=SurveyResponse [age=18, consentGiven=true, answers=[Answer [questionNo=1, answer=Twelve], Answer [questionNo=2, answer=Albert Einstein], Answer [questionNo=3, answer=Big Bang Theory]]] +lineNo=3, rowNo=3, surveyResponse=SurveyResponse [age=null, consentGiven=true, answers=[Answer [questionNo=1, answer=Thirteen], Answer [questionNo=2, answer=Nikola Tesla], Answer [questionNo=3, answer=Stargate]]] +lineNo=4, rowNo=4, surveyResponse=SurveyResponse [age=42, consentGiven=false, answers=[Answer [questionNo=1, answer=null], Answer [questionNo=2, answer=Carl Sagan], Answer [questionNo=3, answer=Star Wars]]] +--------------------------------------------------------------------------------------------------------------- + +* Partial reading with CsvDozerBeanReader + + Partial reading with CsvDozerBeanReader is virtually identical to CsvBeanReader. + See the partial reading example in the {{{./xref-test/org/supercsv/example/dozer/Reading.html}reading example source}}. + +* Writing with CsvDozerBeanWriter + + {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanWriter.html}CsvDozerBeanWriter}} is the most powerful CSV writer. + The example writes each CSV row from a {{{./xref-test/org/supercsv/mock/dozer/SurveyResponse.html}SurveyResponse}} bean + , which has a Collection of {{{./xref-test/org/supercsv/mock/dozer/Answer.html}Answer}}s. + + It uses exactly the same field mapping as the reading example above, and once again you'll notice that CsvDozerBeanWriter + requires you to configure it (with the <<>> method) prior to writing. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of writing using CsvDozerBeanWriter. + */ +private static void writeWithDozerCsvBeanWriter() throws Exception { + + final CellProcessor[] processors = new CellProcessor[] { + new Optional(), // age + new FmtBool("Y", "N"), // consent + new NotNull(), // questionNo 1 + new Optional(), // answer 1 + new NotNull(), // questionNo 2 + new Optional(), // answer 2 + new NotNull(), // questionNo 3 + new Optional() }; // answer 4 + + // create the survey responses to write + SurveyResponse response1 = new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, + "Albert Einstein"), new Answer(3, "Big Bang Theory"))); + SurveyResponse response2 = new SurveyResponse(null, true, Arrays.asList(new Answer(1, "Thirteen"), new Answer(2, + "Nikola Tesla"), new Answer(3, "Stargate"))); + SurveyResponse response3 = new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2, + "Carl Sagan"), new Answer(3, "Star Wars"))); + final List surveyResponses = Arrays.asList(response1, response2, response3); + + ICsvDozerBeanWriter beanWriter = null; + try { + beanWriter = new CsvDozerBeanWriter(new FileWriter("target/writeWithCsvDozerBeanWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // configure the mapping from the fields to the CSV columns + beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); + + // write the header + beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", + "questionNo3", "answer3"); + + // write the beans + for( final SurveyResponse surveyResponse : surveyResponses ) { + beanWriter.write(surveyResponse, processors); + } + + } + finally { + if( beanWriter != null ) { + beanWriter.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +lineNo=2, rowNo=2, surveyResponse=SurveyResponse [age=18, consentGiven=true, answers=[Answer [questionNo=1, answer=Twelve], Answer [questionNo=2, answer=Albert Einstein], Answer [questionNo=3, answer=Big Bang Theory]]] +lineNo=3, rowNo=3, surveyResponse=SurveyResponse [age=null, consentGiven=true, answers=[Answer [questionNo=1, answer=Thirteen], Answer [questionNo=2, answer=Nikola Tesla], Answer [questionNo=3, answer=Stargate]]] +lineNo=4, rowNo=4, surveyResponse=SurveyResponse [age=42, consentGiven=false, answers=[Answer [questionNo=1, answer=null], Answer [questionNo=2, answer=Carl Sagan], Answer [questionNo=3, answer=Star Wars]]] +--------------------------------------------------------------------------------------------------------------- + +* Partial writing with CsvDozerBeanWriter + + Partial writing with CsvDozerBeanWriter is virtually identical to CsvBeanWriter. + See the partial writing example in the {{{./xref-test/org/supercsv/example/dozer/Writing.html}writing example source}}. diff --git a/src/site/apt/examples_new_cell_processor.apt b/src/site/apt/examples_new_cell_processor.apt index 766d4692..7e69a6bd 100644 --- a/src/site/apt/examples_new_cell_processor.apt +++ b/src/site/apt/examples_new_cell_processor.apt @@ -1,109 +1,109 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ------------------------------ - Writing custom cell processors - ------------------------------ - -Writing custom cell processors - - Super CSV provides a wide variety of useful cell processors, but you are free to write your own if need to. - If you think other people might benefit from your custom cell processor, send us a patch and we'll consider adding - it to the next version of Super CSV. - - So how do you write a custom cell processor? - - Let's say you're trying to read a CSV file that has a day column, and you've written your own enumeration - to represent that. - - -+------------------------------------------------------------------------------------------------------+ -package org.supercsv.example; - -/** - * An enumeration of days. - */ -public enum Day { - MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY -} -+------------------------------------------------------------------------------------------------------+ - - You could write the following processor to parse the column to your enum (ignoring the case of the input). - -+------------------------------------------------------------------------------------------------------+ -package org.supercsv.example; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * An example of a custom cell processor. - */ -public class ParseDay extends CellProcessorAdaptor { - - public ParseDay() { - super(); - } - - public ParseDay(CellProcessor next) { - // this constructor allows other processors to be chained after ParseDay - super(next); - } - - public Object execute(Object value, CsvContext context) { - - validateInputNotNull(value, context); // throws an Exception if the input is null - - for (Day day : Day.values()){ - if (day.name().equalsIgnoreCase(value.toString())){ - // passes the Day enum to the next processor in the chain - return next.execute(day, context); - } - } - - throw new SuperCsvCellProcessorException( - String.format("Could not parse '%s' as a day", value), context, this); - } -} -+------------------------------------------------------------------------------------------------------+ - - The important things to note above are: - - * the processor must extend {{{./apidocs/org/supercsv/cellprocessor/CellProcessorAdaptor.html}CellProcessorAdaptor}} - - this ensures it implements the <<>> interface and can be chained to other processors - - * it has a no-args constructor (for when this is the last or only processor in the chain) - - * it has constructor that allows another processor to be chained afterwards (it must call <<>>) - - * if the processor required further configuration, additional parameters could be added to the constructors - - * input is mandatory for this processor, so it calls its inherited <<>> method, - which throws an Exception for null input - - * the return statement for the <<>> method actually invokes the <<>> method of the next processor in the chain. - If there is no next processor, the value will simply be returned, otherwise the next processor is free to perform additional processing. - If your processor doesn't allow chaining at all, then you could simply return the value instead (i.e. <<>> in the above example). - - * if the processor fails to parse the input (it doesn't match any of the days), it throws an Exception with - a meaningful message, the current context (which will contain the line/row/column numbers), and a reference to the - processor. - - [] - - For more ideas, take a look at the existing cell processors in the {{{./xref/index.html}project source}}. - +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ------------------------------ + Writing custom cell processors + ------------------------------ + +Writing custom cell processors + + Super CSV provides a wide variety of useful cell processors, but you are free to write your own if need to. + If you think other people might benefit from your custom cell processor, send us a patch and we'll consider adding + it to the next version of Super CSV. + + So how do you write a custom cell processor? + + Let's say you're trying to read a CSV file that has a day column, and you've written your own enumeration + to represent that. + + ++------------------------------------------------------------------------------------------------------+ +package org.supercsv.example; + +/** + * An enumeration of days. + */ +public enum Day { + MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY +} ++------------------------------------------------------------------------------------------------------+ + + You could write the following processor to parse the column to your enum (ignoring the case of the input). + ++------------------------------------------------------------------------------------------------------+ +package org.supercsv.example; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * An example of a custom cell processor. + */ +public class ParseDay extends CellProcessorAdaptor { + + public ParseDay() { + super(); + } + + public ParseDay(CellProcessor next) { + // this constructor allows other processors to be chained after ParseDay + super(next); + } + + public Object execute(Object value, CsvContext context) { + + validateInputNotNull(value, context); // throws an Exception if the input is null + + for (Day day : Day.values()){ + if (day.name().equalsIgnoreCase(value.toString())){ + // passes the Day enum to the next processor in the chain + return next.execute(day, context); + } + } + + throw new SuperCsvCellProcessorException( + String.format("Could not parse '%s' as a day", value), context, this); + } +} ++------------------------------------------------------------------------------------------------------+ + + The important things to note above are: + + * the processor must extend {{{./apidocs/org/supercsv/cellprocessor/CellProcessorAdaptor.html}CellProcessorAdaptor}} - + this ensures it implements the <<>> interface and can be chained to other processors + + * it has a no-args constructor (for when this is the last or only processor in the chain) + + * it has constructor that allows another processor to be chained afterwards (it must call <<>>) + + * if the processor required further configuration, additional parameters could be added to the constructors + + * input is mandatory for this processor, so it calls its inherited <<>> method, + which throws an Exception for null input + + * the return statement for the <<>> method actually invokes the <<>> method of the next processor in the chain. + If there is no next processor, the value will simply be returned, otherwise the next processor is free to perform additional processing. + If your processor doesn't allow chaining at all, then you could simply return the value instead (i.e. <<>> in the above example). + + * if the processor fails to parse the input (it doesn't match any of the days), it throws an Exception with + a meaningful message, the current context (which will contain the line/row/column numbers), and a reference to the + processor. + + [] + + For more ideas, take a look at the existing cell processors in the {{{./xref/index.html}project source}}. + diff --git a/src/site/apt/examples_partial_reading.apt b/src/site/apt/examples_partial_reading.apt index 6bf58958..6b987f3f 100644 --- a/src/site/apt/examples_partial_reading.apt +++ b/src/site/apt/examples_partial_reading.apt @@ -1,130 +1,130 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - --------------- - Partial reading - --------------- - -Partial reading - - Partial reading allows you to ignore columns when reading CSV files by simply setting the appropriate header columns - to <<>>. - - The examples on this page use the same example CSV file as the {{{./examples_reading.html}reading examples}}, and - the full source can be found {{{./xref-test/org/supercsv/example/Reading.html}here}}. - -* Partial reading with CsvBeanReader - - As you can see from the output of this example, the fields associated with the ignored columns kept their default values - - only the <<>>, <<>>, and <<>> are populated. - - Also note that the cell processors associated with the ignored columns were also set to <<>> to avoid any unnecessary - processing (cell processors are always executed). - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of partial reading using CsvBeanReader. - */ -private static void partialReadWithCsvBeanReader() throws Exception { - - ICsvBeanReader beanReader = null; - try { - beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - beanReader.getHeader(true); // skip past the header (we're defining our own) - - // only map the first 3 columns - setting header elements to null means those columns are ignored - final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, - null, null }; - - // no processing required for ignored columns - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), null, null, null, null, null, null, null }; - - CustomerBean customer; - while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), - beanReader.getRowNumber(), customer)); - } - - } - finally { - if( beanReader != null ) { - beanReader.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -lineNo=4, rowNo=2, customer=CustomerBean [customerNo=1, firstName=John, lastName=Dunbar, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] -lineNo=7, rowNo=3, customer=CustomerBean [customerNo=2, firstName=Bob, lastName=Down, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] -lineNo=10, rowNo=4, customer=CustomerBean [customerNo=3, firstName=Alice, lastName=Wunderland, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] -lineNo=13, rowNo=5, customer=CustomerBean [customerNo=4, firstName=Bill, lastName=Jobs, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] ---------------------------------------------------------------------------------------------------------------- - -* Partial reading with CsvMapReader - - As you can see from the output of this example, the output Map only has entries for <<>>, <<>>, and <<>> - the other fields were ignored. - - Unlike the CsvBeanReader example above, this example defines processors for all columns. This means that constraint validation is still applied to the ignored columns, - but they don't appear in the output Map. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of partial reading using CsvMapReader. - */ -private static void partialReadWithCsvMapReader() throws Exception { - - ICsvMapReader mapReader = null; - try { - mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - mapReader.getHeader(true); // skip past the header (we're defining our own) - - // only map the first 3 columns - setting header elements to null means those columns are ignored - final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, - null, null }; - - // apply some constraints to ignored columns (just because we can) - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new NotNull(), new NotNull(), new Optional(), new Optional(), new NotNull(), - new NotNull(), new LMinMax(0L, LMinMax.MAX_LONG) }; - - Map customerMap; - while( (customerMap = mapReader.read(header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), - mapReader.getRowNumber(), customerMap)); - } - - } - finally { - if( mapReader != null ) { - mapReader.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -lineNo=4, rowNo=2, customerMap={lastName=Dunbar, customerNo=1, firstName=John} -lineNo=7, rowNo=3, customerMap={lastName=Down, customerNo=2, firstName=Bob} -lineNo=10, rowNo=4, customerMap={lastName=Wunderland, customerNo=3, firstName=Alice} -lineNo=13, rowNo=5, customerMap={lastName=Jobs, customerNo=4, firstName=Bill} ---------------------------------------------------------------------------------------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + --------------- + Partial reading + --------------- + +Partial reading + + Partial reading allows you to ignore columns when reading CSV files by simply setting the appropriate header columns + to <<>>. + + The examples on this page use the same example CSV file as the {{{./examples_reading.html}reading examples}}, and + the full source can be found {{{./xref-test/org/supercsv/example/Reading.html}here}}. + +* Partial reading with CsvBeanReader + + As you can see from the output of this example, the fields associated with the ignored columns kept their default values - + only the <<>>, <<>>, and <<>> are populated. + + Also note that the cell processors associated with the ignored columns were also set to <<>> to avoid any unnecessary + processing (cell processors are always executed). + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of partial reading using CsvBeanReader. + */ +private static void partialReadWithCsvBeanReader() throws Exception { + + ICsvBeanReader beanReader = null; + try { + beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + beanReader.getHeader(true); // skip past the header (we're defining our own) + + // only map the first 3 columns - setting header elements to null means those columns are ignored + final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, + null, null }; + + // no processing required for ignored columns + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), null, null, null, null, null, null, null }; + + CustomerBean customer; + while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), + beanReader.getRowNumber(), customer)); + } + + } + finally { + if( beanReader != null ) { + beanReader.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +lineNo=4, rowNo=2, customer=CustomerBean [customerNo=1, firstName=John, lastName=Dunbar, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] +lineNo=7, rowNo=3, customer=CustomerBean [customerNo=2, firstName=Bob, lastName=Down, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] +lineNo=10, rowNo=4, customer=CustomerBean [customerNo=3, firstName=Alice, lastName=Wunderland, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] +lineNo=13, rowNo=5, customer=CustomerBean [customerNo=4, firstName=Bill, lastName=Jobs, birthDate=null, mailingAddress=null, married=null, numberOfKids=null, favouriteQuote=null, email=null, loyaltyPoints=0] +--------------------------------------------------------------------------------------------------------------- + +* Partial reading with CsvMapReader + + As you can see from the output of this example, the output Map only has entries for <<>>, <<>>, and <<>> - the other fields were ignored. + + Unlike the CsvBeanReader example above, this example defines processors for all columns. This means that constraint validation is still applied to the ignored columns, + but they don't appear in the output Map. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of partial reading using CsvMapReader. + */ +private static void partialReadWithCsvMapReader() throws Exception { + + ICsvMapReader mapReader = null; + try { + mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + mapReader.getHeader(true); // skip past the header (we're defining our own) + + // only map the first 3 columns - setting header elements to null means those columns are ignored + final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, + null, null }; + + // apply some constraints to ignored columns (just because we can) + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new NotNull(), new NotNull(), new Optional(), new Optional(), new NotNull(), + new NotNull(), new LMinMax(0L, LMinMax.MAX_LONG) }; + + Map customerMap; + while( (customerMap = mapReader.read(header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), + mapReader.getRowNumber(), customerMap)); + } + + } + finally { + if( mapReader != null ) { + mapReader.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +lineNo=4, rowNo=2, customerMap={lastName=Dunbar, customerNo=1, firstName=John} +lineNo=7, rowNo=3, customerMap={lastName=Down, customerNo=2, firstName=Bob} +lineNo=10, rowNo=4, customerMap={lastName=Wunderland, customerNo=3, firstName=Alice} +lineNo=13, rowNo=5, customerMap={lastName=Jobs, customerNo=4, firstName=Bill} +--------------------------------------------------------------------------------------------------------------- diff --git a/src/site/apt/examples_partial_writing.apt b/src/site/apt/examples_partial_writing.apt index 61b9df9d..8c8b7922 100644 --- a/src/site/apt/examples_partial_writing.apt +++ b/src/site/apt/examples_partial_writing.apt @@ -1,201 +1,201 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - --------------- - Partial writing - --------------- - -Partial writing - - Partial writing allows you to handle optional values in your data. - - The full source for these examples can be found {{{./xref-test/org/supercsv/example/Writing.html}here}}. - -* Partial writing with CsvBeanWriter - - As you can see in this example, we're only writing 5 of the available fields from the bean and 2 of those are optional. - - This example demonstrates the two options you have when writing optional fields: - - [[1]] specifying a default value if the value is <<>> by using <<>> - in this case <<<"no response">>> is written when <<>> is <<>>. - - [[2]] writing an empty column if the value is <<>> - as is done by specifying <<>> for <<>> - (<<>> would have the same effect as <<>>, but it's not as meaningful) - - [] - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of partial reading using CsvBeanWriter. - */ -private static void partialWriteWithCsvBeanWriter() throws Exception { - - // create the customer beans - final CustomerBean john = new CustomerBean("1", "John", "Dunbar", - new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), - "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, - "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); - final CustomerBean bob = new CustomerBean("2", "Bob", "Down", - new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), - "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, - "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); - final List customers = Arrays.asList(john, bob); - - ICsvBeanWriter beanWriter = null; - try { - beanWriter = new CsvBeanWriter(new FileWriter("target/partialWriteWithCsvBeanWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // only map 5 of the 10 fields - final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; - - // assign a default value for married (if null), and write numberOfKids as an empty column if null - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; - - // write the header - beanWriter.writeHeader(header); - - // write the customer beans - for( final CustomerBean customer : customers ) { - beanWriter.write(customer, header, processors); - } - - } - finally { - if( beanWriter != null ) { - beanWriter.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,married,numberOfKids -1,John,Dunbar,no response, -2,Bob,Down,yes,0 ---------------------------------------------------------------------------------------------------------------- - -* Partial writing with CsvListWriter - - This example is identical to the one above, but uses CsvListWriter. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of partial reading using CsvListWriter. - */ -private static void partialWriteWithCsvListWriter() throws Exception { - - final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; - - // create the customer Lists (CsvListWriter also accepts arrays!) - final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar",null, null}); - final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", true, 0 }); - - ICsvListWriter listWriter = null; - try { - listWriter = new CsvListWriter(new FileWriter("target/partialWriteWithCsvListWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // assign a default value for married (if null), and write numberOfKids as an empty column if null - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; - - // write the header - listWriter.writeHeader(header); - - // write the customer Lists - listWriter.write(john, processors); - listWriter.write(bob, processors); - - } - finally { - if( listWriter != null ) { - listWriter.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,married,numberOfKids -1,John,Dunbar,no response, -2,Bob,Down,yes,0 ---------------------------------------------------------------------------------------------------------------- - -* Partial writing with CsvMapWriter - - This example is identical to the others above, but uses CsvMapWriter. - It also demonstrates that a <<>> cell processor has the same effect as using <<>>. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of partial reading using CsvMapWriter. - */ -private static void partialWriteWithCsvMapWriter() throws Exception { - - final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; - - // create the customer Maps (using the header elements for the column keys) - final Map john = new HashMap(); - john.put(header[0], "1"); - john.put(header[1], "John"); - john.put(header[2], "Dunbar"); - john.put(header[3], null); - john.put(header[4], null); - - final Map bob = new HashMap(); - bob.put(header[0], "2"); - bob.put(header[1], "Bob"); - bob.put(header[2], "Down"); - bob.put(header[3], true); - bob.put(header[4], 0); - - ICsvMapWriter mapWriter = null; - try { - mapWriter = new CsvMapWriter(new FileWriter("target/partialWriteWithCsvMapWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // assign a default value for married (if null), and write numberOfKids as an empty column if null - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), null }; - - // write the header - mapWriter.writeHeader(header); - - // write the customer Maps - mapWriter.write(john, header, processors); - mapWriter.write(bob, header, processors); - - } - finally { - if( mapWriter != null ) { - mapWriter.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,married,numberOfKids -1,John,Dunbar,no response, -2,Bob,Down,yes,0 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + --------------- + Partial writing + --------------- + +Partial writing + + Partial writing allows you to handle optional values in your data. + + The full source for these examples can be found {{{./xref-test/org/supercsv/example/Writing.html}here}}. + +* Partial writing with CsvBeanWriter + + As you can see in this example, we're only writing 5 of the available fields from the bean and 2 of those are optional. + + This example demonstrates the two options you have when writing optional fields: + + [[1]] specifying a default value if the value is <<>> by using <<>> - in this case <<<"no response">>> is written when <<>> is <<>>. + + [[2]] writing an empty column if the value is <<>> - as is done by specifying <<>> for <<>> + (<<>> would have the same effect as <<>>, but it's not as meaningful) + + [] + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of partial reading using CsvBeanWriter. + */ +private static void partialWriteWithCsvBeanWriter() throws Exception { + + // create the customer beans + final CustomerBean john = new CustomerBean("1", "John", "Dunbar", + new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), + "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, + "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); + final CustomerBean bob = new CustomerBean("2", "Bob", "Down", + new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), + "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, + "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); + final List customers = Arrays.asList(john, bob); + + ICsvBeanWriter beanWriter = null; + try { + beanWriter = new CsvBeanWriter(new FileWriter("target/partialWriteWithCsvBeanWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // only map 5 of the 10 fields + final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; + + // assign a default value for married (if null), and write numberOfKids as an empty column if null + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; + + // write the header + beanWriter.writeHeader(header); + + // write the customer beans + for( final CustomerBean customer : customers ) { + beanWriter.write(customer, header, processors); + } + + } + finally { + if( beanWriter != null ) { + beanWriter.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,married,numberOfKids +1,John,Dunbar,no response, +2,Bob,Down,yes,0 +--------------------------------------------------------------------------------------------------------------- + +* Partial writing with CsvListWriter + + This example is identical to the one above, but uses CsvListWriter. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of partial reading using CsvListWriter. + */ +private static void partialWriteWithCsvListWriter() throws Exception { + + final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; + + // create the customer Lists (CsvListWriter also accepts arrays!) + final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar",null, null}); + final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", true, 0 }); + + ICsvListWriter listWriter = null; + try { + listWriter = new CsvListWriter(new FileWriter("target/partialWriteWithCsvListWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // assign a default value for married (if null), and write numberOfKids as an empty column if null + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; + + // write the header + listWriter.writeHeader(header); + + // write the customer Lists + listWriter.write(john, processors); + listWriter.write(bob, processors); + + } + finally { + if( listWriter != null ) { + listWriter.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,married,numberOfKids +1,John,Dunbar,no response, +2,Bob,Down,yes,0 +--------------------------------------------------------------------------------------------------------------- + +* Partial writing with CsvMapWriter + + This example is identical to the others above, but uses CsvMapWriter. + It also demonstrates that a <<>> cell processor has the same effect as using <<>>. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of partial reading using CsvMapWriter. + */ +private static void partialWriteWithCsvMapWriter() throws Exception { + + final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; + + // create the customer Maps (using the header elements for the column keys) + final Map john = new HashMap(); + john.put(header[0], "1"); + john.put(header[1], "John"); + john.put(header[2], "Dunbar"); + john.put(header[3], null); + john.put(header[4], null); + + final Map bob = new HashMap(); + bob.put(header[0], "2"); + bob.put(header[1], "Bob"); + bob.put(header[2], "Down"); + bob.put(header[3], true); + bob.put(header[4], 0); + + ICsvMapWriter mapWriter = null; + try { + mapWriter = new CsvMapWriter(new FileWriter("target/partialWriteWithCsvMapWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // assign a default value for married (if null), and write numberOfKids as an empty column if null + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), null }; + + // write the header + mapWriter.writeHeader(header); + + // write the customer Maps + mapWriter.write(john, header, processors); + mapWriter.write(bob, header, processors); + + } + finally { + if( mapWriter != null ) { + mapWriter.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,married,numberOfKids +1,John,Dunbar,no response, +2,Bob,Down,yes,0 --------------------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/src/site/apt/examples_reading.apt b/src/site/apt/examples_reading.apt index 96d11f49..db5939ec 100644 --- a/src/site/apt/examples_reading.apt +++ b/src/site/apt/examples_reading.apt @@ -1,262 +1,262 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ----------------- - Reading CSV files - ----------------- - -Reading CSV files - - This page contains some examples of reading CSV files using Super CSV. - You can view the full source of the examples {{{./xref-test/org/supercsv/example/Reading.html}here}}. - For examples of reading CSV files with Dozer (using CsvDozerBeanReader), click {{{./examples_dozer.html}here}}. - -* Example CSV file - - Here is an example CSV file. It has a header and 4 rows of data, all with 10 columns. - The <<>> column contains data that spans multiple lines and the <<>> column - contains data with escaped quotes. - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints -1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 -2,Bob,Down,25/02/1919,"1601 Willow Rd. -Menlo Park, CA 94025 -United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 -3,Alice,Wunderland,08/08/1985,"One Microsoft Way -Redmond, WA 98052-6399 -United States",Y,0,"""Play it, Sam. Play ""As Time Goes By."""" - Casablanca",throughthelookingglass@yahoo.com,2255887799 -4,Bill,Jobs,10/07/1973,"2701 San Tomas Expressway -Santa Clara, CA 95050 -United States",Y,3,"""You've got to ask yourself one question: ""Do I feel lucky?"" Well, do ya, punk?"" - Dirty Harry",billy34@hotmail.com,36 ---------------------------------------------------------------------------------------------------------------- - -* Example cell processor configuration - - All of the examples on this page use the following {{{./cell_processors.html}cell processor}} configuration. - - It demonstrates: - - * mandatory columns (<<>>) - - * optional columns (<<>>), with further processing - - * conversion to Date (<<>>), Boolean (<<>>) and Integer (<<>>) types - - * constraint validation against regular expressions (<<>>), numeric ranges (<<>>) and uniqueness (<<>>) - - [] - - Don't forget that you can {{{./examples_new_cell_processor.html}write your own cell processors}} if you want! - -+-------------------------------------------------------------------------------------------------------------+ -/** - * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. Empty - * columns are read as null (hence the NotNull() for mandatory columns). - * - * @return the cell processors - */ -private static CellProcessor[] getProcessors() { - - final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust! - StrRegEx.registerMessage(emailRegex, "must be a valid email address"); - - final CellProcessor[] processors = new CellProcessor[] { - new UniqueHashCode(), // customerNo (must be unique) - new NotNull(), // firstName - new NotNull(), // lastName - new ParseDate("dd/MM/yyyy"), // birthDate - new NotNull(), // mailingAddress - new Optional(new ParseBool()), // married - new Optional(new ParseInt()), // numberOfKids - new NotNull(), // favouriteQuote - new StrRegEx(emailRegex), // email - new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints - }; - - return processors; -} -+-------------------------------------------------------------------------------------------------------------+ - -* Reading with CsvBeanReader - - {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}} is the easiest reader to work with. - The example reads each row from the example CSV file into a {{{./xref-test/org/supercsv/mock/CustomerBean.html}CustomerBean}} (which extends - from {{{./xref-test/org/supercsv/mock/PersonBean.html}PersonBean}}). - - This relies on the fact that the column names in the header of the CSV file - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints ---------------------------------------------------------------------------------------------------------------- - - match up exactly with the bean's field names, and the bean has the appropriate setters defined for each field. - - If your header doesn't match (or there is no header), then you can simply define your own name mapping array. - - Note that the field types in the bean are compatible with the type returned by the cell processors - (e.g. <<>> is a <<>> in the bean, and uses the <<>> cell processor). - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of reading using CsvBeanReader. - */ -private static void readWithCsvBeanReader() throws Exception { - - ICsvBeanReader beanReader = null; - try { - beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - // the header elements are used to map the values to the bean (names must match) - final String[] header = beanReader.getHeader(true); - final CellProcessor[] processors = getProcessors(); - - CustomerBean customer; - while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), - beanReader.getRowNumber(), customer)); - } - - } - finally { - if( beanReader != null ) { - beanReader.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -lineNo=4, rowNo=2, customer=CustomerBean [customerNo=1, firstName=John, lastName=Dunbar, birthDate=Wed Jun 13 00:00:00 EST 1945, mailingAddress=1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States, married=null, numberOfKids=null, favouriteQuote="May the Force be with you." - Star Wars, email=jdunbar@gmail.com, loyaltyPoints=0] -lineNo=7, rowNo=3, customer=CustomerBean [customerNo=2, firstName=Bob, lastName=Down, birthDate=Tue Feb 25 00:00:00 EST 1919, mailingAddress=1601 Willow Rd. -Menlo Park, CA 94025 -United States, married=true, numberOfKids=0, favouriteQuote="Frankly, my dear, I don't give a damn." - Gone With The Wind, email=bobdown@hotmail.com, loyaltyPoints=123456] -lineNo=10, rowNo=4, customer=CustomerBean [customerNo=3, firstName=Alice, lastName=Wunderland, birthDate=Thu Aug 08 00:00:00 EST 1985, mailingAddress=One Microsoft Way -Redmond, WA 98052-6399 -United States, married=true, numberOfKids=0, favouriteQuote="Play it, Sam. Play "As Time Goes By."" - Casablanca, email=throughthelookingglass@yahoo.com, loyaltyPoints=2255887799] -lineNo=13, rowNo=5, customer=CustomerBean [customerNo=4, firstName=Bill, lastName=Jobs, birthDate=Tue Jul 10 00:00:00 EST 1973, mailingAddress=2701 San Tomas Expressway -Santa Clara, CA 95050 -United States, married=true, numberOfKids=3, favouriteQuote="You've got to ask yourself one question: "Do I feel lucky?" Well, do ya, punk?" - Dirty Harry, email=billy34@hotmail.com, loyaltyPoints=36] ---------------------------------------------------------------------------------------------------------------- - -* Reading with CsvListReader - - {{{./apidocs/org/supercsv/io/CsvListReader.html}CsvListReader}} is the most primitive reader and should only be used if it's not possible - to use the other implementations. - - On the other hand, it is the only reader that can be used for reading CSV files with an arbitrary number of columns (which is not technically valid CSV, but still happens), - and it's a quick and dirty way to read CSV as a List of Strings. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of reading using CsvListReader. - */ -private static void readWithCsvListReader() throws Exception { - - ICsvListReader listReader = null; - try { - listReader = new CsvListReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - listReader.getHeader(true); // skip the header (can't be used with CsvListReader) - final CellProcessor[] processors = getProcessors(); - - List customerList; - while( (customerList = listReader.read(processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customerList=%s", listReader.getLineNumber(), - listReader.getRowNumber(), customerList)); - } - - } - finally { - if( listReader != null ) { - listReader.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -lineNo=4, rowNo=2, customerList=[1, John, Dunbar, Wed Jun 13 00:00:00 EST 1945, 1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States, null, null, "May the Force be with you." - Star Wars, jdunbar@gmail.com, 0] -lineNo=7, rowNo=3, customerList=[2, Bob, Down, Tue Feb 25 00:00:00 EST 1919, 1601 Willow Rd. -Menlo Park, CA 94025 -United States, true, 0, "Frankly, my dear, I don't give a damn." - Gone With The Wind, bobdown@hotmail.com, 123456] -lineNo=10, rowNo=4, customerList=[3, Alice, Wunderland, Thu Aug 08 00:00:00 EST 1985, One Microsoft Way -Redmond, WA 98052-6399 -United States, true, 0, "Play it, Sam. Play "As Time Goes By."" - Casablanca, throughthelookingglass@yahoo.com, 2255887799] -lineNo=13, rowNo=5, customerList=[4, Bill, Jobs, Tue Jul 10 00:00:00 EST 1973, 2701 San Tomas Expressway -Santa Clara, CA 95050 -United States, true, 3, "You've got to ask yourself one question: "Do I feel lucky?" Well, do ya, punk?" - Dirty Harry, billy34@hotmail.com, 36] ---------------------------------------------------------------------------------------------------------------- - -* Reading with CsvMapReader - - {{{./apidocs/org/supercsv/io/CsvMapReader.html}CsvMapReader}} is a good compromise if you can't use {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}}. - It allows you to retrieve each column by name from the resulting Map, though you'll have to cast each column to it's appropriate type. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of reading using CsvMapReader. - */ -private static void readWithCsvMapReader() throws Exception { - - ICsvMapReader mapReader = null; - try { - mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - // the header columns are used as the keys to the Map - final String[] header = mapReader.getHeader(true); - final CellProcessor[] processors = getProcessors(); - - Map customerMap; - while( (customerMap = mapReader.read(header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), - mapReader.getRowNumber(), customerMap)); - } - - } - finally { - if( mapReader != null ) { - mapReader.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -lineNo=4, rowNo=2, customerMap={loyaltyPoints=0, lastName=Dunbar, numberOfKids=null, married=null, email=jdunbar@gmail.com, customerNo=1, birthDate=Wed Jun 13 00:00:00 EST 1945, firstName=John, mailingAddress=1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States, favouriteQuote="May the Force be with you." - Star Wars} -lineNo=7, rowNo=3, customerMap={loyaltyPoints=123456, lastName=Down, numberOfKids=0, married=true, email=bobdown@hotmail.com, customerNo=2, birthDate=Tue Feb 25 00:00:00 EST 1919, firstName=Bob, mailingAddress=1601 Willow Rd. -Menlo Park, CA 94025 -United States, favouriteQuote="Frankly, my dear, I don't give a damn." - Gone With The Wind} -lineNo=10, rowNo=4, customerMap={loyaltyPoints=2255887799, lastName=Wunderland, numberOfKids=0, married=true, email=throughthelookingglass@yahoo.com, customerNo=3, birthDate=Thu Aug 08 00:00:00 EST 1985, firstName=Alice, mailingAddress=One Microsoft Way -Redmond, WA 98052-6399 -United States, favouriteQuote="Play it, Sam. Play "As Time Goes By."" - Casablanca} -lineNo=13, rowNo=5, customerMap={loyaltyPoints=36, lastName=Jobs, numberOfKids=3, married=true, email=billy34@hotmail.com, customerNo=4, birthDate=Tue Jul 10 00:00:00 EST 1973, firstName=Bill, mailingAddress=2701 San Tomas Expressway -Santa Clara, CA 95050 -United States, favouriteQuote="You've got to ask yourself one question: "Do I feel lucky?" Well, do ya, punk?" - Dirty Harry} ---------------------------------------------------------------------------------------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ----------------- + Reading CSV files + ----------------- + +Reading CSV files + + This page contains some examples of reading CSV files using Super CSV. + You can view the full source of the examples {{{./xref-test/org/supercsv/example/Reading.html}here}}. + For examples of reading CSV files with Dozer (using CsvDozerBeanReader), click {{{./examples_dozer.html}here}}. + +* Example CSV file + + Here is an example CSV file. It has a header and 4 rows of data, all with 10 columns. + The <<>> column contains data that spans multiple lines and the <<>> column + contains data with escaped quotes. + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints +1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 +2,Bob,Down,25/02/1919,"1601 Willow Rd. +Menlo Park, CA 94025 +United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 +3,Alice,Wunderland,08/08/1985,"One Microsoft Way +Redmond, WA 98052-6399 +United States",Y,0,"""Play it, Sam. Play ""As Time Goes By."""" - Casablanca",throughthelookingglass@yahoo.com,2255887799 +4,Bill,Jobs,10/07/1973,"2701 San Tomas Expressway +Santa Clara, CA 95050 +United States",Y,3,"""You've got to ask yourself one question: ""Do I feel lucky?"" Well, do ya, punk?"" - Dirty Harry",billy34@hotmail.com,36 +--------------------------------------------------------------------------------------------------------------- + +* Example cell processor configuration + + All of the examples on this page use the following {{{./cell_processors.html}cell processor}} configuration. + + It demonstrates: + + * mandatory columns (<<>>) + + * optional columns (<<>>), with further processing + + * conversion to Date (<<>>), Boolean (<<>>) and Integer (<<>>) types + + * constraint validation against regular expressions (<<>>), numeric ranges (<<>>) and uniqueness (<<>>) + + [] + + Don't forget that you can {{{./examples_new_cell_processor.html}write your own cell processors}} if you want! + ++-------------------------------------------------------------------------------------------------------------+ +/** + * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. Empty + * columns are read as null (hence the NotNull() for mandatory columns). + * + * @return the cell processors + */ +private static CellProcessor[] getProcessors() { + + final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust! + StrRegEx.registerMessage(emailRegex, "must be a valid email address"); + + final CellProcessor[] processors = new CellProcessor[] { + new UniqueHashCode(), // customerNo (must be unique) + new NotNull(), // firstName + new NotNull(), // lastName + new ParseDate("dd/MM/yyyy"), // birthDate + new NotNull(), // mailingAddress + new Optional(new ParseBool()), // married + new Optional(new ParseInt()), // numberOfKids + new NotNull(), // favouriteQuote + new StrRegEx(emailRegex), // email + new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints + }; + + return processors; +} ++-------------------------------------------------------------------------------------------------------------+ + +* Reading with CsvBeanReader + + {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}} is the easiest reader to work with. + The example reads each row from the example CSV file into a {{{./xref-test/org/supercsv/mock/CustomerBean.html}CustomerBean}} (which extends + from {{{./xref-test/org/supercsv/mock/PersonBean.html}PersonBean}}). + + This relies on the fact that the column names in the header of the CSV file + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints +--------------------------------------------------------------------------------------------------------------- + + match up exactly with the bean's field names, and the bean has the appropriate setters defined for each field. + + If your header doesn't match (or there is no header), then you can simply define your own name mapping array. + + Note that the field types in the bean are compatible with the type returned by the cell processors + (e.g. <<>> is a <<>> in the bean, and uses the <<>> cell processor). + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of reading using CsvBeanReader. + */ +private static void readWithCsvBeanReader() throws Exception { + + ICsvBeanReader beanReader = null; + try { + beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + // the header elements are used to map the values to the bean (names must match) + final String[] header = beanReader.getHeader(true); + final CellProcessor[] processors = getProcessors(); + + CustomerBean customer; + while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), + beanReader.getRowNumber(), customer)); + } + + } + finally { + if( beanReader != null ) { + beanReader.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +lineNo=4, rowNo=2, customer=CustomerBean [customerNo=1, firstName=John, lastName=Dunbar, birthDate=Wed Jun 13 00:00:00 EST 1945, mailingAddress=1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States, married=null, numberOfKids=null, favouriteQuote="May the Force be with you." - Star Wars, email=jdunbar@gmail.com, loyaltyPoints=0] +lineNo=7, rowNo=3, customer=CustomerBean [customerNo=2, firstName=Bob, lastName=Down, birthDate=Tue Feb 25 00:00:00 EST 1919, mailingAddress=1601 Willow Rd. +Menlo Park, CA 94025 +United States, married=true, numberOfKids=0, favouriteQuote="Frankly, my dear, I don't give a damn." - Gone With The Wind, email=bobdown@hotmail.com, loyaltyPoints=123456] +lineNo=10, rowNo=4, customer=CustomerBean [customerNo=3, firstName=Alice, lastName=Wunderland, birthDate=Thu Aug 08 00:00:00 EST 1985, mailingAddress=One Microsoft Way +Redmond, WA 98052-6399 +United States, married=true, numberOfKids=0, favouriteQuote="Play it, Sam. Play "As Time Goes By."" - Casablanca, email=throughthelookingglass@yahoo.com, loyaltyPoints=2255887799] +lineNo=13, rowNo=5, customer=CustomerBean [customerNo=4, firstName=Bill, lastName=Jobs, birthDate=Tue Jul 10 00:00:00 EST 1973, mailingAddress=2701 San Tomas Expressway +Santa Clara, CA 95050 +United States, married=true, numberOfKids=3, favouriteQuote="You've got to ask yourself one question: "Do I feel lucky?" Well, do ya, punk?" - Dirty Harry, email=billy34@hotmail.com, loyaltyPoints=36] +--------------------------------------------------------------------------------------------------------------- + +* Reading with CsvListReader + + {{{./apidocs/org/supercsv/io/CsvListReader.html}CsvListReader}} is the most primitive reader and should only be used if it's not possible + to use the other implementations. + + On the other hand, it is the only reader that can be used for reading CSV files with an arbitrary number of columns (which is not technically valid CSV, but still happens), + and it's a quick and dirty way to read CSV as a List of Strings. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of reading using CsvListReader. + */ +private static void readWithCsvListReader() throws Exception { + + ICsvListReader listReader = null; + try { + listReader = new CsvListReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + listReader.getHeader(true); // skip the header (can't be used with CsvListReader) + final CellProcessor[] processors = getProcessors(); + + List customerList; + while( (customerList = listReader.read(processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customerList=%s", listReader.getLineNumber(), + listReader.getRowNumber(), customerList)); + } + + } + finally { + if( listReader != null ) { + listReader.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +lineNo=4, rowNo=2, customerList=[1, John, Dunbar, Wed Jun 13 00:00:00 EST 1945, 1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States, null, null, "May the Force be with you." - Star Wars, jdunbar@gmail.com, 0] +lineNo=7, rowNo=3, customerList=[2, Bob, Down, Tue Feb 25 00:00:00 EST 1919, 1601 Willow Rd. +Menlo Park, CA 94025 +United States, true, 0, "Frankly, my dear, I don't give a damn." - Gone With The Wind, bobdown@hotmail.com, 123456] +lineNo=10, rowNo=4, customerList=[3, Alice, Wunderland, Thu Aug 08 00:00:00 EST 1985, One Microsoft Way +Redmond, WA 98052-6399 +United States, true, 0, "Play it, Sam. Play "As Time Goes By."" - Casablanca, throughthelookingglass@yahoo.com, 2255887799] +lineNo=13, rowNo=5, customerList=[4, Bill, Jobs, Tue Jul 10 00:00:00 EST 1973, 2701 San Tomas Expressway +Santa Clara, CA 95050 +United States, true, 3, "You've got to ask yourself one question: "Do I feel lucky?" Well, do ya, punk?" - Dirty Harry, billy34@hotmail.com, 36] +--------------------------------------------------------------------------------------------------------------- + +* Reading with CsvMapReader + + {{{./apidocs/org/supercsv/io/CsvMapReader.html}CsvMapReader}} is a good compromise if you can't use {{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}}. + It allows you to retrieve each column by name from the resulting Map, though you'll have to cast each column to it's appropriate type. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of reading using CsvMapReader. + */ +private static void readWithCsvMapReader() throws Exception { + + ICsvMapReader mapReader = null; + try { + mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + // the header columns are used as the keys to the Map + final String[] header = mapReader.getHeader(true); + final CellProcessor[] processors = getProcessors(); + + Map customerMap; + while( (customerMap = mapReader.read(header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), + mapReader.getRowNumber(), customerMap)); + } + + } + finally { + if( mapReader != null ) { + mapReader.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +lineNo=4, rowNo=2, customerMap={loyaltyPoints=0, lastName=Dunbar, numberOfKids=null, married=null, email=jdunbar@gmail.com, customerNo=1, birthDate=Wed Jun 13 00:00:00 EST 1945, firstName=John, mailingAddress=1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States, favouriteQuote="May the Force be with you." - Star Wars} +lineNo=7, rowNo=3, customerMap={loyaltyPoints=123456, lastName=Down, numberOfKids=0, married=true, email=bobdown@hotmail.com, customerNo=2, birthDate=Tue Feb 25 00:00:00 EST 1919, firstName=Bob, mailingAddress=1601 Willow Rd. +Menlo Park, CA 94025 +United States, favouriteQuote="Frankly, my dear, I don't give a damn." - Gone With The Wind} +lineNo=10, rowNo=4, customerMap={loyaltyPoints=2255887799, lastName=Wunderland, numberOfKids=0, married=true, email=throughthelookingglass@yahoo.com, customerNo=3, birthDate=Thu Aug 08 00:00:00 EST 1985, firstName=Alice, mailingAddress=One Microsoft Way +Redmond, WA 98052-6399 +United States, favouriteQuote="Play it, Sam. Play "As Time Goes By."" - Casablanca} +lineNo=13, rowNo=5, customerMap={loyaltyPoints=36, lastName=Jobs, numberOfKids=3, married=true, email=billy34@hotmail.com, customerNo=4, birthDate=Tue Jul 10 00:00:00 EST 1973, firstName=Bill, mailingAddress=2701 San Tomas Expressway +Santa Clara, CA 95050 +United States, favouriteQuote="You've got to ask yourself one question: "Do I feel lucky?" Well, do ya, punk?" - Dirty Harry} +--------------------------------------------------------------------------------------------------------------- diff --git a/src/site/apt/examples_writing.apt b/src/site/apt/examples_writing.apt index 90fb844f..33c6fa68 100644 --- a/src/site/apt/examples_writing.apt +++ b/src/site/apt/examples_writing.apt @@ -1,279 +1,279 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ----------------- - Writing CSV files - ----------------- - -Writing CSV files - - This page contains some examples of writing CSV files using Super CSV. - You can view the full source of the examples {{{./xref-test/org/supercsv/example/Writing.html}here}}. - For examples of writing CSV files with Dozer (using CsvDozerBeanWriter), click {{{./examples_dozer.html}here}}. - -* Example cell processor configuration - - All of the examples on this page use the following {{{./cell_processors.html}cell processor}} configuration. - - It demonstrates: - - * mandatory columns (<<>>) - - * optional columns (<<>>), with further processing - - * formatting of Dates (<<>>) and Booleans (<<>>) - - * constraint validation of numeric ranges (<<>>) and uniqueness (<<>>) - - [] - - Don't forget that you can {{{./examples_new_cell_processor.html}write your own cell processors}} if you want! - -+-------------------------------------------------------------------------------------------------------------+ -/** - * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. All values - * are converted to Strings before writing (there's no need to convert them), and null values will be written as - * empty columns (no need to convert them to ""). - * - * @return the cell processors - */ -private static CellProcessor[] getProcessors() { - - final CellProcessor[] processors = new CellProcessor[] { - new UniqueHashCode(), // customerNo (must be unique) - new NotNull(), // firstName - new NotNull(), // lastName - new FmtDate("dd/MM/yyyy"), // birthDate - new NotNull(), // mailingAddress - new Optional(new FmtBool("Y", "N")), // married - new Optional(), // numberOfKids - new NotNull(), // favouriteQuote - new NotNull(), // email - new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints - }; - - return processors; -} -+-------------------------------------------------------------------------------------------------------------+ - -* Writing with CsvBeanWriter - - {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}} is the easiest writer to work with. - The example writes a List of {{{./xref-test/org/supercsv/mock/CustomerBean.html}CustomerBean}}s (which extend - from {{{./xref-test/org/supercsv/mock/PersonBean.html}PersonBean}}) to a CSV file. - - This relies on the fact that the bean's field names match up exactly with the column names in the header of the CSV file - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints ---------------------------------------------------------------------------------------------------------------- - - and the bean has the appropriate getters defined for each field. - - If your header doesn't match (the column names have spaces, for example), then you can simply define your own name mapping array that match the field names. - - Note that the cell processors are compatible with their associated field types in the bean - (e.g. <<>> is a <<>> in the bean, and uses the <<>> cell processor). - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of writing using CsvBeanWriter. - */ -private static void writeWithCsvBeanWriter() throws Exception { - - // create the customer beans - final CustomerBean john = new CustomerBean("1", "John", "Dunbar", - new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), - "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, - "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); - final CustomerBean bob = new CustomerBean("2", "Bob", "Down", - new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), - "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, - "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); - final List customers = Arrays.asList(john, bob); - - ICsvBeanWriter beanWriter = null; - try { - beanWriter = new CsvBeanWriter(new FileWriter("target/writeWithCsvBeanWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // the header elements are used to map the bean values to each column (names must match) - final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", - "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; - final CellProcessor[] processors = getProcessors(); - - // write the header - beanWriter.writeHeader(header); - - // write the beans - for( final CustomerBean customer : customers ) { - beanWriter.write(customer, header, processors); - } - - } - finally { - if( beanWriter != null ) { - beanWriter.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints -1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 -2,Bob,Down,25/02/1919,"1601 Willow Rd. -Menlo Park, CA 94025 -United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 ---------------------------------------------------------------------------------------------------------------- - -* Writing with CsvListWriter - - {{{./apidocs/org/supercsv/io/CsvListWriter.html}CsvListWriter}} is the most primitive writer and should only be used if it's not possible - to use the other implementations. - - On the other hand, it is the only writer that can be used for writing CSV files with an arbitrary number of columns (which is not technically valid CSV, but still happens), - and it's a quick and dirty way to write CSV from a List or array of Strings. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of reading using CsvListWriter. - */ -private static void writeWithCsvListWriter() throws Exception { - - // create the customer Lists (CsvListWriter also accepts arrays!) - final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar", - new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), - "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, - "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L }); - - final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", - new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), - "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, - "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L }); - - ICsvListWriter listWriter = null; - try { - listWriter = new CsvListWriter(new FileWriter("target/writeWithCsvListWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - final CellProcessor[] processors = getProcessors(); - final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", - "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; - - // write the header - listWriter.writeHeader(header); - - // write the customer lists - listWriter.write(john, processors); - listWriter.write(bob, processors); - - } - finally { - if( listWriter != null ) { - listWriter.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints -1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 -2,Bob,Down,25/02/1919,"1601 Willow Rd. -Menlo Park, CA 94025 -United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 ---------------------------------------------------------------------------------------------------------------- - -* Writing with CsvMapWriter - - {{{./apidocs/org/supercsv/io/CsvMapWriter.html}CsvMapWriter}} is a good compromise if you can't use {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}}. - -+-------------------------------------------------------------------------------------------------------------+ -/** - * An example of reading using CsvMapWriter. - */ -private static void writeWithCsvMapWriter() throws Exception { - - final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress", - "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; - - // create the customer Maps (using the header elements for the column keys) - final Map john = new HashMap(); - john.put(header[0], "1"); - john.put(header[1], "John"); - john.put(header[2], "Dunbar"); - john.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTime()); - john.put(header[4], "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States"); - john.put(header[5], null); - john.put(header[6], null); - john.put(header[7], "\"May the Force be with you.\" - Star Wars"); - john.put(header[8], "jdunbar@gmail.com"); - john.put(header[9], 0L); - - final Map bob = new HashMap(); - bob.put(header[0], "2"); - bob.put(header[1], "Bob"); - bob.put(header[2], "Down"); - bob.put(header[3], new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime()); - bob.put(header[4], "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States"); - bob.put(header[5], true); - bob.put(header[6], 0); - bob.put(header[7], "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind"); - bob.put(header[8], "bobdown@hotmail.com"); - bob.put(header[9], 123456L); - - ICsvMapWriter mapWriter = null; - try { - mapWriter = new CsvMapWriter(new FileWriter("target/writeWithCsvMapWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - final CellProcessor[] processors = getProcessors(); - - // write the header - mapWriter.writeHeader(header); - - // write the customer maps - mapWriter.write(john, header, processors); - mapWriter.write(bob, header, processors); - - } - finally { - if( mapWriter != null ) { - mapWriter.close(); - } - } -} -+-------------------------------------------------------------------------------------------------------------+ - - Output: - ---------------------------------------------------------------------------------------------------------------- -customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints -1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 -2,Bob,Down,25/02/1919,"1601 Willow Rd. -Menlo Park, CA 94025 -United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ----------------- + Writing CSV files + ----------------- + +Writing CSV files + + This page contains some examples of writing CSV files using Super CSV. + You can view the full source of the examples {{{./xref-test/org/supercsv/example/Writing.html}here}}. + For examples of writing CSV files with Dozer (using CsvDozerBeanWriter), click {{{./examples_dozer.html}here}}. + +* Example cell processor configuration + + All of the examples on this page use the following {{{./cell_processors.html}cell processor}} configuration. + + It demonstrates: + + * mandatory columns (<<>>) + + * optional columns (<<>>), with further processing + + * formatting of Dates (<<>>) and Booleans (<<>>) + + * constraint validation of numeric ranges (<<>>) and uniqueness (<<>>) + + [] + + Don't forget that you can {{{./examples_new_cell_processor.html}write your own cell processors}} if you want! + ++-------------------------------------------------------------------------------------------------------------+ +/** + * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. All values + * are converted to Strings before writing (there's no need to convert them), and null values will be written as + * empty columns (no need to convert them to ""). + * + * @return the cell processors + */ +private static CellProcessor[] getProcessors() { + + final CellProcessor[] processors = new CellProcessor[] { + new UniqueHashCode(), // customerNo (must be unique) + new NotNull(), // firstName + new NotNull(), // lastName + new FmtDate("dd/MM/yyyy"), // birthDate + new NotNull(), // mailingAddress + new Optional(new FmtBool("Y", "N")), // married + new Optional(), // numberOfKids + new NotNull(), // favouriteQuote + new NotNull(), // email + new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints + }; + + return processors; +} ++-------------------------------------------------------------------------------------------------------------+ + +* Writing with CsvBeanWriter + + {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}} is the easiest writer to work with. + The example writes a List of {{{./xref-test/org/supercsv/mock/CustomerBean.html}CustomerBean}}s (which extend + from {{{./xref-test/org/supercsv/mock/PersonBean.html}PersonBean}}) to a CSV file. + + This relies on the fact that the bean's field names match up exactly with the column names in the header of the CSV file + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints +--------------------------------------------------------------------------------------------------------------- + + and the bean has the appropriate getters defined for each field. + + If your header doesn't match (the column names have spaces, for example), then you can simply define your own name mapping array that match the field names. + + Note that the cell processors are compatible with their associated field types in the bean + (e.g. <<>> is a <<>> in the bean, and uses the <<>> cell processor). + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of writing using CsvBeanWriter. + */ +private static void writeWithCsvBeanWriter() throws Exception { + + // create the customer beans + final CustomerBean john = new CustomerBean("1", "John", "Dunbar", + new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), + "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, + "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); + final CustomerBean bob = new CustomerBean("2", "Bob", "Down", + new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), + "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, + "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); + final List customers = Arrays.asList(john, bob); + + ICsvBeanWriter beanWriter = null; + try { + beanWriter = new CsvBeanWriter(new FileWriter("target/writeWithCsvBeanWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // the header elements are used to map the bean values to each column (names must match) + final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", + "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; + final CellProcessor[] processors = getProcessors(); + + // write the header + beanWriter.writeHeader(header); + + // write the beans + for( final CustomerBean customer : customers ) { + beanWriter.write(customer, header, processors); + } + + } + finally { + if( beanWriter != null ) { + beanWriter.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints +1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 +2,Bob,Down,25/02/1919,"1601 Willow Rd. +Menlo Park, CA 94025 +United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 +--------------------------------------------------------------------------------------------------------------- + +* Writing with CsvListWriter + + {{{./apidocs/org/supercsv/io/CsvListWriter.html}CsvListWriter}} is the most primitive writer and should only be used if it's not possible + to use the other implementations. + + On the other hand, it is the only writer that can be used for writing CSV files with an arbitrary number of columns (which is not technically valid CSV, but still happens), + and it's a quick and dirty way to write CSV from a List or array of Strings. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of reading using CsvListWriter. + */ +private static void writeWithCsvListWriter() throws Exception { + + // create the customer Lists (CsvListWriter also accepts arrays!) + final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar", + new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), + "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, + "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L }); + + final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", + new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), + "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, + "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L }); + + ICsvListWriter listWriter = null; + try { + listWriter = new CsvListWriter(new FileWriter("target/writeWithCsvListWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + final CellProcessor[] processors = getProcessors(); + final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", + "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; + + // write the header + listWriter.writeHeader(header); + + // write the customer lists + listWriter.write(john, processors); + listWriter.write(bob, processors); + + } + finally { + if( listWriter != null ) { + listWriter.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints +1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 +2,Bob,Down,25/02/1919,"1601 Willow Rd. +Menlo Park, CA 94025 +United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 +--------------------------------------------------------------------------------------------------------------- + +* Writing with CsvMapWriter + + {{{./apidocs/org/supercsv/io/CsvMapWriter.html}CsvMapWriter}} is a good compromise if you can't use {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}}. + ++-------------------------------------------------------------------------------------------------------------+ +/** + * An example of reading using CsvMapWriter. + */ +private static void writeWithCsvMapWriter() throws Exception { + + final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress", + "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; + + // create the customer Maps (using the header elements for the column keys) + final Map john = new HashMap(); + john.put(header[0], "1"); + john.put(header[1], "John"); + john.put(header[2], "Dunbar"); + john.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTime()); + john.put(header[4], "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States"); + john.put(header[5], null); + john.put(header[6], null); + john.put(header[7], "\"May the Force be with you.\" - Star Wars"); + john.put(header[8], "jdunbar@gmail.com"); + john.put(header[9], 0L); + + final Map bob = new HashMap(); + bob.put(header[0], "2"); + bob.put(header[1], "Bob"); + bob.put(header[2], "Down"); + bob.put(header[3], new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime()); + bob.put(header[4], "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States"); + bob.put(header[5], true); + bob.put(header[6], 0); + bob.put(header[7], "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind"); + bob.put(header[8], "bobdown@hotmail.com"); + bob.put(header[9], 123456L); + + ICsvMapWriter mapWriter = null; + try { + mapWriter = new CsvMapWriter(new FileWriter("target/writeWithCsvMapWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + final CellProcessor[] processors = getProcessors(); + + // write the header + mapWriter.writeHeader(header); + + // write the customer maps + mapWriter.write(john, header, processors); + mapWriter.write(bob, header, processors); + + } + finally { + if( mapWriter != null ) { + mapWriter.close(); + } + } +} ++-------------------------------------------------------------------------------------------------------------+ + + Output: + +--------------------------------------------------------------------------------------------------------------- +customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints +1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 +2,Bob,Down,25/02/1919,"1601 Willow Rd. +Menlo Park, CA 94025 +United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 --------------------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/src/site/apt/getting_started.apt b/src/site/apt/getting_started.apt index 4f25eef9..e5043cec 100644 --- a/src/site/apt/getting_started.apt +++ b/src/site/apt/getting_started.apt @@ -1,31 +1,31 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - --------------- - Where to begin? - --------------- - -Where to begin? - - [[1]] {{{./downloading.html}Download}} Super CSV - - [[2]] Choose a {{{./readers.html}reader}} or {{{./writers.html}writer}} - there are 4 of each to choose from! - - [[3]] Choose your {{{./preferences.html}preferences}} for reading/writing (including choice of delimiter, quote character, and end of line symbols) - - [[4]] Choose from a wide variety of {{{./cell_processors.html}cell processors}} to apply conversions or constraints to your data - - [[5]] Check out the {{{./examples_reading.html}reading}} and {{{./examples_writing.html}writing}} examples to see how it's all put together! - +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + --------------- + Where to begin? + --------------- + +Where to begin? + + [[1]] {{{./downloading.html}Download}} Super CSV + + [[2]] Choose a {{{./readers.html}reader}} or {{{./writers.html}writer}} - there are 4 of each to choose from! + + [[3]] Choose your {{{./preferences.html}preferences}} for reading/writing (including choice of delimiter, quote character, and end of line symbols) + + [[4]] Choose from a wide variety of {{{./cell_processors.html}cell processors}} to apply conversions or constraints to your data + + [[5]] Check out the {{{./examples_reading.html}reading}} and {{{./examples_writing.html}writing}} examples to see how it's all put together! + diff --git a/src/site/apt/help.apt b/src/site/apt/help.apt index 8643e337..95b56cb0 100644 --- a/src/site/apt/help.apt +++ b/src/site/apt/help.apt @@ -1,39 +1,39 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ----- - Help! - ----- - -Help! - -* General help - - If you've read the documentation and examples and you still need help - then don't hesitate to ask on the Super CSV {{{https://sourceforge.net/p/supercsv/discussion/718795/}Help forum}}. - - The Super CSV developers also maintain an active presence on {{{http://stackoverflow.com/questions/tagged/supercsv}StackOverflow}} - - just be sure to use the <<>> tag. - -* Found a bug? - - If you believe you've genuinely found a bug that hasn't been previously raised, then please report it on the - {{{https://sourceforge.net/p/supercsv/bugs/}bug tracker}}. Make sure you include: - - * the version of Super CSV you're using - - * sample code/CSV that demonstrates how to reproduce the bug - +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ----- + Help! + ----- + +Help! + +* General help + + If you've read the documentation and examples and you still need help + then don't hesitate to ask on the Super CSV {{{https://sourceforge.net/p/supercsv/discussion/718795/}Help forum}}. + + The Super CSV developers also maintain an active presence on {{{http://stackoverflow.com/questions/tagged/supercsv}StackOverflow}} - + just be sure to use the <<>> tag. + +* Found a bug? + + If you believe you've genuinely found a bug that hasn't been previously raised, then please report it on the + {{{https://sourceforge.net/p/supercsv/bugs/}bug tracker}}. Make sure you include: + + * the version of Super CSV you're using + + * sample code/CSV that demonstrates how to reproduce the bug + * any other details that might help \ No newline at end of file diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt index f4e8795f..27dd0666 100644 --- a/src/site/apt/index.apt +++ b/src/site/apt/index.apt @@ -1,78 +1,78 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ------- - Welcome - ------- - -Super CSV - -* Motivation - - The main motivation for Super CSV is to be the . - -* Features - - Super CSV offers the following features not found together in other CSV packages: - -** POJO support - - Read or write using any old Javabean. - Perform and using the new Dozer extension! - For the old-fashioned, you can read or write with Lists and Maps as well. - -** Automatic CSV encoding - - Forget about handling special characters such as commas and double-quotes - Super CSV will take care of that for you! - All content is properly escaped/un-escaped according to the {{{./csv_specification.html}CSV specification}}. - -** Highly configurable - - Choose your own delimiter, quote character and line separator - or just use one of the predefined configurations. - Comma-separated, tab-separated, semicolon-separated (Germany/Denmark) - it's all possible. - -** Data conversion - - Powerful cell processors make it simple to parse input (to Booleans, Integers, Dates, etc), - transform values (trimming Strings, doing regular expression replacement, etc) and format output like Dates and Numbers. - -** Constraint validation - - Verify that your data conforms to one or more constraints, such as number ranges, string lengths or uniqueness. - -** Stream-based I/O - - Operates on streams rather than filenames, and gives you the control to flush or close the streams when you want. - Write to a file, over the network, to a zip file, whatever! - -* Message from the author - - My years in industry dealing with CSV files (among other things ;-), has enabled me to identify a number of limitations with existing CSV packages. - These limitations led me to write Super CSV. - My main criticism of existing CSV packages is that reading and writing operates on lists of strings. - What you really need is the ability to operate on a range of different types of objects. - Moreover, you often need to restrict input/output data with constraints such as minimum and maximum sizes, or numeric ranges. - Or maybe you are reading image names, and want to ensure you do not read names contain the characters ":", " ", "/", "^", "%". - - Super CSV deals with all these and many other issues. - And should you have a constraint not readily expressible in the package, new cell processors can easily be constructed. - Furthermore, you don't want to "CSV encode" strings you write. If they happen to contain characters that needs escaping, then the CSV package should take care of this automatically! - - The underlying implementation of Super CSV has been written in an extensible fashion, hence new readers/writers and cell processors can easily be supported. - The implementation pattern has been enforced, eradicating long-lived mistakes such as using - filenames as arguments rather than Reader and Writer objects. Design patterns such as and the - can also be found in the code. Feel free to have a look! - +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ------- + Welcome + ------- + +Super CSV + +* Motivation + + The main motivation for Super CSV is to be the . + +* Features + + Super CSV offers the following features not found together in other CSV packages: + +** POJO support + + Read or write using any old Javabean. + Perform and using the new Dozer extension! + For the old-fashioned, you can read or write with Lists and Maps as well. + +** Automatic CSV encoding + + Forget about handling special characters such as commas and double-quotes - Super CSV will take care of that for you! + All content is properly escaped/un-escaped according to the {{{./csv_specification.html}CSV specification}}. + +** Highly configurable + + Choose your own delimiter, quote character and line separator - or just use one of the predefined configurations. + Comma-separated, tab-separated, semicolon-separated (Germany/Denmark) - it's all possible. + +** Data conversion + + Powerful cell processors make it simple to parse input (to Booleans, Integers, Dates, etc), + transform values (trimming Strings, doing regular expression replacement, etc) and format output like Dates and Numbers. + +** Constraint validation + + Verify that your data conforms to one or more constraints, such as number ranges, string lengths or uniqueness. + +** Stream-based I/O + + Operates on streams rather than filenames, and gives you the control to flush or close the streams when you want. + Write to a file, over the network, to a zip file, whatever! + +* Message from the author + + My years in industry dealing with CSV files (among other things ;-), has enabled me to identify a number of limitations with existing CSV packages. + These limitations led me to write Super CSV. + My main criticism of existing CSV packages is that reading and writing operates on lists of strings. + What you really need is the ability to operate on a range of different types of objects. + Moreover, you often need to restrict input/output data with constraints such as minimum and maximum sizes, or numeric ranges. + Or maybe you are reading image names, and want to ensure you do not read names contain the characters ":", " ", "/", "^", "%". + + Super CSV deals with all these and many other issues. + And should you have a constraint not readily expressible in the package, new cell processors can easily be constructed. + Furthermore, you don't want to "CSV encode" strings you write. If they happen to contain characters that needs escaping, then the CSV package should take care of this automatically! + + The underlying implementation of Super CSV has been written in an extensible fashion, hence new readers/writers and cell processors can easily be supported. + The implementation pattern has been enforced, eradicating long-lived mistakes such as using + filenames as arguments rather than Reader and Writer objects. Design patterns such as and the + can also be found in the code. Feel free to have a look! + \ No newline at end of file diff --git a/src/site/apt/preferences.apt b/src/site/apt/preferences.apt index e9091078..b9c08762 100644 --- a/src/site/apt/preferences.apt +++ b/src/site/apt/preferences.apt @@ -1,90 +1,90 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - --------------- - CSV Preferences - --------------- - -CSV Preferences - - Readers and Writers in Super CSV are configured using the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} class. - This class is immutable and is assembled using the {{{http://en.wikipedia.org/wiki/Builder_pattern}Builder pattern}}. - - The preferences available are: - - [quoteChar] The quote character (used when a cell contains special characters, such as the delimiter char, a quote char, or spans multiple lines). - - [] - - [delimiterChar] The delimiter character (separates each cell in a row). - - [] - - [endOfLineSymbols] The end of line symbols to use when (Windows, Mac and Linux style line breaks are all supported when reading, so this preference won't be used at all for reading). - - [] - - [surroundingSpacesNeedQuotes] Whether spaces surrounding a cell need quotes in order to be preserved (see below). The default value is false (quotes aren't required). - -* Predefined preferences - - There are four 'ready to use' configurations for typical scenarios. - -*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* - <> || Quote character || Delimiter character || End of line symbols (for writing only) || Surrounding spaces require quotes -*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* - {{{./apidocs/org/supercsv/prefs/CsvPreference.html#STANDARD_PREFERENCE}STANDARD_PREFERENCE}} | " | , | \\r\\n | false -*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* - {{{./apidocs/org/supercsv/prefs/CsvPreference.html#EXCEL_PREFERENCE}EXCEL_PREFERENCE}} | " | , | \\n | false -*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* - {{{./apidocs/org/supercsv/prefs/CsvPreference.html#EXCEL_NORTH_EUROPE_PREFERENCE}EXCEL_NORTH_EUROPE_PREFERENCE}} | " | ; | \\n | false -*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* - {{{./apidocs/org/supercsv/prefs/CsvPreference.html#TAB_PREFERENCE}TAB_PREFERENCE}} | " | \\t | \\n | false -*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* - -* Create your own preference - - If none of the predefined preferences suit your purposes, you can easily create your own (you're not just limited to CSV files!). - For example, the following code snippet creates preferences suitable for reading/writing pipe-delimited files. - -+----------------------------------------------------------------------------------------------------+ -private static final CsvPreference PIPE_DELIMITED = new CsvPreference.Builder('"', '|', "\n").build(); -+----------------------------------------------------------------------------------------------------+ - -* Ignoring surrounding spaces if they're not within quotes - - In accordance with {{{http://tools.ietf.org/html/rfc4180}RFC 4180}}, the default behaviour of Super CSV is to treat all spaces as important, - . - - This means for reading, a cell with contents <<<\ \ \ surrounded by spaces\ \ \ >>> is read with surrounding spaces preserved. - And for writing, the same String is written with surrounding spaces and no surrounding quotes (they're not required, as spaces are considered important). - - There are some scenarios where this restriction must be relaxed, in particular when the CSV file you're working with assumes that - . For this reason, Super CSV allows you - to enable the <<>> preference. - - With <<>> enabled, it means that for reading, a cell with contents <<<\ \ \ surrounded by spaces\ \ \ >>>\ would be read as <<>> (surrounding spaces are trimmed), - unless the String has surrounding quotes, e.g. <<<"\ \ \ surrounded by spaces\ \ \ ">>>, in which case the spaces are preserved. - And for writing, any String containing surrounding spaces will automatically be given surrounding quotes when written in order to preserve the spaces. - - You can enable this behaviour by calling <<>> on the Builder. You can do this with your own custom preference, or customize an existing preference as shown below. - -+------------------------------------------------------------------------------------------------------------------------------------------------+ -private static final CsvPreference STANDARD_SURROUNDING_SPACES_NEED_QUOTES = - new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); -+------------------------------------------------------------------------------------------------------------------------------------------------+ - - Prior to Super CSV 2.0.0, this behaviour wasn't configurable and surrounding spaces were always trimmed. - +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + --------------- + CSV Preferences + --------------- + +CSV Preferences + + Readers and Writers in Super CSV are configured using the {{{./apidocs/org/supercsv/prefs/CsvPreference.html}CsvPreference}} class. + This class is immutable and is assembled using the {{{http://en.wikipedia.org/wiki/Builder_pattern}Builder pattern}}. + + The preferences available are: + + [quoteChar] The quote character (used when a cell contains special characters, such as the delimiter char, a quote char, or spans multiple lines). + + [] + + [delimiterChar] The delimiter character (separates each cell in a row). + + [] + + [endOfLineSymbols] The end of line symbols to use when (Windows, Mac and Linux style line breaks are all supported when reading, so this preference won't be used at all for reading). + + [] + + [surroundingSpacesNeedQuotes] Whether spaces surrounding a cell need quotes in order to be preserved (see below). The default value is false (quotes aren't required). + +* Predefined preferences + + There are four 'ready to use' configurations for typical scenarios. + +*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* + <> || Quote character || Delimiter character || End of line symbols (for writing only) || Surrounding spaces require quotes +*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* + {{{./apidocs/org/supercsv/prefs/CsvPreference.html#STANDARD_PREFERENCE}STANDARD_PREFERENCE}} | " | , | \\r\\n | false +*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* + {{{./apidocs/org/supercsv/prefs/CsvPreference.html#EXCEL_PREFERENCE}EXCEL_PREFERENCE}} | " | , | \\n | false +*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* + {{{./apidocs/org/supercsv/prefs/CsvPreference.html#EXCEL_NORTH_EUROPE_PREFERENCE}EXCEL_NORTH_EUROPE_PREFERENCE}} | " | ; | \\n | false +*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* + {{{./apidocs/org/supercsv/prefs/CsvPreference.html#TAB_PREFERENCE}TAB_PREFERENCE}} | " | \\t | \\n | false +*------------------------------------------------------------------------------------------------------------------+------------------*----------------------*-----------------------------------------*------------------------------------* + +* Create your own preference + + If none of the predefined preferences suit your purposes, you can easily create your own (you're not just limited to CSV files!). + For example, the following code snippet creates preferences suitable for reading/writing pipe-delimited files. + ++----------------------------------------------------------------------------------------------------+ +private static final CsvPreference PIPE_DELIMITED = new CsvPreference.Builder('"', '|', "\n").build(); ++----------------------------------------------------------------------------------------------------+ + +* Ignoring surrounding spaces if they're not within quotes + + In accordance with {{{http://tools.ietf.org/html/rfc4180}RFC 4180}}, the default behaviour of Super CSV is to treat all spaces as important, + . + + This means for reading, a cell with contents <<<\ \ \ surrounded by spaces\ \ \ >>> is read with surrounding spaces preserved. + And for writing, the same String is written with surrounding spaces and no surrounding quotes (they're not required, as spaces are considered important). + + There are some scenarios where this restriction must be relaxed, in particular when the CSV file you're working with assumes that + . For this reason, Super CSV allows you + to enable the <<>> preference. + + With <<>> enabled, it means that for reading, a cell with contents <<<\ \ \ surrounded by spaces\ \ \ >>>\ would be read as <<>> (surrounding spaces are trimmed), + unless the String has surrounding quotes, e.g. <<<"\ \ \ surrounded by spaces\ \ \ ">>>, in which case the spaces are preserved. + And for writing, any String containing surrounding spaces will automatically be given surrounding quotes when written in order to preserve the spaces. + + You can enable this behaviour by calling <<>> on the Builder. You can do this with your own custom preference, or customize an existing preference as shown below. + ++------------------------------------------------------------------------------------------------------------------------------------------------+ +private static final CsvPreference STANDARD_SURROUNDING_SPACES_NEED_QUOTES = + new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); ++------------------------------------------------------------------------------------------------------------------------------------------------+ + + Prior to Super CSV 2.0.0, this behaviour wasn't configurable and surrounding spaces were always trimmed. + diff --git a/src/site/apt/readers.apt b/src/site/apt/readers.apt index cf478379..e7990cbb 100644 --- a/src/site/apt/readers.apt +++ b/src/site/apt/readers.apt @@ -1,36 +1,36 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ----------- - CSV Readers - ----------- - -CSV Readers - - There are four CSV reading implementations in Super CSV. - -*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* - ||{{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}} ||{{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanReader.html}CsvDozerBeanReader}} ||{{{./apidocs/org/supercsv/io/CsvListReader.html}CsvListReader}} ||{{{./apidocs/org/supercsv/io/CsvMapReader.html}CsvMapReader}} -*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* - Reads each row of CSV as a | POJO (must be a valid Javabean, or interface with setters) | POJO (must be a valid Javabean) | List\ or List\ | Map\ or Map\ -*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* - Supports {{{./dozer.html}deep mapping and index-based mapping}}? | No | Yes | No | No -*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* - Supports {{{./examples_partial_reading.html}partial reading}} (ignoring columns)? | Yes | Yes | No | Yes -*------------------------------------------------------------------------------=----*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* - - Which one you choose will depend on your requirements, but we recommend using CsvBeanReader or CsvDozerBeanReader - where possible, as it's far easier to work with POJOs than Lists or Maps. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ----------- + CSV Readers + ----------- + +CSV Readers + + There are four CSV reading implementations in Super CSV. + +*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* + ||{{{./apidocs/org/supercsv/io/CsvBeanReader.html}CsvBeanReader}} ||{{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanReader.html}CsvDozerBeanReader}} ||{{{./apidocs/org/supercsv/io/CsvListReader.html}CsvListReader}} ||{{{./apidocs/org/supercsv/io/CsvMapReader.html}CsvMapReader}} +*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* + Reads each row of CSV as a | POJO (must be a valid Javabean, or interface with setters) | POJO (must be a valid Javabean) | List\ or List\ | Map\ or Map\ +*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* + Supports {{{./dozer.html}deep mapping and index-based mapping}}? | No | Yes | No | No +*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* + Supports {{{./examples_partial_reading.html}partial reading}} (ignoring columns)? | Yes | Yes | No | Yes +*------------------------------------------------------------------------------=----*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------* + + Which one you choose will depend on your requirements, but we recommend using CsvBeanReader or CsvDozerBeanReader + where possible, as it's far easier to work with POJOs than Lists or Maps. Check out the {{{./examples_reading.html}reading examples}} to see them in action. \ No newline at end of file diff --git a/src/site/apt/release_notes.apt b/src/site/apt/release_notes.apt index 51b9695c..5e7dc858 100644 --- a/src/site/apt/release_notes.apt +++ b/src/site/apt/release_notes.apt @@ -1,401 +1,401 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ------------- - Release notes - ------------- - -Release notes - -* 2.0.1 - - <12/2012> - - Just a small bug fix release to restore Java 5 compatibility (should also be more compatible with older versions of Android as well). - - <> - - * {{{https://sourceforge.net/p/supercsv/bugs/36/}36}} - CsvBeanReader allows a nameMapping array of the wrong size when processors aren't used - - * {{{https://sourceforge.net/p/supercsv/bugs/37/}37}} - Restore Java 5 compatibility - -* 2.0.0 - - <11/2012> - - This is the final release of version 2.0.0, which fixes a few minor bugs found in version 2.0.0-beta-1. - Please refer to the 2.0.0-beta-1 release notes below for a full list of new features, bug fixes and upgrade notes. - - - <> - - * {{{https://sourceforge.net/p/supercsv/bugs/33/}33}} - Added missing WEDNESDAY enum literal to custom cell processor example - - * {{{https://sourceforge.net/p/supercsv/bugs/34/}34}} - Added SLF4J API jar to distribution zip file - - * {{{https://sourceforge.net/p/supercsv/bugs/35/}35}} - CsvListReader now returns a new List for each <<>> operation - -* 2.0.0-beta-1 - - <09/2012> - - <> - - * 100% {{{http://tools.ietf.org/html/rfc4180}RFC 4180}} compliance - - * {{{https://sourceforge.net/p/supercsv/feature-requests/3/}3}} - Super CSV now supports mapping nested properties (deep mapping and index-based mapping) - with the new CsvDozerBeanReader and CsvDozerBeanWriter (included in the super-csv-dozer-extension project). - - * {{{https://sourceforge.net/p/supercsv/feature-requests/12/}12}} - CsvBeanReader now supports any compatible setter method (as long as the parameter type - interface or object - is compatible with the object being set). - Previously, the parameter type had to be an exact match on the object's type. - - * {{{https://sourceforge.net/p/supercsv/feature-requests/17/}17}} - All Writers implement <<>> - - * {{{https://sourceforge.net/p/supercsv/feature-requests/18/}18}} - OSGi support - - * {{{https://sourceforge.net/p/supercsv/feature-requests/19/}19}} - All Readers and Writers now implement <<>> - - * {{{https://sourceforge.net/p/supercsv/feature-requests/20/}20}} - Maven support (see details on the {{{./downloading.html}download}} page) - - * {{{https://sourceforge.net/p/supercsv/feature-requests/21/}21}} - All Readers now have a <<>> method for retrieving the raw String of the row just - read (before it's been tokenized). - All Readers and Writers now have a <<>> method for getting the number of CSV rows read/written (including the header). - This is different from <<>>, which returns the physical line number, as rows may span more than one line (the CSV - format allows for multiline fields, as long as they're within double-quotes). - - <> - - * {{{https://sourceforge.net/p/supercsv/bugs/12/}12}} - Fixed NPE in CsvBeanReader when value to set is null - - * {{{https://sourceforge.net/p/supercsv/bugs/14/}14}} - AbstractCsvWriter now escapes for trailing spaces - - * {{{https://sourceforge.net/p/supercsv/bugs/16/}16}} - Refactored Readers/Writers so it's no longer possible to modify preferences - - * {{{https://sourceforge.net/p/supercsv/bugs/19/}19}} - Fixed NPE in SuperCsvException constructor - - * {{{https://sourceforge.net/p/supercsv/bugs/21/}21}} - New <<>> preference allows the disabling of quoting for leading spaces - - * {{{https://sourceforge.net/p/supercsv/bugs/23/}23}} - CsvListWriter now allows all cell processors (not just String processors) - - * {{{https://sourceforge.net/p/supercsv/bugs/29/}29}} - Column numbers now start at 1 (instead of 0) - - * {{{https://sourceforge.net/p/supercsv/bugs/30/}30}} - All writers now allow null in the nameMapping array (except CsvDozerBeanWriter) - - <> - - * Complete overhaul of javadoc - - * Improved test coverage (now 100%!) - - * More defensive programming (à la Josh Bloch's ). - It's a lot harder to do silly stuff with the API now - for example CellProcessors will fail fast during construction if not set up correctly, instead of during execution. - - * A new and improved maven site (please like/+1 us!) - - * Removed dependency on the Spiffy library - Super CSV (excluding the new Dozer extension) is now completely standalone! - - <> - - As this is a major release and it's been 4 years since the last release, there have been numerous changes that are not backwards-compatible with older versions. - Here's an overview of things to be aware of when upgrading from version 1.52: - - * General changes - - * The treatment of spaces surrounding a cell has changed - - * All spaces are now considered important (to conform to RFC 4180), and surrounding spaces won't be trimmed by default - - * A new preference has been added to enable/disable this functionality (see the section on <<>> on the {{{./preferences.html}preferences}} page). - - * Line number, row number (a new property of both readers and writers) and column number all start from 1. This means: - - * the <<>> method of all Readers now expects the column number to begin at 1 (it was previously 0) - - * the column number reported in Exceptions (via the CsvContext object) begins at 1 - - * the new row number property refers to one record of CSV (which may span multiple physical lines) - this number begins at 1 and includes the header - - * line number refers to the physical line of CSV being read/written and begins at 1 (same as before). - - * CsvPreference is now immutable, and must be constructed using its internal builder (see the {{{./preferences.html}preferences}} page) - - * All classes with <<>> in their name have been renamed to <<>>. The new names are: - - * <<>> - - * <<>> - - * <<>> - - * Exceptions have been tidied up - - * <<>> and <<>> have been removed - (<<>> is now used when an unexpected type or null input is encountered in a cell processor). - - * <<>> has been updated. It no longer contains the offending processor, as there's a new exception (<<>>) for this. - - * <<>> has been added as a general exception for anything that goes wrong during cell processor execution. - - * <<>> has been added. - This exception is thrown when the processor can accept the input (it's of the expected type and not null), but it doesn't satisfy the constraint. - For example, if <<>> encounters a Long value, but it is outside the required range then a <<>> will be thrown. - If the <<>> processor encounters a decimal value (e.g. 1.5), then a general <<>> will be thrown. - - * Changes related to reading - - * The <<>> on all Readers has been renamed to <<>> (to match <<>> on Writers) - - * All Readers will now read empty columns (i.e. <<<"">>>) as <<>> (previously they would be read as <<<"">>>). - The <<>> processor has been updated to cater for this. - - * All Readers now implement <<>> - - * All Readers now have a <<>> method which returns the untokenized CSV row that was just read - - * All Readers now have a <<>> method which returns the number of the CSV row just read (essentially the number of records, including the header) - - * <<>> now returns a List of Objects (not Strings) when CellProcessors are used - - * <<>> read() methods no longer have wildcards in their return type - - * <<>> now allows any compatible setter method to be used - (e.g. if the value to map to the bean is a Double, then a setter that expects a Number will now work - - previously the setter would have to expect a Double as well). - - * Changes related to writing - - * All Writers will now write null columns as <<<"">>> (previously this would have caused an Exception). - - * All Writers now implement <<>> - - * All Writers now implement <<>> - so you can flush the stream without closing. - - * All Writers now have a <<>> method which returns the number of the CSV row just written (essentially the number of records, including the header) - - * Changes related to CellProcessors - - * The Optional processor now matches on <<>> instead of <<<"">>>. This means it can now be used for reading writing. - - * The <<>>, <<>>, and <<>> processors have been removed. - Instead, you should use <<>>, <<>>, and <<>> respectively. - - * The <<>> processor now trims whitespace (i.e. <<>>). The new <<>> processor contains the old Trim functionality. - - * The min/max constants in <<>> and <<>> have all been renamed, and extra constants added to distinguish between signed/unsigned 8-bit min/max values. - - * <<>> now uses <<>> instead of <<>>, so the regular expression must match the whole field - - * All processors have been updated to use the new exception classes <<>> and <<>> - -========================================================================================================= - -* 1.52 - - <09/2008> - - <> - - * Bug in CsvListWriter on null inputs - -========================================================================================================= - -* 1.51 - - <08/2008> - - <> - - * Improved processors. Extended auto boxing types to include boolean, float and double. - -========================================================================================================= - -* 1.50 - - <08/2008> - - <> - - * Improved processors. - - <> - - * Minor bug fixes - -========================================================================================================= - -* 1.50 Beta - - <06/2008> - - Added the following cell processors - - * <<>> - test if all values are equals alone, or equals to a given constant - - * <<>> - format as a string any Boolean value - - * <<>> - to map encountered values with other objects/values - - * <<>> - to ensure input value belongs to a specific set of given values - - * <<>> - to ensure non-null values for columns - - * <<>> - parse a string to get a big decimal - - * <<>> - to ensure non-null or empty values for columns - - * <<>> - for string manipulation - - * <<>> - for string manipulation - - Deprecated the following cell processors - - * <<>>, re-implemented as <<>> - - A new processor named <<>> (based on <<>>) has been created - the old definition based on hashCode() has been renamed to <<>>. - - BeanReader and BeanWriter now supports method overloading of get/set methods. - - Cell processors now only throw <<>> - - Added the following exceptions - - * ClassCastInputCSVException - - * NullInputException: this exception is raised now for unexpected 'null' input value for processor. - Numerous processors have been modified to use that exception class. - - Better handling of lines without the expected number of columns - - * The raised exception is now associated with a valid CSVContext object (previously, this object was 'null') - - Better error messages, more context information in the exception and available to the programmer - - Upgrade notes - - * Just copy over the .jar file and notice the deprecated classes... - -========================================================================================================= - -* 1.30 - - <01/2008> - - Improved integration and convenience - - * BeanReader now accepts interface types to read into. The reader will create an implementation on-the-fly of the interface and use this. - - * The ITokenizer interface has become public, making 3rd party extensions better integrated. - - * The exception class now contains the file context in which it was thrown. And generally, all places exceptions are - thrown have been cleaned up, streamlined and now passes the file context upon an exception. - - * An overloaded read() has been removed entirely - - * Added the following new cell processors: <<>> - - * A new exception <<>> replaces annoying Java checked exceptions - <<>> - - * More methods now use the var-args ("...") notation for easy use. - -========================================================================================================= - -* 1.20 - - <11/2007> - - Improved processors and partial writing - - * Added the ConvertNullTo cell processor which enables better support for writing partial objects, maps and lists. - - * Changed method signatures to use the var-args ("...") notation to make the programming more natural. This has been done for: - - * <<>> on all Writers - - * <<>>, <<>>, and <<>> - - * Small bugfix in processor StrLen - - * More documentation on the web - -========================================================================================================= - -* 1.15 - - <10/2007> - - Improved robustness and speed - - * Made the CSV Encoder more robust (used when writing CSV files) - - * Made the CSV encoder faster. Around 25% faster! - - * Added a lot of tests. - - * Set up an environment in dir slow_tests to enable future development to easily compare efficiency with older versions of the same functionality - -========================================================================================================= - -* 1.10 - - <10/2007> - - Faster and better - - * Introduced new cell processors <<>>, <<>>, <<>> - - * Made the tokenizer 5% faster (the thing that reads and interprets the CSV files)! Reading files has never been faster! - - * The framework now support plugging in new tokenizers onto readers. Feel free to author your own fast tokenizer - - * Improved the Javadoc for some processors - - * Added source branch specifically for tokenizer speed testing and comparison. It is now easy to experiment with various tokenizing strategies. - -========================================================================================================= - -* 1.02 - - <09/2007> - - Small bugfixes - - * Empty cells with value <<<"">>> was mistakenly interpreted as an escaped quoted char rather than the empty line - - * No longer removes trailing spaces inside quotes so <<<" hello ">>> is read as <<<" hello ">>> rather than <<<" hello">>> - - * Renamed the cell processor <<>> to <<>> - - * TABs are not regarded as whitespace anymore - -========================================================================================================= - -* 1.01 - - <09/2007> - - Small bugfixes - - * Inherited properties are now supported by the bean reader/writer - - * JAR file is now compiled for JDK 5. - -========================================================================================================= - -* 1.0 - - <09/2007> - - Initial release +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ------------- + Release notes + ------------- + +Release notes + +* 2.0.1 + + <12/2012> + + Just a small bug fix release to restore Java 5 compatibility (should also be more compatible with older versions of Android as well). + + <> + + * {{{https://sourceforge.net/p/supercsv/bugs/36/}36}} - CsvBeanReader allows a nameMapping array of the wrong size when processors aren't used + + * {{{https://sourceforge.net/p/supercsv/bugs/37/}37}} - Restore Java 5 compatibility + +* 2.0.0 + + <11/2012> + + This is the final release of version 2.0.0, which fixes a few minor bugs found in version 2.0.0-beta-1. + Please refer to the 2.0.0-beta-1 release notes below for a full list of new features, bug fixes and upgrade notes. + + + <> + + * {{{https://sourceforge.net/p/supercsv/bugs/33/}33}} - Added missing WEDNESDAY enum literal to custom cell processor example + + * {{{https://sourceforge.net/p/supercsv/bugs/34/}34}} - Added SLF4J API jar to distribution zip file + + * {{{https://sourceforge.net/p/supercsv/bugs/35/}35}} - CsvListReader now returns a new List for each <<>> operation + +* 2.0.0-beta-1 + + <09/2012> + + <> + + * 100% {{{http://tools.ietf.org/html/rfc4180}RFC 4180}} compliance + + * {{{https://sourceforge.net/p/supercsv/feature-requests/3/}3}} - Super CSV now supports mapping nested properties (deep mapping and index-based mapping) + with the new CsvDozerBeanReader and CsvDozerBeanWriter (included in the super-csv-dozer-extension project). + + * {{{https://sourceforge.net/p/supercsv/feature-requests/12/}12}} - CsvBeanReader now supports any compatible setter method (as long as the parameter type - interface or object - is compatible with the object being set). + Previously, the parameter type had to be an exact match on the object's type. + + * {{{https://sourceforge.net/p/supercsv/feature-requests/17/}17}} - All Writers implement <<>> + + * {{{https://sourceforge.net/p/supercsv/feature-requests/18/}18}} - OSGi support + + * {{{https://sourceforge.net/p/supercsv/feature-requests/19/}19}} - All Readers and Writers now implement <<>> + + * {{{https://sourceforge.net/p/supercsv/feature-requests/20/}20}} - Maven support (see details on the {{{./downloading.html}download}} page) + + * {{{https://sourceforge.net/p/supercsv/feature-requests/21/}21}} - All Readers now have a <<>> method for retrieving the raw String of the row just + read (before it's been tokenized). + All Readers and Writers now have a <<>> method for getting the number of CSV rows read/written (including the header). + This is different from <<>>, which returns the physical line number, as rows may span more than one line (the CSV + format allows for multiline fields, as long as they're within double-quotes). + + <> + + * {{{https://sourceforge.net/p/supercsv/bugs/12/}12}} - Fixed NPE in CsvBeanReader when value to set is null + + * {{{https://sourceforge.net/p/supercsv/bugs/14/}14}} - AbstractCsvWriter now escapes for trailing spaces + + * {{{https://sourceforge.net/p/supercsv/bugs/16/}16}} - Refactored Readers/Writers so it's no longer possible to modify preferences + + * {{{https://sourceforge.net/p/supercsv/bugs/19/}19}} - Fixed NPE in SuperCsvException constructor + + * {{{https://sourceforge.net/p/supercsv/bugs/21/}21}} - New <<>> preference allows the disabling of quoting for leading spaces + + * {{{https://sourceforge.net/p/supercsv/bugs/23/}23}} - CsvListWriter now allows all cell processors (not just String processors) + + * {{{https://sourceforge.net/p/supercsv/bugs/29/}29}} - Column numbers now start at 1 (instead of 0) + + * {{{https://sourceforge.net/p/supercsv/bugs/30/}30}} - All writers now allow null in the nameMapping array (except CsvDozerBeanWriter) + + <> + + * Complete overhaul of javadoc + + * Improved test coverage (now 100%!) + + * More defensive programming (à la Josh Bloch's ). + It's a lot harder to do silly stuff with the API now - for example CellProcessors will fail fast during construction if not set up correctly, instead of during execution. + + * A new and improved maven site (please like/+1 us!) + + * Removed dependency on the Spiffy library - Super CSV (excluding the new Dozer extension) is now completely standalone! + + <> + + As this is a major release and it's been 4 years since the last release, there have been numerous changes that are not backwards-compatible with older versions. + Here's an overview of things to be aware of when upgrading from version 1.52: + + * General changes + + * The treatment of spaces surrounding a cell has changed + + * All spaces are now considered important (to conform to RFC 4180), and surrounding spaces won't be trimmed by default + + * A new preference has been added to enable/disable this functionality (see the section on <<>> on the {{{./preferences.html}preferences}} page). + + * Line number, row number (a new property of both readers and writers) and column number all start from 1. This means: + + * the <<>> method of all Readers now expects the column number to begin at 1 (it was previously 0) + + * the column number reported in Exceptions (via the CsvContext object) begins at 1 + + * the new row number property refers to one record of CSV (which may span multiple physical lines) - this number begins at 1 and includes the header + + * line number refers to the physical line of CSV being read/written and begins at 1 (same as before). + + * CsvPreference is now immutable, and must be constructed using its internal builder (see the {{{./preferences.html}preferences}} page) + + * All classes with <<>> in their name have been renamed to <<>>. The new names are: + + * <<>> + + * <<>> + + * <<>> + + * Exceptions have been tidied up + + * <<>> and <<>> have been removed + (<<>> is now used when an unexpected type or null input is encountered in a cell processor). + + * <<>> has been updated. It no longer contains the offending processor, as there's a new exception (<<>>) for this. + + * <<>> has been added as a general exception for anything that goes wrong during cell processor execution. + + * <<>> has been added. + This exception is thrown when the processor can accept the input (it's of the expected type and not null), but it doesn't satisfy the constraint. + For example, if <<>> encounters a Long value, but it is outside the required range then a <<>> will be thrown. + If the <<>> processor encounters a decimal value (e.g. 1.5), then a general <<>> will be thrown. + + * Changes related to reading + + * The <<>> on all Readers has been renamed to <<>> (to match <<>> on Writers) + + * All Readers will now read empty columns (i.e. <<<"">>>) as <<>> (previously they would be read as <<<"">>>). + The <<>> processor has been updated to cater for this. + + * All Readers now implement <<>> + + * All Readers now have a <<>> method which returns the untokenized CSV row that was just read + + * All Readers now have a <<>> method which returns the number of the CSV row just read (essentially the number of records, including the header) + + * <<>> now returns a List of Objects (not Strings) when CellProcessors are used + + * <<>> read() methods no longer have wildcards in their return type + + * <<>> now allows any compatible setter method to be used + (e.g. if the value to map to the bean is a Double, then a setter that expects a Number will now work - + previously the setter would have to expect a Double as well). + + * Changes related to writing + + * All Writers will now write null columns as <<<"">>> (previously this would have caused an Exception). + + * All Writers now implement <<>> + + * All Writers now implement <<>> - so you can flush the stream without closing. + + * All Writers now have a <<>> method which returns the number of the CSV row just written (essentially the number of records, including the header) + + * Changes related to CellProcessors + + * The Optional processor now matches on <<>> instead of <<<"">>>. This means it can now be used for reading writing. + + * The <<>>, <<>>, and <<>> processors have been removed. + Instead, you should use <<>>, <<>>, and <<>> respectively. + + * The <<>> processor now trims whitespace (i.e. <<>>). The new <<>> processor contains the old Trim functionality. + + * The min/max constants in <<>> and <<>> have all been renamed, and extra constants added to distinguish between signed/unsigned 8-bit min/max values. + + * <<>> now uses <<>> instead of <<>>, so the regular expression must match the whole field + + * All processors have been updated to use the new exception classes <<>> and <<>> + +========================================================================================================= + +* 1.52 + + <09/2008> + + <> + + * Bug in CsvListWriter on null inputs + +========================================================================================================= + +* 1.51 + + <08/2008> + + <> + + * Improved processors. Extended auto boxing types to include boolean, float and double. + +========================================================================================================= + +* 1.50 + + <08/2008> + + <> + + * Improved processors. + + <> + + * Minor bug fixes + +========================================================================================================= + +* 1.50 Beta + + <06/2008> + + Added the following cell processors + + * <<>> - test if all values are equals alone, or equals to a given constant + + * <<>> - format as a string any Boolean value + + * <<>> - to map encountered values with other objects/values + + * <<>> - to ensure input value belongs to a specific set of given values + + * <<>> - to ensure non-null values for columns + + * <<>> - parse a string to get a big decimal + + * <<>> - to ensure non-null or empty values for columns + + * <<>> - for string manipulation + + * <<>> - for string manipulation + + Deprecated the following cell processors + + * <<>>, re-implemented as <<>> + + A new processor named <<>> (based on <<>>) has been created - the old definition based on hashCode() has been renamed to <<>>. + + BeanReader and BeanWriter now supports method overloading of get/set methods. + + Cell processors now only throw <<>> + + Added the following exceptions + + * ClassCastInputCSVException + + * NullInputException: this exception is raised now for unexpected 'null' input value for processor. + Numerous processors have been modified to use that exception class. + + Better handling of lines without the expected number of columns + + * The raised exception is now associated with a valid CSVContext object (previously, this object was 'null') + + Better error messages, more context information in the exception and available to the programmer + + Upgrade notes + + * Just copy over the .jar file and notice the deprecated classes... + +========================================================================================================= + +* 1.30 + + <01/2008> + + Improved integration and convenience + + * BeanReader now accepts interface types to read into. The reader will create an implementation on-the-fly of the interface and use this. + + * The ITokenizer interface has become public, making 3rd party extensions better integrated. + + * The exception class now contains the file context in which it was thrown. And generally, all places exceptions are + thrown have been cleaned up, streamlined and now passes the file context upon an exception. + + * An overloaded read() has been removed entirely + + * Added the following new cell processors: <<>> + + * A new exception <<>> replaces annoying Java checked exceptions + <<>> + + * More methods now use the var-args ("...") notation for easy use. + +========================================================================================================= + +* 1.20 + + <11/2007> + + Improved processors and partial writing + + * Added the ConvertNullTo cell processor which enables better support for writing partial objects, maps and lists. + + * Changed method signatures to use the var-args ("...") notation to make the programming more natural. This has been done for: + + * <<>> on all Writers + + * <<>>, <<>>, and <<>> + + * Small bugfix in processor StrLen + + * More documentation on the web + +========================================================================================================= + +* 1.15 + + <10/2007> + + Improved robustness and speed + + * Made the CSV Encoder more robust (used when writing CSV files) + + * Made the CSV encoder faster. Around 25% faster! + + * Added a lot of tests. + + * Set up an environment in dir slow_tests to enable future development to easily compare efficiency with older versions of the same functionality + +========================================================================================================= + +* 1.10 + + <10/2007> + + Faster and better + + * Introduced new cell processors <<>>, <<>>, <<>> + + * Made the tokenizer 5% faster (the thing that reads and interprets the CSV files)! Reading files has never been faster! + + * The framework now support plugging in new tokenizers onto readers. Feel free to author your own fast tokenizer + + * Improved the Javadoc for some processors + + * Added source branch specifically for tokenizer speed testing and comparison. It is now easy to experiment with various tokenizing strategies. + +========================================================================================================= + +* 1.02 + + <09/2007> + + Small bugfixes + + * Empty cells with value <<<"">>> was mistakenly interpreted as an escaped quoted char rather than the empty line + + * No longer removes trailing spaces inside quotes so <<<" hello ">>> is read as <<<" hello ">>> rather than <<<" hello">>> + + * Renamed the cell processor <<>> to <<>> + + * TABs are not regarded as whitespace anymore + +========================================================================================================= + +* 1.01 + + <09/2007> + + Small bugfixes + + * Inherited properties are now supported by the bean reader/writer + + * JAR file is now compiled for JDK 5. + +========================================================================================================= + +* 1.0 + + <09/2007> + + Initial release diff --git a/src/site/apt/roadmap.apt b/src/site/apt/roadmap.apt index 12cb6ab8..d0f43e5b 100644 --- a/src/site/apt/roadmap.apt +++ b/src/site/apt/roadmap.apt @@ -1,42 +1,42 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -------- - Road map - -------- - -Road map - -* 2.1.0 - - <01/2013> - - * Upgrade to Dozer 5.4.0 - - * Better support for delaying errors (for batch reading/writing) - - * Resurrect the speed benchmark tests (including the new Dozer reader/writer) - -* Other possible ideas for the future - - There's nothing else definitively planned for future releases at this stage, so please let us know if you have any {{{https://sourceforge.net/p/supercsv/feature-requests/}feature requests}}. - - Possible features include: - - * Comment character support (ignoring comments) - - * Internationalization of error messages - - * End world hunger and make dolphins speak +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + -------- + Road map + -------- + +Road map + +* 2.1.0 + + <01/2013> + + * Upgrade to Dozer 5.4.0 + + * Better support for delaying errors (for batch reading/writing) + + * Resurrect the speed benchmark tests (including the new Dozer reader/writer) + +* Other possible ideas for the future + + There's nothing else definitively planned for future releases at this stage, so please let us know if you have any {{{https://sourceforge.net/p/supercsv/feature-requests/}feature requests}}. + + Possible features include: + + * Comment character support (ignoring comments) + + * Internationalization of error messages + + * End world hunger and make dolphins speak diff --git a/src/site/apt/writers.apt b/src/site/apt/writers.apt index bf3fedb6..9041c25d 100644 --- a/src/site/apt/writers.apt +++ b/src/site/apt/writers.apt @@ -1,36 +1,36 @@ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -~~ Copyright 2007 Kasper B. Graversen -~~ -~~ 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. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ----------- - CSV Writers - ----------- - -CSV Writers - - There are four CSV writing implementations in Super CSV. - -*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* - || {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}} || {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanWriter.html} CsvDozerBeanWriter}} || {{{./apidocs/org/supercsv/io/CsvListWriter.html}CsvListWriter}} || {{{./apidocs/org/supercsv/io/CsvMapWriter.html}CsvMapWriter}} -*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* - Writes each row of CSV from a | POJO (must be a valid Javabean) | POJO (must be a valid Javabean) | List\ or List\ | Map\ or Map\ -*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* - Supports {{{./dozer.html}deep mapping and index-based mapping}}? | No | Yes | No | No -*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* - Supports {{{./examples_partial_writing.html}partial writing}} (default values)? | Yes | Yes | Yes | Yes -*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* - - Which one you choose will depend on your requirements, but we recommend using CsvBeanWriter or CsvDozerBeanWriter - where possible, as it's far easier to work with POJOs than Lists or Maps. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~ Copyright 2007 Kasper B. Graversen +~~ +~~ 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. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ----------- + CSV Writers + ----------- + +CSV Writers + + There are four CSV writing implementations in Super CSV. + +*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* + || {{{./apidocs/org/supercsv/io/CsvBeanWriter.html}CsvBeanWriter}} || {{{./apidocs/org/supercsv/io/dozer/CsvDozerBeanWriter.html} CsvDozerBeanWriter}} || {{{./apidocs/org/supercsv/io/CsvListWriter.html}CsvListWriter}} || {{{./apidocs/org/supercsv/io/CsvMapWriter.html}CsvMapWriter}} +*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* + Writes each row of CSV from a | POJO (must be a valid Javabean) | POJO (must be a valid Javabean) | List\ or List\ | Map\ or Map\ +*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* + Supports {{{./dozer.html}deep mapping and index-based mapping}}? | No | Yes | No | No +*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* + Supports {{{./examples_partial_writing.html}partial writing}} (default values)? | Yes | Yes | Yes | Yes +*----------------------------------------------------------------------------------*-------------------------------------------------------------------*-----------------------------------------------------------------------------------*------------------------------------------------------------------*-----------------------------------------------------------------* + + Which one you choose will depend on your requirements, but we recommend using CsvBeanWriter or CsvDozerBeanWriter + where possible, as it's far easier to work with POJOs than Lists or Maps. Check out the {{{./examples_writing.html}writing examples}} to see them in action. \ No newline at end of file diff --git a/src/site/site.xml b/src/site/site.xml index c4f0cd2e..d0b30f00 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -1,73 +1,73 @@ - - - - org.apache.maven.skins - maven-fluido-skin - 1.3.0 - - - - false - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + org.apache.maven.skins + maven-fluido-skin + 1.3.0 + + + + false + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/super-csv-distribution/.project b/super-csv-distribution/.project index 66f1e7ed..9decd2ca 100644 --- a/super-csv-distribution/.project +++ b/super-csv-distribution/.project @@ -1,11 +1,11 @@ - - - super-csv-distribution - - - - - - - - + + + super-csv-distribution + + + + + + + + diff --git a/super-csv-distribution/pom.xml b/super-csv-distribution/pom.xml index 42886728..060c8672 100644 --- a/super-csv-distribution/pom.xml +++ b/super-csv-distribution/pom.xml @@ -1,70 +1,70 @@ - - - - 4.0.0 - - - net.sf.supercsv - super-csv-parent - 2.0.2-SNAPSHOT - - - net.sf.supercsv - super-csv-distribution - pom - Super CSV Distribution - Creates the Super CSV distribution for SourceForge - - - - net.sf.supercsv - super-csv - zip - bin - ${project.version} - - - net.sf.supercsv - super-csv-dozer - zip - jar-with-dependencies - ${project.version} - - - - - - - maven-assembly-plugin - - - create-assembly - package - - single - - - - src/assembly/assembly.xml - - - - - - - + + + + 4.0.0 + + + net.sf.supercsv + super-csv-parent + 2.0.2-SNAPSHOT + + + net.sf.supercsv + super-csv-distribution + pom + Super CSV Distribution + Creates the Super CSV distribution for SourceForge + + + + net.sf.supercsv + super-csv + zip + bin + ${project.version} + + + net.sf.supercsv + super-csv-dozer + zip + jar-with-dependencies + ${project.version} + + + + + + + maven-assembly-plugin + + + create-assembly + package + + single + + + + src/assembly/assembly.xml + + + + + + + \ No newline at end of file diff --git a/super-csv-distribution/src/assembly/assembly.xml b/super-csv-distribution/src/assembly/assembly.xml index 38c99ef4..befd654b 100644 --- a/super-csv-distribution/src/assembly/assembly.xml +++ b/super-csv-distribution/src/assembly/assembly.xml @@ -1,38 +1,38 @@ - - - bin - - zip - - false - - - - ../LICENSE.txt - / - - - - - - - net.sf.supercsv:super-csv - - super-csv - false - true - - - - - net.sf.supercsv:super-csv-dozer - - super-csv-dozer - false - true - - + + + bin + + zip + + false + + + + ../LICENSE.txt + / + + + + + + + net.sf.supercsv:super-csv + + super-csv + false + true + + + + + net.sf.supercsv:super-csv-dozer + + super-csv-dozer + false + true + + \ No newline at end of file diff --git a/super-csv-dozer/.classpath b/super-csv-dozer/.classpath index 35e9fd19..cda0dbf5 100644 --- a/super-csv-dozer/.classpath +++ b/super-csv-dozer/.classpath @@ -1,50 +1,50 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/super-csv-dozer/.project b/super-csv-dozer/.project index 7e5753cf..7044b74d 100644 --- a/super-csv-dozer/.project +++ b/super-csv-dozer/.project @@ -1,16 +1,16 @@ - - - super-csv-dozer - An extension for Super CSV that uses Dozer for reading/writing between CSV and POJOs. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. - - super-csv - - - - org.eclipse.jdt.core.javabuilder - - - - org.eclipse.jdt.core.javanature - + + + super-csv-dozer + An extension for Super CSV that uses Dozer for reading/writing between CSV and POJOs. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. + + super-csv + + + + org.eclipse.jdt.core.javabuilder + + + + org.eclipse.jdt.core.javanature + \ No newline at end of file diff --git a/super-csv-dozer/.settings/org.eclipse.jdt.core.prefs b/super-csv-dozer/.settings/org.eclipse.jdt.core.prefs index cc922b5f..d6822743 100644 --- a/super-csv-dozer/.settings/org.eclipse.jdt.core.prefs +++ b/super-csv-dozer/.settings/org.eclipse.jdt.core.prefs @@ -1,285 +1,285 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.5 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=66 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=20 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=true -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true -org.eclipse.jdt.core.formatter.comment.format_block_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=true -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert -org.eclipse.jdt.core.formatter.comment.line_length=120 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=1 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=true -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=true -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=120 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=false -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=66 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=20 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=true +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=120 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=1 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=true +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=120 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/super-csv-dozer/.settings/org.eclipse.jdt.ui.prefs b/super-csv-dozer/.settings/org.eclipse.jdt.ui.prefs index c0fbbf9e..acc8dfe2 100644 --- a/super-csv-dozer/.settings/org.eclipse.jdt.ui.prefs +++ b/super-csv-dozer/.settings/org.eclipse.jdt.ui.prefs @@ -1,3 +1,3 @@ -eclipse.preferences.version=1 -formatter_profile=_supercsv -formatter_settings_version=12 +eclipse.preferences.version=1 +formatter_profile=_supercsv +formatter_settings_version=12 diff --git a/super-csv-dozer/.settings/org.eclipse.m2e.core.prefs b/super-csv-dozer/.settings/org.eclipse.m2e.core.prefs index 14b697b7..f897a7f1 100644 --- a/super-csv-dozer/.settings/org.eclipse.m2e.core.prefs +++ b/super-csv-dozer/.settings/org.eclipse.m2e.core.prefs @@ -1,4 +1,4 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/super-csv-dozer/pom.xml b/super-csv-dozer/pom.xml index 99e99364..113c6f8a 100644 --- a/super-csv-dozer/pom.xml +++ b/super-csv-dozer/pom.xml @@ -1,81 +1,81 @@ - - - - - 4.0.0 - - - net.sf.supercsv - super-csv-parent - 2.0.2-SNAPSHOT - - - super-csv-dozer - Super CSV Dozer Extension - An extension for Super CSV that uses Dozer for reading/writing between CSV and POJOs - jar - - - 5.3.2 - 1.7.1 - - - - - - maven-assembly-plugin - - - create-assembly - package - - single - - - - src/assembly/assembly.xml - - - - - - - - - - - net.sf.supercsv - super-csv - - - net.sf.dozer - dozer - ${dozer.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - ch.qos.logback - logback-classic - 1.0.7 - test - - + + + + + 4.0.0 + + + net.sf.supercsv + super-csv-parent + 2.0.2-SNAPSHOT + + + super-csv-dozer + Super CSV Dozer Extension + An extension for Super CSV that uses Dozer for reading/writing between CSV and POJOs + jar + + + 5.3.2 + 1.7.1 + + + + + + maven-assembly-plugin + + + create-assembly + package + + single + + + + src/assembly/assembly.xml + + + + + + + + + + + net.sf.supercsv + super-csv + + + net.sf.dozer + dozer + ${dozer.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + ch.qos.logback + logback-classic + 1.0.7 + test + + \ No newline at end of file diff --git a/super-csv-dozer/src/assembly/assembly.xml b/super-csv-dozer/src/assembly/assembly.xml index 799c9a67..18a79c37 100644 --- a/super-csv-dozer/src/assembly/assembly.xml +++ b/super-csv-dozer/src/assembly/assembly.xml @@ -1,30 +1,30 @@ - - - jar-with-dependencies - - zip - - false - - - - ${project.build.directory} - / - - *.jar - - - - - - - lib - false - false - runtime - - + + + jar-with-dependencies + + zip + + false + + + + ${project.build.directory} + / + + *.jar + + + + + + + lib + false + false + runtime + + \ No newline at end of file diff --git a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanData.java b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanData.java index 98e43a17..38bcd732 100644 --- a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanData.java +++ b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanData.java @@ -1,52 +1,52 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io.dozer; - -import java.util.ArrayList; -import java.util.List; - -/** - * Class used internally by CsvDozerBeanReader and CsvDozerBeanWriter for Dozer mapping between CSV columns and beans. As Dozer - * supports index-based mapping, the Reader/Writer's DozerBeanMapper just needs to be configured with the mappings - * between the column index and the associated field in the bean. - * - * @author James Bassett - * @since 2.0.0 - */ -public class CsvDozerBeanData { - - private List columns = new ArrayList(); - - /** - * Gets the List of columns - * - * @return the List of columns - */ - public List getColumns() { - return columns; - } - - /** - * Sets the List of columns - * - * @param columns - * the List of columns - */ - public void setColumns(final List columns) { - this.columns = columns; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io.dozer; + +import java.util.ArrayList; +import java.util.List; + +/** + * Class used internally by CsvDozerBeanReader and CsvDozerBeanWriter for Dozer mapping between CSV columns and beans. As Dozer + * supports index-based mapping, the Reader/Writer's DozerBeanMapper just needs to be configured with the mappings + * between the column index and the associated field in the bean. + * + * @author James Bassett + * @since 2.0.0 + */ +public class CsvDozerBeanData { + + private List columns = new ArrayList(); + + /** + * Gets the List of columns + * + * @return the List of columns + */ + public List getColumns() { + return columns; + } + + /** + * Sets the List of columns + * + * @param columns + * the List of columns + */ + public void setColumns(final List columns) { + this.columns = columns; + } + +} diff --git a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanReader.java b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanReader.java index e78f50dd..a82e0e45 100644 --- a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanReader.java +++ b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanReader.java @@ -1,223 +1,223 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io.dozer; - -import static org.dozer.loader.api.TypeMappingOptions.mapNull; -import static org.dozer.loader.api.TypeMappingOptions.oneWay; -import static org.dozer.loader.api.TypeMappingOptions.wildcard; - -import java.io.IOException; -import java.io.Reader; - -import org.dozer.DozerBeanMapper; -import org.dozer.loader.api.BeanMappingBuilder; -import org.dozer.loader.api.TypeMappingBuilder; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.io.AbstractCsvReader; -import org.supercsv.io.CsvBeanReader; -import org.supercsv.io.ITokenizer; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * CsvDozerBeanReader is a powerful replacement for {@link CsvBeanReader} that uses Dozer to map from CSV to a bean. - * - * @author James Bassett - * @since 2.0.0 - */ -public class CsvDozerBeanReader extends AbstractCsvReader implements ICsvDozerBeanReader { - - private final DozerBeanMapper dozerBeanMapper; - - // source of dozer bean mapping - private final CsvDozerBeanData beanData = new CsvDozerBeanData(); - - /** - * Constructs a new CsvDozerBeanReader with the supplied Reader and CSV preferences and creates it's own - * DozerBeanMapper. Note that the reader will be wrapped in a BufferedReader before accessed. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if reader or preferences are null - */ - public CsvDozerBeanReader(final Reader reader, final CsvPreference preferences) { - super(reader, preferences); - this.dozerBeanMapper = new DozerBeanMapper(); - } - - /** - * Constructs a new CsvDozerBeanReader with the supplied (custom) Tokenizer and CSV preferences and creates - * it's own DozerBeanMapper. The tokenizer should be set up with the Reader (CSV input) and CsvPreference - * beforehand. - * - * @param tokenizer - * the tokenizer - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if tokenizer or preferences are null - */ - public CsvDozerBeanReader(final ITokenizer tokenizer, final CsvPreference preferences) { - super(tokenizer, preferences); - this.dozerBeanMapper = new DozerBeanMapper(); - } - - /** - * Constructs a new CsvDozerBeanReader with the supplied Reader, CSV preferences and DozerBeanMapper. Note - * that the reader will be wrapped in a BufferedReader before accessed. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @param dozerBeanMapper - * the dozer bean mapper to use - * @throws NullPointerException - * if reader, preferences or dozerBeanMapper are null - */ - public CsvDozerBeanReader(final Reader reader, final CsvPreference preferences, - final DozerBeanMapper dozerBeanMapper) { - super(reader, preferences); - if( dozerBeanMapper == null ) { - throw new NullPointerException("dozerBeanMapper should not be null"); - } - this.dozerBeanMapper = dozerBeanMapper; - } - - /** - * Constructs a new CsvDozerBeanReader with the supplied (custom) Tokenizer, CSV preferences and - * DozerBeanMapper. The tokenizer should be set up with the Reader (CSV input) and CsvPreference beforehand. - * - * @param tokenizer - * the tokenizer - * @param preferences - * the CSV preferences - * @param dozerBeanMapper - * the dozer bean mapper to use - * @throws NullPointerException - * if tokenizer, preferences or dozerBeanMapper are null - */ - public CsvDozerBeanReader(final ITokenizer tokenizer, final CsvPreference preferences, - final DozerBeanMapper dozerBeanMapper) { - super(tokenizer, preferences); - if( dozerBeanMapper == null ) { - throw new NullPointerException("dozerBeanMapper should not be null"); - } - this.dozerBeanMapper = dozerBeanMapper; - } - - /** - * {@inheritDoc} - */ - public void configureBeanMapping(final Class clazz, final String[] fieldMapping) { - dozerBeanMapper.addMapping(new MappingBuilder(clazz, fieldMapping)); - } - - /** - * {@inheritDoc} - */ - public T read(final Class clazz) throws IOException { - if( clazz == null ) { - throw new NullPointerException("clazz should not be null"); - } - - if( readRow() ) { - // call dozer to map the read columns to the bean - beanData.getColumns().clear(); - beanData.getColumns().addAll(getColumns()); - return dozerBeanMapper.map(beanData, clazz); - } - - return null; // EOF - } - - /** - * {@inheritDoc} - */ - public T read(final Class clazz, final CellProcessor... processors) throws IOException { - if( clazz == null ) { - throw new NullPointerException("clazz should not be null"); - } else if( processors == null ) { - throw new NullPointerException("processors should not be null"); - } - - if( readRow() ) { - // execute the processors then call dozer to populate the bean - Util.executeCellProcessors(beanData.getColumns(), getColumns(), processors, getLineNumber(), getRowNumber()); - return dozerBeanMapper.map(beanData, clazz); - } - - return null; // EOF - } - - /** - * Assembles the dozer bean mappings required by CsvDozerBeanReader programatically using the Dozer API. - */ - private static class MappingBuilder extends BeanMappingBuilder { - - private final Class clazz; - private final String[] fieldMapping; - - /** - * Constructs a new MappingBuilder. - * - * @param clazz - * the class to add mapping configuration for (same as the type passed into write methods) - * @param fieldMapping - * the field mapping for for each column (may contain null elements to indicate ignored - * columns) - * @throws NullPointerException - * if clazz or fieldMapping is null - */ - public MappingBuilder(final Class clazz, final String[] fieldMapping) { - if( clazz == null ) { - throw new NullPointerException("clazz should not be null"); - } else if( fieldMapping == null ) { - throw new NullPointerException("fieldMapping should not be null"); - } - this.clazz = clazz; - this.fieldMapping = fieldMapping; - } - - @Override - protected void configure() { - - /* - * Add the required dozer mappings to map from each column (in the CsvDozerBeanData List) to its associated - * field in the supplied class. mapNull is disabled so that null field values are ignored. oneWay is enabled - * just in case a custom DozerBeanMapper is supplied (so the same DozerBeanMapper can be used by - * CsvDozerBeanWriter). wildcard is disabled to prevent Dozer from trying to map things automatically. - */ - final TypeMappingBuilder mappingBuilder = mapping(CsvDozerBeanData.class, clazz, oneWay(), wildcard(false), - mapNull(false)); - - for( int i = 0; i < fieldMapping.length; i++ ) { - - final String mapping = fieldMapping[i]; - - if( mapping == null ) { - continue; // no field mappings required (column will be ignored) - } - - mappingBuilder.fields("columns[" + i + "]", mapping); - } - } - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io.dozer; + +import static org.dozer.loader.api.TypeMappingOptions.mapNull; +import static org.dozer.loader.api.TypeMappingOptions.oneWay; +import static org.dozer.loader.api.TypeMappingOptions.wildcard; + +import java.io.IOException; +import java.io.Reader; + +import org.dozer.DozerBeanMapper; +import org.dozer.loader.api.BeanMappingBuilder; +import org.dozer.loader.api.TypeMappingBuilder; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.io.AbstractCsvReader; +import org.supercsv.io.CsvBeanReader; +import org.supercsv.io.ITokenizer; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * CsvDozerBeanReader is a powerful replacement for {@link CsvBeanReader} that uses Dozer to map from CSV to a bean. + * + * @author James Bassett + * @since 2.0.0 + */ +public class CsvDozerBeanReader extends AbstractCsvReader implements ICsvDozerBeanReader { + + private final DozerBeanMapper dozerBeanMapper; + + // source of dozer bean mapping + private final CsvDozerBeanData beanData = new CsvDozerBeanData(); + + /** + * Constructs a new CsvDozerBeanReader with the supplied Reader and CSV preferences and creates it's own + * DozerBeanMapper. Note that the reader will be wrapped in a BufferedReader before accessed. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if reader or preferences are null + */ + public CsvDozerBeanReader(final Reader reader, final CsvPreference preferences) { + super(reader, preferences); + this.dozerBeanMapper = new DozerBeanMapper(); + } + + /** + * Constructs a new CsvDozerBeanReader with the supplied (custom) Tokenizer and CSV preferences and creates + * it's own DozerBeanMapper. The tokenizer should be set up with the Reader (CSV input) and CsvPreference + * beforehand. + * + * @param tokenizer + * the tokenizer + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if tokenizer or preferences are null + */ + public CsvDozerBeanReader(final ITokenizer tokenizer, final CsvPreference preferences) { + super(tokenizer, preferences); + this.dozerBeanMapper = new DozerBeanMapper(); + } + + /** + * Constructs a new CsvDozerBeanReader with the supplied Reader, CSV preferences and DozerBeanMapper. Note + * that the reader will be wrapped in a BufferedReader before accessed. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @param dozerBeanMapper + * the dozer bean mapper to use + * @throws NullPointerException + * if reader, preferences or dozerBeanMapper are null + */ + public CsvDozerBeanReader(final Reader reader, final CsvPreference preferences, + final DozerBeanMapper dozerBeanMapper) { + super(reader, preferences); + if( dozerBeanMapper == null ) { + throw new NullPointerException("dozerBeanMapper should not be null"); + } + this.dozerBeanMapper = dozerBeanMapper; + } + + /** + * Constructs a new CsvDozerBeanReader with the supplied (custom) Tokenizer, CSV preferences and + * DozerBeanMapper. The tokenizer should be set up with the Reader (CSV input) and CsvPreference beforehand. + * + * @param tokenizer + * the tokenizer + * @param preferences + * the CSV preferences + * @param dozerBeanMapper + * the dozer bean mapper to use + * @throws NullPointerException + * if tokenizer, preferences or dozerBeanMapper are null + */ + public CsvDozerBeanReader(final ITokenizer tokenizer, final CsvPreference preferences, + final DozerBeanMapper dozerBeanMapper) { + super(tokenizer, preferences); + if( dozerBeanMapper == null ) { + throw new NullPointerException("dozerBeanMapper should not be null"); + } + this.dozerBeanMapper = dozerBeanMapper; + } + + /** + * {@inheritDoc} + */ + public void configureBeanMapping(final Class clazz, final String[] fieldMapping) { + dozerBeanMapper.addMapping(new MappingBuilder(clazz, fieldMapping)); + } + + /** + * {@inheritDoc} + */ + public T read(final Class clazz) throws IOException { + if( clazz == null ) { + throw new NullPointerException("clazz should not be null"); + } + + if( readRow() ) { + // call dozer to map the read columns to the bean + beanData.getColumns().clear(); + beanData.getColumns().addAll(getColumns()); + return dozerBeanMapper.map(beanData, clazz); + } + + return null; // EOF + } + + /** + * {@inheritDoc} + */ + public T read(final Class clazz, final CellProcessor... processors) throws IOException { + if( clazz == null ) { + throw new NullPointerException("clazz should not be null"); + } else if( processors == null ) { + throw new NullPointerException("processors should not be null"); + } + + if( readRow() ) { + // execute the processors then call dozer to populate the bean + Util.executeCellProcessors(beanData.getColumns(), getColumns(), processors, getLineNumber(), getRowNumber()); + return dozerBeanMapper.map(beanData, clazz); + } + + return null; // EOF + } + + /** + * Assembles the dozer bean mappings required by CsvDozerBeanReader programatically using the Dozer API. + */ + private static class MappingBuilder extends BeanMappingBuilder { + + private final Class clazz; + private final String[] fieldMapping; + + /** + * Constructs a new MappingBuilder. + * + * @param clazz + * the class to add mapping configuration for (same as the type passed into write methods) + * @param fieldMapping + * the field mapping for for each column (may contain null elements to indicate ignored + * columns) + * @throws NullPointerException + * if clazz or fieldMapping is null + */ + public MappingBuilder(final Class clazz, final String[] fieldMapping) { + if( clazz == null ) { + throw new NullPointerException("clazz should not be null"); + } else if( fieldMapping == null ) { + throw new NullPointerException("fieldMapping should not be null"); + } + this.clazz = clazz; + this.fieldMapping = fieldMapping; + } + + @Override + protected void configure() { + + /* + * Add the required dozer mappings to map from each column (in the CsvDozerBeanData List) to its associated + * field in the supplied class. mapNull is disabled so that null field values are ignored. oneWay is enabled + * just in case a custom DozerBeanMapper is supplied (so the same DozerBeanMapper can be used by + * CsvDozerBeanWriter). wildcard is disabled to prevent Dozer from trying to map things automatically. + */ + final TypeMappingBuilder mappingBuilder = mapping(CsvDozerBeanData.class, clazz, oneWay(), wildcard(false), + mapNull(false)); + + for( int i = 0; i < fieldMapping.length; i++ ) { + + final String mapping = fieldMapping[i]; + + if( mapping == null ) { + continue; // no field mappings required (column will be ignored) + } + + mappingBuilder.fields("columns[" + i + "]", mapping); + } + } + } + +} diff --git a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanWriter.java b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanWriter.java index f6108a1e..0dab08ca 100644 --- a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanWriter.java +++ b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanWriter.java @@ -1,195 +1,195 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io.dozer; - -import static org.dozer.loader.api.TypeMappingOptions.oneWay; -import static org.dozer.loader.api.TypeMappingOptions.wildcard; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; - -import org.dozer.DozerBeanMapper; -import org.dozer.loader.api.BeanMappingBuilder; -import org.dozer.loader.api.FieldsMappingOptions; -import org.dozer.loader.api.TypeMappingBuilder; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.io.AbstractCsvWriter; -import org.supercsv.io.CsvBeanWriter; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * CsvDozerBeanWriter is a powerful replacement for {@link CsvBeanWriter} that uses Dozer to map from a bean to CSV. - * - * @author James Bassett - * @since 2.0.0 - */ -public class CsvDozerBeanWriter extends AbstractCsvWriter implements ICsvDozerBeanWriter { - - private final DozerBeanMapper dozerBeanMapper; - - // target of dozer bean mapping - private final CsvDozerBeanData beanData = new CsvDozerBeanData(); - - // temporary storage of processed columns to be written - private final List processedColumns = new ArrayList(); - - /** - * Constructs a new CsvDozerBeanWriter with the supplied Writer and CSV preferences and and creates it's - * own DozerBeanMapper. Note that the writer will be wrapped in a BufferedWriter before accessed. - * - * @param writer - * the writer - * @param preference - * the CSV preferences - * @throws NullPointerException - * if writer or preference are null - */ - public CsvDozerBeanWriter(final Writer writer, final CsvPreference preference) { - super(writer, preference); - this.dozerBeanMapper = new DozerBeanMapper(); - } - - /** - * Constructs a new CsvDozerBeanWriter with the supplied Writer, CSV preferences and DozerBeanMapper. Note - * that the writer will be wrapped in a BufferedWriter before accessed. - * - * @param writer - * the writer - * @param preference - * the CSV preferences - * @throws NullPointerException - * if writer, preference or dozerBeanMapper are null - */ - public CsvDozerBeanWriter(final Writer writer, final CsvPreference preference, final DozerBeanMapper dozerBeanMapper) { - super(writer, preference); - if( dozerBeanMapper == null ) { - throw new NullPointerException("dozerBeanMapper should not be null"); - } - this.dozerBeanMapper = dozerBeanMapper; - } - - /** - * {@inheritDoc} - */ - public void configureBeanMapping(final Class clazz, final String[] fieldMapping) { - dozerBeanMapper.addMapping(new MappingBuilder(clazz, fieldMapping)); - } - - /** - * {@inheritDoc} - */ - public void write(final Object source) throws IOException { - - if( source == null ) { - throw new NullPointerException("object to write should not be null"); - } - - // update the current row/line numbers - super.incrementRowAndLineNo(); - - // extract the bean values into the List using dozer - beanData.getColumns().clear(); - dozerBeanMapper.map(source, beanData); - - // write the list - super.writeRow(beanData.getColumns()); - } - - /** - * {@inheritDoc} - */ - public void write(final Object source, final CellProcessor[] processors) throws IOException { - - if( source == null ) { - throw new NullPointerException("object to write should not be null"); - } else if( processors == null ) { - throw new NullPointerException("processors should not be null"); - } - - // update the current row/line numbers - super.incrementRowAndLineNo(); - - // extract the bean values into the List using dozer - beanData.getColumns().clear(); - dozerBeanMapper.map(source, beanData); - - // execute the cell processors - Util.executeCellProcessors(processedColumns, beanData.getColumns(), processors, getLineNumber(), getRowNumber()); - - // write the list - super.writeRow(processedColumns); - } - - /** - * Assembles the dozer bean mappings required by CsvDozerBeanWriter programatically using the Dozer API. - */ - private static class MappingBuilder extends BeanMappingBuilder { - - private final Class clazz; - private final String[] fieldMapping; - - /** - * Constructs a new MappingBuilder. - * - * @param clazz - * the class to add mapping configuration for (same as the type passed into write methods) - * @param fieldMapping - * the field mapping for for each column (cannot contain null elements) - * @throws NullPointerException - * if clazz or fieldMapping (or one of its elements) is null - */ - public MappingBuilder(final Class clazz, final String[] fieldMapping) { - if( clazz == null ) { - throw new NullPointerException("clazz should not be null"); - } else if( fieldMapping == null ) { - throw new NullPointerException("fieldMapping should not be null"); - } - this.clazz = clazz; - this.fieldMapping = fieldMapping; - } - - @Override - protected void configure() { - - /* - * Add the required dozer mappings to map from each field in the supplied class to its associated column (in - * the CsvDozerBeanData List). mapNull is enabled so that null field values are added to the List (otherwise - * the List would be too short!). oneWay is enabled just in case a custom DozerBeanMapper is supplied (so - * the same DozerBeanMapper can be used by CsvDozerBeanReader). wildcard is disabled to prevent Dozer from - * trying to map every field in the bean automatically. copyByReference is enabled on the field mapping - * to ensure no conversions are performed (bean values are just copied to the List). - */ - final TypeMappingBuilder mappingBuilder = mapping(clazz, type(CsvDozerBeanData.class).mapNull(true), - oneWay(), wildcard(false)); - - for( int i = 0; i < fieldMapping.length; i++ ) { - - final String mapping = fieldMapping[i]; - - if( mapping == null ) { - // a null field mapping at end of array results in the List being too short, so don't allow - throw new NullPointerException(String.format("fieldMapping at index %d should not be null", i)); - } - - // add a field mapping from the field to the appropriate column in the beanData List - mappingBuilder.fields(mapping, "columns[" + i + "]", FieldsMappingOptions.copyByReference()); - } - } - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io.dozer; + +import static org.dozer.loader.api.TypeMappingOptions.oneWay; +import static org.dozer.loader.api.TypeMappingOptions.wildcard; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; + +import org.dozer.DozerBeanMapper; +import org.dozer.loader.api.BeanMappingBuilder; +import org.dozer.loader.api.FieldsMappingOptions; +import org.dozer.loader.api.TypeMappingBuilder; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.io.AbstractCsvWriter; +import org.supercsv.io.CsvBeanWriter; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * CsvDozerBeanWriter is a powerful replacement for {@link CsvBeanWriter} that uses Dozer to map from a bean to CSV. + * + * @author James Bassett + * @since 2.0.0 + */ +public class CsvDozerBeanWriter extends AbstractCsvWriter implements ICsvDozerBeanWriter { + + private final DozerBeanMapper dozerBeanMapper; + + // target of dozer bean mapping + private final CsvDozerBeanData beanData = new CsvDozerBeanData(); + + // temporary storage of processed columns to be written + private final List processedColumns = new ArrayList(); + + /** + * Constructs a new CsvDozerBeanWriter with the supplied Writer and CSV preferences and and creates it's + * own DozerBeanMapper. Note that the writer will be wrapped in a BufferedWriter before accessed. + * + * @param writer + * the writer + * @param preference + * the CSV preferences + * @throws NullPointerException + * if writer or preference are null + */ + public CsvDozerBeanWriter(final Writer writer, final CsvPreference preference) { + super(writer, preference); + this.dozerBeanMapper = new DozerBeanMapper(); + } + + /** + * Constructs a new CsvDozerBeanWriter with the supplied Writer, CSV preferences and DozerBeanMapper. Note + * that the writer will be wrapped in a BufferedWriter before accessed. + * + * @param writer + * the writer + * @param preference + * the CSV preferences + * @throws NullPointerException + * if writer, preference or dozerBeanMapper are null + */ + public CsvDozerBeanWriter(final Writer writer, final CsvPreference preference, final DozerBeanMapper dozerBeanMapper) { + super(writer, preference); + if( dozerBeanMapper == null ) { + throw new NullPointerException("dozerBeanMapper should not be null"); + } + this.dozerBeanMapper = dozerBeanMapper; + } + + /** + * {@inheritDoc} + */ + public void configureBeanMapping(final Class clazz, final String[] fieldMapping) { + dozerBeanMapper.addMapping(new MappingBuilder(clazz, fieldMapping)); + } + + /** + * {@inheritDoc} + */ + public void write(final Object source) throws IOException { + + if( source == null ) { + throw new NullPointerException("object to write should not be null"); + } + + // update the current row/line numbers + super.incrementRowAndLineNo(); + + // extract the bean values into the List using dozer + beanData.getColumns().clear(); + dozerBeanMapper.map(source, beanData); + + // write the list + super.writeRow(beanData.getColumns()); + } + + /** + * {@inheritDoc} + */ + public void write(final Object source, final CellProcessor[] processors) throws IOException { + + if( source == null ) { + throw new NullPointerException("object to write should not be null"); + } else if( processors == null ) { + throw new NullPointerException("processors should not be null"); + } + + // update the current row/line numbers + super.incrementRowAndLineNo(); + + // extract the bean values into the List using dozer + beanData.getColumns().clear(); + dozerBeanMapper.map(source, beanData); + + // execute the cell processors + Util.executeCellProcessors(processedColumns, beanData.getColumns(), processors, getLineNumber(), getRowNumber()); + + // write the list + super.writeRow(processedColumns); + } + + /** + * Assembles the dozer bean mappings required by CsvDozerBeanWriter programatically using the Dozer API. + */ + private static class MappingBuilder extends BeanMappingBuilder { + + private final Class clazz; + private final String[] fieldMapping; + + /** + * Constructs a new MappingBuilder. + * + * @param clazz + * the class to add mapping configuration for (same as the type passed into write methods) + * @param fieldMapping + * the field mapping for for each column (cannot contain null elements) + * @throws NullPointerException + * if clazz or fieldMapping (or one of its elements) is null + */ + public MappingBuilder(final Class clazz, final String[] fieldMapping) { + if( clazz == null ) { + throw new NullPointerException("clazz should not be null"); + } else if( fieldMapping == null ) { + throw new NullPointerException("fieldMapping should not be null"); + } + this.clazz = clazz; + this.fieldMapping = fieldMapping; + } + + @Override + protected void configure() { + + /* + * Add the required dozer mappings to map from each field in the supplied class to its associated column (in + * the CsvDozerBeanData List). mapNull is enabled so that null field values are added to the List (otherwise + * the List would be too short!). oneWay is enabled just in case a custom DozerBeanMapper is supplied (so + * the same DozerBeanMapper can be used by CsvDozerBeanReader). wildcard is disabled to prevent Dozer from + * trying to map every field in the bean automatically. copyByReference is enabled on the field mapping + * to ensure no conversions are performed (bean values are just copied to the List). + */ + final TypeMappingBuilder mappingBuilder = mapping(clazz, type(CsvDozerBeanData.class).mapNull(true), + oneWay(), wildcard(false)); + + for( int i = 0; i < fieldMapping.length; i++ ) { + + final String mapping = fieldMapping[i]; + + if( mapping == null ) { + // a null field mapping at end of array results in the List being too short, so don't allow + throw new NullPointerException(String.format("fieldMapping at index %d should not be null", i)); + } + + // add a field mapping from the field to the appropriate column in the beanData List + mappingBuilder.fields(mapping, "columns[" + i + "]", FieldsMappingOptions.copyByReference()); + } + } + } +} diff --git a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanReader.java b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanReader.java index afd6730f..7c0ed129 100644 --- a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanReader.java +++ b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanReader.java @@ -1,100 +1,100 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io.dozer; - -import java.io.IOException; - -import org.dozer.MappingException; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.io.ICsvReader; - -/** - * Interface for CSV readers reading into objects/beans using Dozer. - * - * @author James Bassett - * @since 2.0.0 - */ -public interface ICsvDozerBeanReader extends ICsvReader { - - /** - * Configures the underlying DozerBeanMapper with the mappings required to map from the CSV file to the specified - * class (this method may only be called before reading, as it's not possible to configure a DozerBeanMapper that - * has already been initialized). Generally this method will only be called once, but it may called more times to - * add mappings for other classes (you can define mappings for two different subclasses for example, but if you - * define a mapping for the parent class then that will take precedence - inheritance mapping isn't supported). - *

- * Each element of the fieldMapping array represents a CSV column to be read and uses the standard Dozer field - * mapping syntax. For example, if you were configuring the mappings for Person class you might define - * firstName as the first element (just a simple field mapping), address.city as the second - * element (a nested - or deep - field mapping), and - * accounts[0].balance as the third element (index based mapping). - *

- * If you require access to the other features of Dozer in your mappings (customer getters/setters, bean factories, custom converters), - * then you should supply your own DozerBeanMapper to the Writer instead. - * - * @param clazz - * the class to add mapping configuration for (same as the type passed into write methods) - * @param fieldMapping - * the field mapping for for each column (may contain null elements to indicate ignored columns) - * @throws NullPointerException - * if clazz or fieldMapping is null - * @since 2.0.0 - */ - void configureBeanMapping(Class clazz, String[] fieldMapping); - - /** - * Reads a row of a CSV file and populates an instance of the specified class, using Dozer to map column values to - * the appropriate fields. - * - * @param clazz - * the type to instantiate - * @return a populated bean or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws MappingException - * if there was an exception during Dozer mapping - * @throws NullPointerException - * if clazz is null - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @since 2.0.0 - */ - T read(Class clazz) throws IOException; - - /** - * Reads a row of a CSV file and populates an instance of the specified class, using Dozer to map column values to - * the appropriate fields. Before population the data can be further processed by cell processors (each element in - * the processors array corresponds with a CSV column). A null entry in the processors array indicates no - * further processing is required (the unprocessed String value will be set on the bean's field) - though Dozer will - * attempt some conversions of it's own it the types don't match. - * - * @param clazz - * the type to instantiate - * @return a populated bean or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws MappingException - * if there was an exception during Dozer mapping - * @throws NullPointerException - * if clazz is null - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @since 2.0.0 - */ - T read(Class clazz, CellProcessor... processors) throws IOException; - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io.dozer; + +import java.io.IOException; + +import org.dozer.MappingException; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.io.ICsvReader; + +/** + * Interface for CSV readers reading into objects/beans using Dozer. + * + * @author James Bassett + * @since 2.0.0 + */ +public interface ICsvDozerBeanReader extends ICsvReader { + + /** + * Configures the underlying DozerBeanMapper with the mappings required to map from the CSV file to the specified + * class (this method may only be called before reading, as it's not possible to configure a DozerBeanMapper that + * has already been initialized). Generally this method will only be called once, but it may called more times to + * add mappings for other classes (you can define mappings for two different subclasses for example, but if you + * define a mapping for the parent class then that will take precedence - inheritance mapping isn't supported). + *

+ * Each element of the fieldMapping array represents a CSV column to be read and uses the standard Dozer field + * mapping syntax. For example, if you were configuring the mappings for Person class you might define + * firstName as the first element (just a simple field mapping), address.city as the second + * element (a nested - or deep - field mapping), and + * accounts[0].balance as the third element (index based mapping). + *

+ * If you require access to the other features of Dozer in your mappings (customer getters/setters, bean factories, custom converters), + * then you should supply your own DozerBeanMapper to the Writer instead. + * + * @param clazz + * the class to add mapping configuration for (same as the type passed into write methods) + * @param fieldMapping + * the field mapping for for each column (may contain null elements to indicate ignored columns) + * @throws NullPointerException + * if clazz or fieldMapping is null + * @since 2.0.0 + */ + void configureBeanMapping(Class clazz, String[] fieldMapping); + + /** + * Reads a row of a CSV file and populates an instance of the specified class, using Dozer to map column values to + * the appropriate fields. + * + * @param clazz + * the type to instantiate + * @return a populated bean or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws MappingException + * if there was an exception during Dozer mapping + * @throws NullPointerException + * if clazz is null + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @since 2.0.0 + */ + T read(Class clazz) throws IOException; + + /** + * Reads a row of a CSV file and populates an instance of the specified class, using Dozer to map column values to + * the appropriate fields. Before population the data can be further processed by cell processors (each element in + * the processors array corresponds with a CSV column). A null entry in the processors array indicates no + * further processing is required (the unprocessed String value will be set on the bean's field) - though Dozer will + * attempt some conversions of it's own it the types don't match. + * + * @param clazz + * the type to instantiate + * @return a populated bean or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws MappingException + * if there was an exception during Dozer mapping + * @throws NullPointerException + * if clazz is null + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @since 2.0.0 + */ + T read(Class clazz, CellProcessor... processors) throws IOException; + +} diff --git a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanWriter.java b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanWriter.java index baca883a..714b7e2d 100644 --- a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanWriter.java +++ b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/ICsvDozerBeanWriter.java @@ -1,108 +1,108 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io.dozer; - -import java.io.IOException; - -import org.dozer.MappingException; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.io.ICsvWriter; - -/** - * Interface for CSV writers writing objects/beans to CSV using Dozer. - * - * @author James Bassett - * @since 2.0.0 - */ -public interface ICsvDozerBeanWriter extends ICsvWriter { - - /** - * Configures the underlying DozerBeanMapper with the mappings required to map from the specified class to the CSV - * file (this method may only be called before writing, as it's not possible to configure a DozerBeanMapper that has - * already been initialized). Generally this method will only be called once, but it may called more times to add - * mappings for other classes (you can define mappings for two different subclasses for example, but if you define a - * mapping for the parent class then that will take precedence - inheritance mapping isn't supported). - *

- * Each element of the fieldMapping array represents a CSV column to be written and uses the standard Dozer field - * mapping syntax. For example, if you were configuring the mappings for Person class you might define - * firstName as the first element (just a simple field mapping), address.city as the second - * element (a nested - or deep - field mapping), and - * accounts[0].balance as the third element (index based mapping). - *

- * If you require access to the other features of Dozer in your mappings (customer getters/setters, bean factories, custom converters), - * then you should supply your own DozerBeanMapper to the Writer instead. - * - * @param clazz - * the class to add mapping configuration for (same as the type passed into write methods) - * @param fieldMapping - * the field mapping for for each column (cannot contain null elements) - * @throws NullPointerException - * if clazz or fieldMapping (or one of its elements) is null - * @since 2.0.0 - */ - void configureBeanMapping(Class clazz, String[] fieldMapping); - - /** - * Writes the fields of the object as columns of a CSV file, using the pre-configured DozerBeanMapper to map fields - * to the appropriate columns. toString() will be called on each element prior to writing. - * - * @param source - * the object (bean instance) containing the values to write - * @throws IOException - * if an I/O error occurred - * @throws MappingException - * if there was an exception during Dozer mapping - * @throws NullPointerException - * if source is null - * @throws SuperCsvException - * if there was a general exception while writing - * @since 2.0.0 - */ - void write(Object source) throws IOException; - - /** - * Writes the fields of the object as columns of a CSV file, using the pre-configured DozerBeanMapper to map fields - * to the appropriate columns. - *

- * Before writing, the data can be further processed by cell processors (each element in the processors array - * corresponds with a CSV column). A null entry in the processors array indicates no further processing is - * required (the value returned by toString() will be written as the column value). toString() will be - * called on each (processed) element prior to writing. - * - * @param source - * the object (bean instance) containing the values to write - * @param processors - * an array of CellProcessors used to further process data before it is written (each element in the - * processors array corresponds with a CSV column - the number of processors should match the number of - * columns). A null entry indicates no further processing is required (the value returned by - * toString() will be written as the column value). - * @throws IOException - * if an I/O error occurred - * @throws MappingException - * if there was an exception during Dozer mapping - * @throws NullPointerException - * if source, nameMapping or processors are null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if there was a general exception while writing/processing - * @since 2.0.0 - */ - void write(Object source, CellProcessor[] processors) throws IOException; - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io.dozer; + +import java.io.IOException; + +import org.dozer.MappingException; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.io.ICsvWriter; + +/** + * Interface for CSV writers writing objects/beans to CSV using Dozer. + * + * @author James Bassett + * @since 2.0.0 + */ +public interface ICsvDozerBeanWriter extends ICsvWriter { + + /** + * Configures the underlying DozerBeanMapper with the mappings required to map from the specified class to the CSV + * file (this method may only be called before writing, as it's not possible to configure a DozerBeanMapper that has + * already been initialized). Generally this method will only be called once, but it may called more times to add + * mappings for other classes (you can define mappings for two different subclasses for example, but if you define a + * mapping for the parent class then that will take precedence - inheritance mapping isn't supported). + *

+ * Each element of the fieldMapping array represents a CSV column to be written and uses the standard Dozer field + * mapping syntax. For example, if you were configuring the mappings for Person class you might define + * firstName as the first element (just a simple field mapping), address.city as the second + * element (a nested - or deep - field mapping), and + * accounts[0].balance as the third element (index based mapping). + *

+ * If you require access to the other features of Dozer in your mappings (customer getters/setters, bean factories, custom converters), + * then you should supply your own DozerBeanMapper to the Writer instead. + * + * @param clazz + * the class to add mapping configuration for (same as the type passed into write methods) + * @param fieldMapping + * the field mapping for for each column (cannot contain null elements) + * @throws NullPointerException + * if clazz or fieldMapping (or one of its elements) is null + * @since 2.0.0 + */ + void configureBeanMapping(Class clazz, String[] fieldMapping); + + /** + * Writes the fields of the object as columns of a CSV file, using the pre-configured DozerBeanMapper to map fields + * to the appropriate columns. toString() will be called on each element prior to writing. + * + * @param source + * the object (bean instance) containing the values to write + * @throws IOException + * if an I/O error occurred + * @throws MappingException + * if there was an exception during Dozer mapping + * @throws NullPointerException + * if source is null + * @throws SuperCsvException + * if there was a general exception while writing + * @since 2.0.0 + */ + void write(Object source) throws IOException; + + /** + * Writes the fields of the object as columns of a CSV file, using the pre-configured DozerBeanMapper to map fields + * to the appropriate columns. + *

+ * Before writing, the data can be further processed by cell processors (each element in the processors array + * corresponds with a CSV column). A null entry in the processors array indicates no further processing is + * required (the value returned by toString() will be written as the column value). toString() will be + * called on each (processed) element prior to writing. + * + * @param source + * the object (bean instance) containing the values to write + * @param processors + * an array of CellProcessors used to further process data before it is written (each element in the + * processors array corresponds with a CSV column - the number of processors should match the number of + * columns). A null entry indicates no further processing is required (the value returned by + * toString() will be written as the column value). + * @throws IOException + * if an I/O error occurred + * @throws MappingException + * if there was an exception during Dozer mapping + * @throws NullPointerException + * if source, nameMapping or processors are null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if there was a general exception while writing/processing + * @since 2.0.0 + */ + void write(Object source, CellProcessor[] processors) throws IOException; + +} diff --git a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/package-info.java b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/package-info.java index ea57d044..272b2d15 100644 --- a/super-csv-dozer/src/main/java/org/supercsv/io/dozer/package-info.java +++ b/super-csv-dozer/src/main/java/org/supercsv/io/dozer/package-info.java @@ -1,19 +1,19 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides the various readers and writers used to read/write POJOs using Dozer. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides the various readers and writers used to read/write POJOs using Dozer. + */ package org.supercsv.io.dozer; \ No newline at end of file diff --git a/super-csv-dozer/src/site/site.xml b/super-csv-dozer/src/site/site.xml index f97dbd88..7dcd0631 100644 --- a/super-csv-dozer/src/site/site.xml +++ b/super-csv-dozer/src/site/site.xml @@ -1,25 +1,25 @@ - - - - - - - -

- - + + + + + + + + + + \ No newline at end of file diff --git a/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Reading.java b/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Reading.java index 3168be56..4c155ea8 100644 --- a/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Reading.java +++ b/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Reading.java @@ -1,122 +1,122 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.example.dozer; - -import java.io.FileReader; - -import org.supercsv.cellprocessor.Optional; -import org.supercsv.cellprocessor.ParseBool; -import org.supercsv.cellprocessor.ParseInt; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.io.dozer.CsvDozerBeanReader; -import org.supercsv.io.dozer.ICsvDozerBeanReader; -import org.supercsv.mock.dozer.SurveyResponse; -import org.supercsv.prefs.CsvPreference; - -/** - * Dozer reading examples. - */ -public class Reading { - - private static final String CSV_FILENAME = "src/test/resources/surveyresponses.csv"; - - private static final String[] FIELD_MAPPING = new String[] { - "age", // simple field mapping (like CsvBeanReader) - "consentGiven", // as above - "answers[0].questionNo", // indexed (first element) + deep mapping - "answers[0].answer", - "answers[1].questionNo", // indexed (second element) + deep mapping - "answers[1].answer", - "answers[2].questionNo", - "answers[2].answer" }; - - public static void main(String[] args) throws Exception { - readWithCsvDozerBeanReader(); - partialReadWithCsvDozerBeanReader(); - } - - /** - * An example of reading using CsvDozerBeanReader. - */ - private static void readWithCsvDozerBeanReader() throws Exception { - - final CellProcessor[] processors = new CellProcessor[] { - new Optional(new ParseInt()), // age - new ParseBool(), // consent - new ParseInt(), // questionNo 1 - new Optional(), // answer 1 - new ParseInt(), // questionNo 2 - new Optional(), // answer 2 - new ParseInt(), // questionNo 3 - new Optional() // answer 3 - }; - - ICsvDozerBeanReader beanReader = null; - try { - beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - beanReader.getHeader(true); // ignore the header - beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); - - SurveyResponse surveyResponse; - while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(), - beanReader.getRowNumber(), surveyResponse)); - } - - } - finally { - if( beanReader != null ) { - beanReader.close(); - } - } - } - - /** - * An example of partial reading using CsvDozerBeanReader. - */ - private static void partialReadWithCsvDozerBeanReader() throws Exception { - - // ignore age, and question/answer 3 - final String[] partialFieldMapping = new String[] { null, "consentGiven", "answers[0].questionNo", - "answers[0].answer", "answers[1].questionNo", "answers[1].answer", null, null }; - - // set processors for ignored columns to null for efficiency (could have used full array if we wanted them to execute anyway) - final CellProcessor[] processors = new CellProcessor[] { null, new ParseBool(), new ParseInt(), new Optional(), - new ParseInt(), new Optional(), null, null }; - - ICsvDozerBeanReader beanReader = null; - try { - beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - beanReader.getHeader(true); // ignore the header - beanReader.configureBeanMapping(SurveyResponse.class, partialFieldMapping); - - SurveyResponse surveyResponse; - while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(), - beanReader.getRowNumber(), surveyResponse)); - } - - } - finally { - if( beanReader != null ) { - beanReader.close(); - } - } - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.example.dozer; + +import java.io.FileReader; + +import org.supercsv.cellprocessor.Optional; +import org.supercsv.cellprocessor.ParseBool; +import org.supercsv.cellprocessor.ParseInt; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.io.dozer.CsvDozerBeanReader; +import org.supercsv.io.dozer.ICsvDozerBeanReader; +import org.supercsv.mock.dozer.SurveyResponse; +import org.supercsv.prefs.CsvPreference; + +/** + * Dozer reading examples. + */ +public class Reading { + + private static final String CSV_FILENAME = "src/test/resources/surveyresponses.csv"; + + private static final String[] FIELD_MAPPING = new String[] { + "age", // simple field mapping (like CsvBeanReader) + "consentGiven", // as above + "answers[0].questionNo", // indexed (first element) + deep mapping + "answers[0].answer", + "answers[1].questionNo", // indexed (second element) + deep mapping + "answers[1].answer", + "answers[2].questionNo", + "answers[2].answer" }; + + public static void main(String[] args) throws Exception { + readWithCsvDozerBeanReader(); + partialReadWithCsvDozerBeanReader(); + } + + /** + * An example of reading using CsvDozerBeanReader. + */ + private static void readWithCsvDozerBeanReader() throws Exception { + + final CellProcessor[] processors = new CellProcessor[] { + new Optional(new ParseInt()), // age + new ParseBool(), // consent + new ParseInt(), // questionNo 1 + new Optional(), // answer 1 + new ParseInt(), // questionNo 2 + new Optional(), // answer 2 + new ParseInt(), // questionNo 3 + new Optional() // answer 3 + }; + + ICsvDozerBeanReader beanReader = null; + try { + beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + beanReader.getHeader(true); // ignore the header + beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); + + SurveyResponse surveyResponse; + while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(), + beanReader.getRowNumber(), surveyResponse)); + } + + } + finally { + if( beanReader != null ) { + beanReader.close(); + } + } + } + + /** + * An example of partial reading using CsvDozerBeanReader. + */ + private static void partialReadWithCsvDozerBeanReader() throws Exception { + + // ignore age, and question/answer 3 + final String[] partialFieldMapping = new String[] { null, "consentGiven", "answers[0].questionNo", + "answers[0].answer", "answers[1].questionNo", "answers[1].answer", null, null }; + + // set processors for ignored columns to null for efficiency (could have used full array if we wanted them to execute anyway) + final CellProcessor[] processors = new CellProcessor[] { null, new ParseBool(), new ParseInt(), new Optional(), + new ParseInt(), new Optional(), null, null }; + + ICsvDozerBeanReader beanReader = null; + try { + beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + beanReader.getHeader(true); // ignore the header + beanReader.configureBeanMapping(SurveyResponse.class, partialFieldMapping); + + SurveyResponse surveyResponse; + while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(), + beanReader.getRowNumber(), surveyResponse)); + } + + } + finally { + if( beanReader != null ) { + beanReader.close(); + } + } + } + +} diff --git a/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Writing.java b/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Writing.java index 09cd6d42..dc98e7f3 100644 --- a/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Writing.java +++ b/super-csv-dozer/src/test/java/org/supercsv/example/dozer/Writing.java @@ -1,151 +1,151 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.example.dozer; - -import java.io.FileWriter; -import java.util.Arrays; -import java.util.List; - -import org.supercsv.cellprocessor.ConvertNullTo; -import org.supercsv.cellprocessor.FmtBool; -import org.supercsv.cellprocessor.Optional; -import org.supercsv.cellprocessor.constraint.NotNull; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.io.dozer.CsvDozerBeanWriter; -import org.supercsv.io.dozer.ICsvDozerBeanWriter; -import org.supercsv.mock.dozer.Answer; -import org.supercsv.mock.dozer.SurveyResponse; -import org.supercsv.prefs.CsvPreference; - -/** - * Dozer writing examples. - */ -public class Writing { - - private static final String[] FIELD_MAPPING = new String[] { - "age", // simple field mapping (like CsvBeanWriter) - "consentGiven", // as above - "answers[0].questionNo", // indexed (first element) + deep mapping - "answers[0].answer", - "answers[1].questionNo", // indexed (second element) + deep mapping - "answers[1].answer", - "answers[2].questionNo", - "answers[2].answer" }; - - public static void main(String[] args) throws Exception { - writeWithDozerCsvBeanWriter(); - partialWriteWithCsvDozerBeanWriter(); - } - - /** - * An example of writing using CsvDozerBeanWriter. - */ - private static void writeWithDozerCsvBeanWriter() throws Exception { - - final CellProcessor[] processors = new CellProcessor[] { - new Optional(), // age - new FmtBool("Y", "N"), // consent - new NotNull(), // questionNo 1 - new Optional(), // answer 1 - new NotNull(), // questionNo 2 - new Optional(), // answer 2 - new NotNull(), // questionNo 3 - new Optional() }; // answer 4 - - // create the survey responses to write - SurveyResponse response1 = new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, - "Albert Einstein"), new Answer(3, "Big Bang Theory"))); - SurveyResponse response2 = new SurveyResponse(null, true, Arrays.asList(new Answer(1, "Thirteen"), new Answer(2, - "Nikola Tesla"), new Answer(3, "Stargate"))); - SurveyResponse response3 = new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2, - "Carl Sagan"), new Answer(3, "Star Wars"))); - final List surveyResponses = Arrays.asList(response1, response2, response3); - - ICsvDozerBeanWriter beanWriter = null; - try { - beanWriter = new CsvDozerBeanWriter(new FileWriter("target/writeWithCsvDozerBeanWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // configure the mapping from the fields to the CSV columns - beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); - - // write the header - beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", - "questionNo3", "answer3"); - - // write the beans - for( final SurveyResponse surveyResponse : surveyResponses ) { - beanWriter.write(surveyResponse, processors); - } - - } - finally { - if( beanWriter != null ) { - beanWriter.close(); - } - } - } - - /** - * An example of partial reading using CsvDozerBeanWriter. - */ - private static void partialWriteWithCsvDozerBeanWriter() throws Exception { - - // null ages and answers are converted to something more meaningful - final CellProcessor[] partialProcessors = new CellProcessor[] { - new ConvertNullTo("age not supplied"), // age - new FmtBool("Y", "N"), // consent - new NotNull(), // questionNo 1 - new ConvertNullTo("not answered"), // answer 1 - new NotNull(), // questionNo 2 - new ConvertNullTo("not answered"), // answer 2 - new NotNull(), // questionNo 3 - new ConvertNullTo("not answered")}; // answer 4 - - // create the survey responses to write - SurveyResponse response1 = new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, - "Albert Einstein"), new Answer(3, "Big Bang Theory"))); - SurveyResponse response2 = new SurveyResponse(null, true, Arrays.asList(new Answer(1, "Thirteen"), new Answer(2, - "Nikola Tesla"), new Answer(3, "Stargate"))); - SurveyResponse response3 = new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2, - "Carl Sagan"), new Answer(3, "Star Wars"))); - final List surveyResponses = Arrays.asList(response1, response2, response3); - - ICsvDozerBeanWriter beanWriter = null; - try { - beanWriter = new CsvDozerBeanWriter(new FileWriter("target/partialWriteWithCsvDozerBeanWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // configure the mapping from the fields to the CSV columns - beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); - - // write the header - beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", - "questionNo3", "answer3"); - - // write the beans - for( final SurveyResponse surveyResponse : surveyResponses ) { - beanWriter.write(surveyResponse, partialProcessors); - } - - } - finally { - if( beanWriter != null ) { - beanWriter.close(); - } - } - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.example.dozer; + +import java.io.FileWriter; +import java.util.Arrays; +import java.util.List; + +import org.supercsv.cellprocessor.ConvertNullTo; +import org.supercsv.cellprocessor.FmtBool; +import org.supercsv.cellprocessor.Optional; +import org.supercsv.cellprocessor.constraint.NotNull; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.io.dozer.CsvDozerBeanWriter; +import org.supercsv.io.dozer.ICsvDozerBeanWriter; +import org.supercsv.mock.dozer.Answer; +import org.supercsv.mock.dozer.SurveyResponse; +import org.supercsv.prefs.CsvPreference; + +/** + * Dozer writing examples. + */ +public class Writing { + + private static final String[] FIELD_MAPPING = new String[] { + "age", // simple field mapping (like CsvBeanWriter) + "consentGiven", // as above + "answers[0].questionNo", // indexed (first element) + deep mapping + "answers[0].answer", + "answers[1].questionNo", // indexed (second element) + deep mapping + "answers[1].answer", + "answers[2].questionNo", + "answers[2].answer" }; + + public static void main(String[] args) throws Exception { + writeWithDozerCsvBeanWriter(); + partialWriteWithCsvDozerBeanWriter(); + } + + /** + * An example of writing using CsvDozerBeanWriter. + */ + private static void writeWithDozerCsvBeanWriter() throws Exception { + + final CellProcessor[] processors = new CellProcessor[] { + new Optional(), // age + new FmtBool("Y", "N"), // consent + new NotNull(), // questionNo 1 + new Optional(), // answer 1 + new NotNull(), // questionNo 2 + new Optional(), // answer 2 + new NotNull(), // questionNo 3 + new Optional() }; // answer 4 + + // create the survey responses to write + SurveyResponse response1 = new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, + "Albert Einstein"), new Answer(3, "Big Bang Theory"))); + SurveyResponse response2 = new SurveyResponse(null, true, Arrays.asList(new Answer(1, "Thirteen"), new Answer(2, + "Nikola Tesla"), new Answer(3, "Stargate"))); + SurveyResponse response3 = new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2, + "Carl Sagan"), new Answer(3, "Star Wars"))); + final List surveyResponses = Arrays.asList(response1, response2, response3); + + ICsvDozerBeanWriter beanWriter = null; + try { + beanWriter = new CsvDozerBeanWriter(new FileWriter("target/writeWithCsvDozerBeanWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // configure the mapping from the fields to the CSV columns + beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); + + // write the header + beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", + "questionNo3", "answer3"); + + // write the beans + for( final SurveyResponse surveyResponse : surveyResponses ) { + beanWriter.write(surveyResponse, processors); + } + + } + finally { + if( beanWriter != null ) { + beanWriter.close(); + } + } + } + + /** + * An example of partial reading using CsvDozerBeanWriter. + */ + private static void partialWriteWithCsvDozerBeanWriter() throws Exception { + + // null ages and answers are converted to something more meaningful + final CellProcessor[] partialProcessors = new CellProcessor[] { + new ConvertNullTo("age not supplied"), // age + new FmtBool("Y", "N"), // consent + new NotNull(), // questionNo 1 + new ConvertNullTo("not answered"), // answer 1 + new NotNull(), // questionNo 2 + new ConvertNullTo("not answered"), // answer 2 + new NotNull(), // questionNo 3 + new ConvertNullTo("not answered")}; // answer 4 + + // create the survey responses to write + SurveyResponse response1 = new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, + "Albert Einstein"), new Answer(3, "Big Bang Theory"))); + SurveyResponse response2 = new SurveyResponse(null, true, Arrays.asList(new Answer(1, "Thirteen"), new Answer(2, + "Nikola Tesla"), new Answer(3, "Stargate"))); + SurveyResponse response3 = new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2, + "Carl Sagan"), new Answer(3, "Star Wars"))); + final List surveyResponses = Arrays.asList(response1, response2, response3); + + ICsvDozerBeanWriter beanWriter = null; + try { + beanWriter = new CsvDozerBeanWriter(new FileWriter("target/partialWriteWithCsvDozerBeanWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // configure the mapping from the fields to the CSV columns + beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); + + // write the header + beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", + "questionNo3", "answer3"); + + // write the beans + for( final SurveyResponse surveyResponse : surveyResponses ) { + beanWriter.write(surveyResponse, partialProcessors); + } + + } + finally { + if( beanWriter != null ) { + beanWriter.close(); + } + } + } +} diff --git a/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanReaderTest.java b/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanReaderTest.java index 14728fa3..ea5926c9 100644 --- a/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanReaderTest.java +++ b/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanReaderTest.java @@ -1,492 +1,492 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io.dozer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.Arrays; - -import org.dozer.DozerBeanMapper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.Optional; -import org.supercsv.cellprocessor.ParseBool; -import org.supercsv.cellprocessor.ParseInt; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.io.ITokenizer; -import org.supercsv.io.Tokenizer; -import org.supercsv.mock.dozer.SurveyResponse; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests the CsvDozerBeanReader class. - * - * @author James Bassett - */ -public class CsvDozerBeanReaderTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private Reader reader; - - private CsvDozerBeanReader beanReader; - private CsvDozerBeanReader beanReaderWithMapper; - private CsvDozerBeanReader beanReaderWithConfiguredMapper; - private CsvDozerBeanReader tokenizerBeanReader; - private CsvDozerBeanReader tokenizerBeanReaderWithMapper; - private ITokenizer tokenizer; - private DozerBeanMapper beanMapper; - private DozerBeanMapper configuredBeanMapper; - - private static final String[] FIELD_MAPPING = new String[] { "age", "consentGiven", "answers[0].questionNo", - "answers[0].answer", "answers[1].questionNo", "answers[1].answer", "answers[2].questionNo", "answers[2].answer" }; - - private static final CellProcessor[] PROCESSORS = new CellProcessor[] { new ParseInt(), new ParseBool(), - new ParseInt(), new Optional(), new ParseInt(), new Optional(), new ParseInt(), new Optional() }; - - private static final String CSV = "age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3\n" - + "23,Y,1,Nikola Tesla,2,\"\"\"A brief history of time\"\" by Steven Hawking\",3,Theoretical physicist\n" - + "16,Y,1,Genghis Kahn,2,\"\"\"Monsoon\"\" by Wilbur Smith\",3,\n" - + "44,Y,1,,2,,3,\"I hate surveys, thanks for wasting my time!\""; - - /** - * Sets up the readers for the tests (all four constructor varieties are tested!). - */ - @Before - public void setUp() { - reader = new StringReader(CSV); - beanReader = new CsvDozerBeanReader(reader, PREFS); - - tokenizer = new Tokenizer(reader, PREFS); - tokenizerBeanReader = new CsvDozerBeanReader(tokenizer, PREFS); - - beanMapper = new DozerBeanMapper(); - beanReaderWithMapper = new CsvDozerBeanReader(reader, PREFS, beanMapper); - - configuredBeanMapper = new DozerBeanMapper(Arrays.asList("reference.xml")); - beanReaderWithConfiguredMapper = new CsvDozerBeanReader(reader, PREFS, configuredBeanMapper); - - tokenizerBeanReaderWithMapper = new CsvDozerBeanReader(tokenizer, PREFS, beanMapper); - } - - /** - * Closes the readers after the test. - */ - @After - public void tearDown() throws IOException { - beanReader.close(); - tokenizerBeanReader.close(); - beanReaderWithMapper.close(); - beanReaderWithConfiguredMapper.close(); - tokenizerBeanReaderWithMapper.close(); - } - - /** - * Tests the read() method without any processors for a standard bean reader. - */ - @Test - public void testReadForBeanReader() throws IOException { - testRead(beanReader, false, false); - } - - /** - * Tests the read() method using processors for a standard bean reader. - */ - @Test - public void testReadForBeanReaderUsingProcessors() throws IOException { - testRead(beanReader, true, false); - } - - /** - * Tests the read() method without any processors for a bean reader with custom tokenizer. - */ - @Test - public void testReadForTokenizerBeanReader() throws IOException { - testRead(tokenizerBeanReader, false, false); - } - - /** - * Tests the read() method using processors for a bean reader with custom tokenizer. - */ - @Test - public void testReadForTokenizerBeanReaderUsingProcessors() throws IOException { - testRead(tokenizerBeanReader, true, false); - } - - /** - * Tests the read() method without any processors for a bean reader with custom DozerBeanMapper. - */ - @Test - public void testReadForBeanReaderWithMapper() throws IOException { - testRead(beanReaderWithMapper, false, false); - } - - /** - * Tests the read() method using processors for a bean reader with custom DozerBeanMapper. - */ - @Test - public void testReadForBeanReaderWithMapperUsingProcessors() throws IOException { - testRead(beanReaderWithMapper, true, false); - } - - /** - * Tests the read() method without any processors for a bean reader with a pre-configured DozerBeanMapper (no need - * to call configureBeanMapping() at all). - */ - @Test - public void testReadForBeanReaderWithConfiguredMapper() throws IOException { - testRead(beanReaderWithConfiguredMapper, false, true); - } - - /** - * Tests the read() method using processors for a bean reader with a pre-configured DozerBeanMapper (no need to call - * configureBeanMapping() at all). - */ - @Test - public void testReadForBeanReaderWithConfiguredMapperUsingProcessors() throws IOException { - testRead(beanReaderWithConfiguredMapper, true, true); - } - - /** - * Tests the read() method without any processors for a bean reader with custom tokenizer and DozerBeanMapper. - */ - @Test - public void testReadForTokenizerBeanReaderWithMapper() throws IOException { - testRead(tokenizerBeanReaderWithMapper, false, false); - } - - /** - * Tests the read() method using processors for a bean reader with custom tokenizer and DozerBeanMapper. - */ - @Test - public void testReadForTokenizerBeanReaderWithMapperUsingProcessors() throws IOException { - testRead(tokenizerBeanReaderWithMapper, true, false); - } - - /** - * Tests the read() method with or without processors. The great thing here is that Dozer is smart enough to map the - * Booleans and Integers even if no processors are used, so the results should be identical! - * - * @param beanReader - * the bean reader to use for the test - * @param useProcessors - * whether processors should be used for the test - * @param configured - * whether the reader is already configured - * @throws IOException - */ - private void testRead(final CsvDozerBeanReader beanReader, final boolean useProcessors, final boolean configured) - throws IOException { - - beanReader.getHeader(true); - - if( !configured ) { - beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); - } - - SurveyResponse response1 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class); - assertEquals(23, response1.getAge().intValue()); - assertEquals(Boolean.TRUE, response1.getConsentGiven()); - assertEquals(3, response1.getAnswers().size()); - assertEquals(1, response1.getAnswers().get(0).getQuestionNo().intValue()); - assertEquals("Nikola Tesla", response1.getAnswers().get(0).getAnswer()); - assertEquals(2, response1.getAnswers().get(1).getQuestionNo().intValue()); - assertEquals("\"A brief history of time\" by Steven Hawking", response1.getAnswers().get(1).getAnswer()); - assertEquals(3, response1.getAnswers().get(2).getQuestionNo().intValue()); - assertEquals("Theoretical physicist", response1.getAnswers().get(2).getAnswer()); - - SurveyResponse response2 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class); - assertEquals(16, response2.getAge().intValue()); - assertEquals(Boolean.TRUE, response2.getConsentGiven()); - assertEquals(3, response2.getAnswers().size()); - assertEquals(1, response2.getAnswers().get(0).getQuestionNo().intValue()); - assertEquals("Genghis Kahn", response2.getAnswers().get(0).getAnswer()); - assertEquals(2, response2.getAnswers().get(1).getQuestionNo().intValue()); - assertEquals("\"Monsoon\" by Wilbur Smith", response2.getAnswers().get(1).getAnswer()); - assertEquals(3, response2.getAnswers().get(2).getQuestionNo().intValue()); - assertNull(response2.getAnswers().get(2).getAnswer()); - - SurveyResponse response3 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class); - assertEquals(44, response3.getAge().intValue()); - assertEquals(Boolean.TRUE, response3.getConsentGiven()); - assertEquals(3, response3.getAnswers().size()); - assertEquals(1, response3.getAnswers().get(0).getQuestionNo().intValue()); - assertNull(response3.getAnswers().get(0).getAnswer()); - assertEquals(2, response3.getAnswers().get(1).getQuestionNo().intValue()); - assertNull(response3.getAnswers().get(1).getAnswer()); - assertEquals(3, response3.getAnswers().get(2).getQuestionNo().intValue()); - assertEquals("I hate surveys, thanks for wasting my time!", response3.getAnswers().get(2).getAnswer()); - - assertNull(useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class)); - - } - - /** - * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a - * standard bean reader. - */ - @Test - public void testPartialReadForBeanReader() throws IOException { - testPartialRead(beanReader, false); - } - - /** - * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a standard - * bean reader. - */ - @Test - public void testPartialReadForBeanReaderUsingProcessors() throws IOException { - testPartialRead(beanReader, true); - } - - /** - * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a - * bean reader with custom tokenizer. - */ - @Test - public void testPartialReadForTokenizerBeanReader() throws IOException { - testPartialRead(tokenizerBeanReader, false); - } - - /** - * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a bean - * reader with custom tokenizer. - */ - @Test - public void testPartialReadForTokenizerBeanReaderUsingProcessors() throws IOException { - testPartialRead(tokenizerBeanReader, true); - } - - /** - * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a - * bean reader with custom DozerBeanMapper. - */ - @Test - public void testPartialReadForBeanReaderWithMapper() throws IOException { - testPartialRead(beanReaderWithMapper, false); - } - - /** - * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a bean - * reader with custom DozerBeanMapper. - */ - @Test - public void testPartialReadForBeanReaderWithMapperUsingProcessors() throws IOException { - testPartialRead(beanReaderWithMapper, true); - } - - /** - * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a - * bean reader with custom tokenizer and DozerBeanMapper. - */ - @Test - public void testPartialReadForTokenizerBeanReaderWithMapper() throws IOException { - testPartialRead(tokenizerBeanReaderWithMapper, false); - } - - /** - * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a bean - * reader with custom tokenizer and DozerBeanMapper. - */ - @Test - public void testPartialReadForTokenizerBeanReaderWithMapperUsingProcessors() throws IOException { - testPartialRead(tokenizerBeanReaderWithMapper, true); - } - - /** - * Tests the read() method with or without any processors with null elements in the fieldMapping (ignored columns). - * As Dozer is smart enough to do basic type mapping, the result will be the same regardless of whether processors - * are used. - * - * @param beanReader - * the bean reader to use for the test - * @param useProcessors - * whether processors should be used for the test - * @throws IOException - */ - private void testPartialRead(final CsvDozerBeanReader beanReader, final boolean useProcessors) throws IOException { - - beanReader.getHeader(true); - - // ignore age, and the last question/answer - final String[] partialMapping = new String[] { null, "consentGiven", "answers[0].questionNo", - "answers[0].answer", "answers[1].questionNo", "answers[1].answer", null, null }; - beanReader.configureBeanMapping(SurveyResponse.class, partialMapping); - - SurveyResponse response1 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class); - assertNull(response1.getAge()); - assertEquals(Boolean.TRUE, response1.getConsentGiven()); - assertEquals(2, response1.getAnswers().size()); - assertEquals(1, response1.getAnswers().get(0).getQuestionNo().intValue()); - assertEquals("Nikola Tesla", response1.getAnswers().get(0).getAnswer()); - assertEquals(2, response1.getAnswers().get(1).getQuestionNo().intValue()); - assertEquals("\"A brief history of time\" by Steven Hawking", response1.getAnswers().get(1).getAnswer()); - - SurveyResponse response2 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class); - assertNull(response2.getAge()); - assertEquals(Boolean.TRUE, response2.getConsentGiven()); - assertEquals(2, response2.getAnswers().size()); - assertEquals(1, response2.getAnswers().get(0).getQuestionNo().intValue()); - assertEquals("Genghis Kahn", response2.getAnswers().get(0).getAnswer()); - assertEquals(2, response2.getAnswers().get(1).getQuestionNo().intValue()); - assertEquals("\"Monsoon\" by Wilbur Smith", response2.getAnswers().get(1).getAnswer()); - - SurveyResponse response3 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class); - assertNull(response3.getAge()); - assertEquals(Boolean.TRUE, response3.getConsentGiven()); - assertEquals(2, response3.getAnswers().size()); - assertEquals(1, response3.getAnswers().get(0).getQuestionNo().intValue()); - assertNull(response3.getAnswers().get(0).getAnswer()); - assertEquals(2, response3.getAnswers().get(1).getQuestionNo().intValue()); - assertNull(response3.getAnswers().get(1).getAnswer()); - - assertNull(useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader - .read(SurveyResponse.class)); - - } - - /** - * Tests all of the constructors with null values (should throw an Exception). - */ - @Test - public void testConstructorsWithNulls() { - - // constructor one - null reader - try { - new CsvDozerBeanReader((Reader) null, PREFS); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor one - null prefs - try { - new CsvDozerBeanReader(reader, null); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor two - null tokenizer - try { - new CsvDozerBeanReader((ITokenizer) null, PREFS); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor two - null prefs - try { - new CsvDozerBeanReader(tokenizer, null); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor three - null reader - try { - new CsvDozerBeanReader((Reader) null, PREFS, beanMapper); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor three - null prefs - try { - new CsvDozerBeanReader(reader, null, beanMapper); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor three - null dozerBeanMapper - try { - new CsvDozerBeanReader(reader, PREFS, null); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor four - null tokenizer - try { - new CsvDozerBeanReader((ITokenizer) null, PREFS, beanMapper); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor four - null prefs - try { - new CsvDozerBeanReader(tokenizer, null, beanMapper); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor four - null dozerBeanMapper - try { - new CsvDozerBeanReader(tokenizer, PREFS, null); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - } - - /** - * Tests the configureBeanMapping() method with a null clazz (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testConfigureBeanMappingWithNullClazz() { - beanReader.configureBeanMapping(null, FIELD_MAPPING); - } - - /** - * Tests the configureBeanMapping() method with a null fieldMapping array (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testConfigureBeanMappingWithNullFieldMapping() { - beanReader.configureBeanMapping(SurveyResponse.class, null); - } - - /** - * Tests the read() method with a null clazz (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testReadWithNullClazz() throws IOException { - beanReader.read(null); - } - - /** - * Tests the read() method (with processors) with a null clazz (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testReadWithProcessorsWithNullClazz() throws IOException { - beanReader.read(null, PROCESSORS); - } - - /** - * Tests the read() method (with processors) with a null cell processor array (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testReadWithProcessorsWithNullProcessors() throws IOException { - beanReader.read(SurveyResponse.class, (CellProcessor[]) null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io.dozer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.Arrays; + +import org.dozer.DozerBeanMapper; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.Optional; +import org.supercsv.cellprocessor.ParseBool; +import org.supercsv.cellprocessor.ParseInt; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.io.ITokenizer; +import org.supercsv.io.Tokenizer; +import org.supercsv.mock.dozer.SurveyResponse; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests the CsvDozerBeanReader class. + * + * @author James Bassett + */ +public class CsvDozerBeanReaderTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private Reader reader; + + private CsvDozerBeanReader beanReader; + private CsvDozerBeanReader beanReaderWithMapper; + private CsvDozerBeanReader beanReaderWithConfiguredMapper; + private CsvDozerBeanReader tokenizerBeanReader; + private CsvDozerBeanReader tokenizerBeanReaderWithMapper; + private ITokenizer tokenizer; + private DozerBeanMapper beanMapper; + private DozerBeanMapper configuredBeanMapper; + + private static final String[] FIELD_MAPPING = new String[] { "age", "consentGiven", "answers[0].questionNo", + "answers[0].answer", "answers[1].questionNo", "answers[1].answer", "answers[2].questionNo", "answers[2].answer" }; + + private static final CellProcessor[] PROCESSORS = new CellProcessor[] { new ParseInt(), new ParseBool(), + new ParseInt(), new Optional(), new ParseInt(), new Optional(), new ParseInt(), new Optional() }; + + private static final String CSV = "age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3\n" + + "23,Y,1,Nikola Tesla,2,\"\"\"A brief history of time\"\" by Steven Hawking\",3,Theoretical physicist\n" + + "16,Y,1,Genghis Kahn,2,\"\"\"Monsoon\"\" by Wilbur Smith\",3,\n" + + "44,Y,1,,2,,3,\"I hate surveys, thanks for wasting my time!\""; + + /** + * Sets up the readers for the tests (all four constructor varieties are tested!). + */ + @Before + public void setUp() { + reader = new StringReader(CSV); + beanReader = new CsvDozerBeanReader(reader, PREFS); + + tokenizer = new Tokenizer(reader, PREFS); + tokenizerBeanReader = new CsvDozerBeanReader(tokenizer, PREFS); + + beanMapper = new DozerBeanMapper(); + beanReaderWithMapper = new CsvDozerBeanReader(reader, PREFS, beanMapper); + + configuredBeanMapper = new DozerBeanMapper(Arrays.asList("reference.xml")); + beanReaderWithConfiguredMapper = new CsvDozerBeanReader(reader, PREFS, configuredBeanMapper); + + tokenizerBeanReaderWithMapper = new CsvDozerBeanReader(tokenizer, PREFS, beanMapper); + } + + /** + * Closes the readers after the test. + */ + @After + public void tearDown() throws IOException { + beanReader.close(); + tokenizerBeanReader.close(); + beanReaderWithMapper.close(); + beanReaderWithConfiguredMapper.close(); + tokenizerBeanReaderWithMapper.close(); + } + + /** + * Tests the read() method without any processors for a standard bean reader. + */ + @Test + public void testReadForBeanReader() throws IOException { + testRead(beanReader, false, false); + } + + /** + * Tests the read() method using processors for a standard bean reader. + */ + @Test + public void testReadForBeanReaderUsingProcessors() throws IOException { + testRead(beanReader, true, false); + } + + /** + * Tests the read() method without any processors for a bean reader with custom tokenizer. + */ + @Test + public void testReadForTokenizerBeanReader() throws IOException { + testRead(tokenizerBeanReader, false, false); + } + + /** + * Tests the read() method using processors for a bean reader with custom tokenizer. + */ + @Test + public void testReadForTokenizerBeanReaderUsingProcessors() throws IOException { + testRead(tokenizerBeanReader, true, false); + } + + /** + * Tests the read() method without any processors for a bean reader with custom DozerBeanMapper. + */ + @Test + public void testReadForBeanReaderWithMapper() throws IOException { + testRead(beanReaderWithMapper, false, false); + } + + /** + * Tests the read() method using processors for a bean reader with custom DozerBeanMapper. + */ + @Test + public void testReadForBeanReaderWithMapperUsingProcessors() throws IOException { + testRead(beanReaderWithMapper, true, false); + } + + /** + * Tests the read() method without any processors for a bean reader with a pre-configured DozerBeanMapper (no need + * to call configureBeanMapping() at all). + */ + @Test + public void testReadForBeanReaderWithConfiguredMapper() throws IOException { + testRead(beanReaderWithConfiguredMapper, false, true); + } + + /** + * Tests the read() method using processors for a bean reader with a pre-configured DozerBeanMapper (no need to call + * configureBeanMapping() at all). + */ + @Test + public void testReadForBeanReaderWithConfiguredMapperUsingProcessors() throws IOException { + testRead(beanReaderWithConfiguredMapper, true, true); + } + + /** + * Tests the read() method without any processors for a bean reader with custom tokenizer and DozerBeanMapper. + */ + @Test + public void testReadForTokenizerBeanReaderWithMapper() throws IOException { + testRead(tokenizerBeanReaderWithMapper, false, false); + } + + /** + * Tests the read() method using processors for a bean reader with custom tokenizer and DozerBeanMapper. + */ + @Test + public void testReadForTokenizerBeanReaderWithMapperUsingProcessors() throws IOException { + testRead(tokenizerBeanReaderWithMapper, true, false); + } + + /** + * Tests the read() method with or without processors. The great thing here is that Dozer is smart enough to map the + * Booleans and Integers even if no processors are used, so the results should be identical! + * + * @param beanReader + * the bean reader to use for the test + * @param useProcessors + * whether processors should be used for the test + * @param configured + * whether the reader is already configured + * @throws IOException + */ + private void testRead(final CsvDozerBeanReader beanReader, final boolean useProcessors, final boolean configured) + throws IOException { + + beanReader.getHeader(true); + + if( !configured ) { + beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); + } + + SurveyResponse response1 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class); + assertEquals(23, response1.getAge().intValue()); + assertEquals(Boolean.TRUE, response1.getConsentGiven()); + assertEquals(3, response1.getAnswers().size()); + assertEquals(1, response1.getAnswers().get(0).getQuestionNo().intValue()); + assertEquals("Nikola Tesla", response1.getAnswers().get(0).getAnswer()); + assertEquals(2, response1.getAnswers().get(1).getQuestionNo().intValue()); + assertEquals("\"A brief history of time\" by Steven Hawking", response1.getAnswers().get(1).getAnswer()); + assertEquals(3, response1.getAnswers().get(2).getQuestionNo().intValue()); + assertEquals("Theoretical physicist", response1.getAnswers().get(2).getAnswer()); + + SurveyResponse response2 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class); + assertEquals(16, response2.getAge().intValue()); + assertEquals(Boolean.TRUE, response2.getConsentGiven()); + assertEquals(3, response2.getAnswers().size()); + assertEquals(1, response2.getAnswers().get(0).getQuestionNo().intValue()); + assertEquals("Genghis Kahn", response2.getAnswers().get(0).getAnswer()); + assertEquals(2, response2.getAnswers().get(1).getQuestionNo().intValue()); + assertEquals("\"Monsoon\" by Wilbur Smith", response2.getAnswers().get(1).getAnswer()); + assertEquals(3, response2.getAnswers().get(2).getQuestionNo().intValue()); + assertNull(response2.getAnswers().get(2).getAnswer()); + + SurveyResponse response3 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class); + assertEquals(44, response3.getAge().intValue()); + assertEquals(Boolean.TRUE, response3.getConsentGiven()); + assertEquals(3, response3.getAnswers().size()); + assertEquals(1, response3.getAnswers().get(0).getQuestionNo().intValue()); + assertNull(response3.getAnswers().get(0).getAnswer()); + assertEquals(2, response3.getAnswers().get(1).getQuestionNo().intValue()); + assertNull(response3.getAnswers().get(1).getAnswer()); + assertEquals(3, response3.getAnswers().get(2).getQuestionNo().intValue()); + assertEquals("I hate surveys, thanks for wasting my time!", response3.getAnswers().get(2).getAnswer()); + + assertNull(useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class)); + + } + + /** + * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a + * standard bean reader. + */ + @Test + public void testPartialReadForBeanReader() throws IOException { + testPartialRead(beanReader, false); + } + + /** + * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a standard + * bean reader. + */ + @Test + public void testPartialReadForBeanReaderUsingProcessors() throws IOException { + testPartialRead(beanReader, true); + } + + /** + * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a + * bean reader with custom tokenizer. + */ + @Test + public void testPartialReadForTokenizerBeanReader() throws IOException { + testPartialRead(tokenizerBeanReader, false); + } + + /** + * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a bean + * reader with custom tokenizer. + */ + @Test + public void testPartialReadForTokenizerBeanReaderUsingProcessors() throws IOException { + testPartialRead(tokenizerBeanReader, true); + } + + /** + * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a + * bean reader with custom DozerBeanMapper. + */ + @Test + public void testPartialReadForBeanReaderWithMapper() throws IOException { + testPartialRead(beanReaderWithMapper, false); + } + + /** + * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a bean + * reader with custom DozerBeanMapper. + */ + @Test + public void testPartialReadForBeanReaderWithMapperUsingProcessors() throws IOException { + testPartialRead(beanReaderWithMapper, true); + } + + /** + * Tests the read() method without any processors with null elements in the fieldMapping (ignored columns) for a + * bean reader with custom tokenizer and DozerBeanMapper. + */ + @Test + public void testPartialReadForTokenizerBeanReaderWithMapper() throws IOException { + testPartialRead(tokenizerBeanReaderWithMapper, false); + } + + /** + * Tests the read() method using processors with null elements in the fieldMapping (ignored columns) for a bean + * reader with custom tokenizer and DozerBeanMapper. + */ + @Test + public void testPartialReadForTokenizerBeanReaderWithMapperUsingProcessors() throws IOException { + testPartialRead(tokenizerBeanReaderWithMapper, true); + } + + /** + * Tests the read() method with or without any processors with null elements in the fieldMapping (ignored columns). + * As Dozer is smart enough to do basic type mapping, the result will be the same regardless of whether processors + * are used. + * + * @param beanReader + * the bean reader to use for the test + * @param useProcessors + * whether processors should be used for the test + * @throws IOException + */ + private void testPartialRead(final CsvDozerBeanReader beanReader, final boolean useProcessors) throws IOException { + + beanReader.getHeader(true); + + // ignore age, and the last question/answer + final String[] partialMapping = new String[] { null, "consentGiven", "answers[0].questionNo", + "answers[0].answer", "answers[1].questionNo", "answers[1].answer", null, null }; + beanReader.configureBeanMapping(SurveyResponse.class, partialMapping); + + SurveyResponse response1 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class); + assertNull(response1.getAge()); + assertEquals(Boolean.TRUE, response1.getConsentGiven()); + assertEquals(2, response1.getAnswers().size()); + assertEquals(1, response1.getAnswers().get(0).getQuestionNo().intValue()); + assertEquals("Nikola Tesla", response1.getAnswers().get(0).getAnswer()); + assertEquals(2, response1.getAnswers().get(1).getQuestionNo().intValue()); + assertEquals("\"A brief history of time\" by Steven Hawking", response1.getAnswers().get(1).getAnswer()); + + SurveyResponse response2 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class); + assertNull(response2.getAge()); + assertEquals(Boolean.TRUE, response2.getConsentGiven()); + assertEquals(2, response2.getAnswers().size()); + assertEquals(1, response2.getAnswers().get(0).getQuestionNo().intValue()); + assertEquals("Genghis Kahn", response2.getAnswers().get(0).getAnswer()); + assertEquals(2, response2.getAnswers().get(1).getQuestionNo().intValue()); + assertEquals("\"Monsoon\" by Wilbur Smith", response2.getAnswers().get(1).getAnswer()); + + SurveyResponse response3 = useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class); + assertNull(response3.getAge()); + assertEquals(Boolean.TRUE, response3.getConsentGiven()); + assertEquals(2, response3.getAnswers().size()); + assertEquals(1, response3.getAnswers().get(0).getQuestionNo().intValue()); + assertNull(response3.getAnswers().get(0).getAnswer()); + assertEquals(2, response3.getAnswers().get(1).getQuestionNo().intValue()); + assertNull(response3.getAnswers().get(1).getAnswer()); + + assertNull(useProcessors ? beanReader.read(SurveyResponse.class, PROCESSORS) : beanReader + .read(SurveyResponse.class)); + + } + + /** + * Tests all of the constructors with null values (should throw an Exception). + */ + @Test + public void testConstructorsWithNulls() { + + // constructor one - null reader + try { + new CsvDozerBeanReader((Reader) null, PREFS); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor one - null prefs + try { + new CsvDozerBeanReader(reader, null); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor two - null tokenizer + try { + new CsvDozerBeanReader((ITokenizer) null, PREFS); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor two - null prefs + try { + new CsvDozerBeanReader(tokenizer, null); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor three - null reader + try { + new CsvDozerBeanReader((Reader) null, PREFS, beanMapper); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor three - null prefs + try { + new CsvDozerBeanReader(reader, null, beanMapper); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor three - null dozerBeanMapper + try { + new CsvDozerBeanReader(reader, PREFS, null); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor four - null tokenizer + try { + new CsvDozerBeanReader((ITokenizer) null, PREFS, beanMapper); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor four - null prefs + try { + new CsvDozerBeanReader(tokenizer, null, beanMapper); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor four - null dozerBeanMapper + try { + new CsvDozerBeanReader(tokenizer, PREFS, null); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + } + + /** + * Tests the configureBeanMapping() method with a null clazz (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testConfigureBeanMappingWithNullClazz() { + beanReader.configureBeanMapping(null, FIELD_MAPPING); + } + + /** + * Tests the configureBeanMapping() method with a null fieldMapping array (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testConfigureBeanMappingWithNullFieldMapping() { + beanReader.configureBeanMapping(SurveyResponse.class, null); + } + + /** + * Tests the read() method with a null clazz (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testReadWithNullClazz() throws IOException { + beanReader.read(null); + } + + /** + * Tests the read() method (with processors) with a null clazz (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testReadWithProcessorsWithNullClazz() throws IOException { + beanReader.read(null, PROCESSORS); + } + + /** + * Tests the read() method (with processors) with a null cell processor array (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testReadWithProcessorsWithNullProcessors() throws IOException { + beanReader.read(SurveyResponse.class, (CellProcessor[]) null); + } + +} diff --git a/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanWriterTest.java b/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanWriterTest.java index 50b5dd70..9b5fb557 100644 --- a/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanWriterTest.java +++ b/super-csv-dozer/src/test/java/org/supercsv/io/dozer/CsvDozerBeanWriterTest.java @@ -1,293 +1,293 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io.dozer; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Arrays; - -import org.dozer.DozerBeanMapper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.FmtBool; -import org.supercsv.cellprocessor.Optional; -import org.supercsv.cellprocessor.constraint.NotNull; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.mock.dozer.Answer; -import org.supercsv.mock.dozer.SurveyResponse; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests the CsvDozerBeanWriter class. - * - * @author James Bassett - */ -public class CsvDozerBeanWriterTest { - - private static final CsvPreference PREFS = CsvPreference.EXCEL_PREFERENCE; - - private static final String[] FIELD_MAPPING = new String[] { "age", "consentGiven", "answers[0].questionNo", - "answers[0].answer", "answers[1].questionNo", "answers[1].answer", "answers[2].questionNo", "answers[2].answer" }; - - private static final CellProcessor[] PROCESSORS = new CellProcessor[] { new NotNull(), new FmtBool("Y", "N"), - new Optional(), new Optional(), new Optional(), new Optional(), new Optional(), new Optional() }; - - private static final String CSV = "age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3\n" - + "66,true,1,Twelve,2,Albert Einstein?,3,Big Bang Theory\n" + "32,true,1,,2,Superman,3,Stargate\n" - + "19,true,1,\"Um, how am I supposed to know?\",2,Me,3,\"Last question, can I go now?\"\n" + "4,false,,,,,,\n"; - - private static final String PROCESSORS_CSV = "age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3\n" - + "66,Y,1,Twelve,2,Albert Einstein?,3,Big Bang Theory\n" - + "32,Y,1,,2,Superman,3,Stargate\n" - + "19,Y,1,\"Um, how am I supposed to know?\",2,Me,3,\"Last question, can I go now?\"\n" + "4,N,,,,,,\n"; - - private Writer writer; - - private CsvDozerBeanWriter beanWriter; - private CsvDozerBeanWriter beanWriterWithMapper; - private CsvDozerBeanWriter beanWriterWithConfiguredMapper; - private DozerBeanMapper beanMapper; - private DozerBeanMapper configuredBeanMapper; - - private SurveyResponse response1; - private SurveyResponse response2; - private SurveyResponse response3; - private SurveyResponse response4; - - /** - * Sets up the writer for the tests. - */ - @Before - public void setUp() { - writer = new StringWriter(); - beanWriter = new CsvDozerBeanWriter(writer, PREFS); - - beanMapper = new DozerBeanMapper(); - beanWriterWithMapper = new CsvDozerBeanWriter(writer, PREFS, beanMapper); - - configuredBeanMapper = new DozerBeanMapper(Arrays.asList("reference.xml")); - beanWriterWithConfiguredMapper = new CsvDozerBeanWriter(writer, PREFS, configuredBeanMapper); - } - - /** - * Closes the bean writers after the test. - */ - @After - public void tearDown() throws IOException { - beanWriter.close(); - beanWriterWithMapper.close(); - beanWriterWithConfiguredMapper.close(); - } - - /** - * Creates the survey responses to use in the tests. - */ - @Before - public void createResponses() { - response1 = new SurveyResponse(66, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, - "Albert Einstein?"), new Answer(3, "Big Bang Theory"))); - response2 = new SurveyResponse(32, true, Arrays.asList(new Answer(1, null), new Answer(2, "Superman"), - new Answer(3, "Stargate"))); - response3 = new SurveyResponse(19, true, Arrays.asList(new Answer(1, "Um, how am I supposed to know?"), - new Answer(2, "Me"), new Answer(3, "Last question, can I go now?"))); - response4 = new SurveyResponse(4, false, null); - } - - /** - * Tests the write() method with a normal bean writer and no processors. - */ - @Test - public void testWriteWithBeanWriter() throws IOException { - testWrite(beanWriter, false, false); - } - - /** - * Tests the write() method with a normal bean writer and processors. - */ - @Test - public void testWriteWithBeanWriterUsingProcessors() throws IOException { - testWrite(beanWriter, true, false); - } - - /** - * Tests the write() method with a bean writer using a custom DozerBeanMapper and no processors. - */ - @Test - public void testWriteWithBeanWriterCustomMapper() throws IOException { - testWrite(beanWriterWithMapper, false, false); - } - - /** - * Tests the write() method with a bean writer using a custom DozerBeanMapper and processors. - */ - @Test - public void testWriteWithBeanWriterCustomMapperUsingProcessors() throws IOException { - testWrite(beanWriterWithMapper, true, false); - } - - /** - * Tests the write() method with a bean writer using a custom DozerBeanMapper and no processors. - */ - @Test - public void testWriteWithBeanWriterConfiguredMapper() throws IOException { - testWrite(beanWriterWithConfiguredMapper, false, true); - } - - /** - * Tests the write() method with a bean writer using a custom DozerBeanMapper and processors. - */ - @Test - public void testWriteWithBeanWriterConfiguredMapperUsingProcessors() throws IOException { - testWrite(beanWriterWithConfiguredMapper, true, true); - } - - /** - * Tests the write() methods with the supplied writer, with or without using processors. - * - * @param beanWriter - * the dozer bean writer to use for the tests - * @param useProcessors - * whether to use processors for the test - * @param configured - * whether the writer is already configured - * @throws IOException - */ - private void testWrite(final CsvDozerBeanWriter beanWriter, final boolean useProcessors, final boolean configured) - throws IOException { - - if (!configured){ - beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); - } - - beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", - "questionNo3", "answer3"); - - if( useProcessors ) { - beanWriter.write(response1, PROCESSORS); - beanWriter.write(response2, PROCESSORS); - beanWriter.write(response3, PROCESSORS); - beanWriter.write(response4, PROCESSORS); - beanWriter.flush(); - assertEquals(PROCESSORS_CSV, writer.toString()); - - } else { - beanWriter.write(response1); - beanWriter.write(response2); - beanWriter.write(response3); - beanWriter.write(response4); - beanWriter.flush(); - assertEquals(CSV, writer.toString()); - } - - } - - /** - * Tests all of the constructors with null values (should throw an Exception). - */ - @Test - public void testConstructorsWithNulls() { - - // constructor one - null Writer - try { - new CsvDozerBeanWriter((Writer) null, PREFS); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor one - null prefs - try { - new CsvDozerBeanWriter(writer, null); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor two - null Writer - try { - new CsvDozerBeanWriter((Writer) null, PREFS, beanMapper); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor two - null prefs - try { - new CsvDozerBeanWriter(writer, null, beanMapper); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - // constructor two - null dozerBeanMapper - try { - new CsvDozerBeanWriter(writer, PREFS, null); - fail("should have thrown NullPointerException"); - } - catch(NullPointerException e) {} - - } - - /** - * Tests the configureBeanMapping() method with a null clazz (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testConfigureBeanMappingWithNullClazz() { - beanWriter.configureBeanMapping(null, FIELD_MAPPING); - } - - /** - * Tests the configureBeanMapping() method with a null fieldMapping array (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testConfigureBeanMappingWithNullFieldMapping() { - beanWriter.configureBeanMapping(SurveyResponse.class, null); - } - - /** - * Tests the configureBeanMapping() method with a null fieldMapping element (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testConfigureBeanMappingWithNullFieldMappingElement() { - beanWriter.configureBeanMapping(SurveyResponse.class, new String[] { "age", null, "consentGiven" }); - } - - /** - * Tests the write() method with a null clazz (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testWriteWithNullClazz() throws IOException { - beanWriter.write(null); - } - - /** - * Tests the write() method (with processors) with a null clazz (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testWriteWithProcessorsWithNullClazz() throws IOException { - beanWriter.write(null, PROCESSORS); - } - - /** - * Tests the write() method (with processors) with a null cell processor array (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testWriteWithProcessorsWithNullProcessors() throws IOException { - beanWriter.write(SurveyResponse.class, (CellProcessor[]) null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io.dozer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Arrays; + +import org.dozer.DozerBeanMapper; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.FmtBool; +import org.supercsv.cellprocessor.Optional; +import org.supercsv.cellprocessor.constraint.NotNull; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.mock.dozer.Answer; +import org.supercsv.mock.dozer.SurveyResponse; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests the CsvDozerBeanWriter class. + * + * @author James Bassett + */ +public class CsvDozerBeanWriterTest { + + private static final CsvPreference PREFS = CsvPreference.EXCEL_PREFERENCE; + + private static final String[] FIELD_MAPPING = new String[] { "age", "consentGiven", "answers[0].questionNo", + "answers[0].answer", "answers[1].questionNo", "answers[1].answer", "answers[2].questionNo", "answers[2].answer" }; + + private static final CellProcessor[] PROCESSORS = new CellProcessor[] { new NotNull(), new FmtBool("Y", "N"), + new Optional(), new Optional(), new Optional(), new Optional(), new Optional(), new Optional() }; + + private static final String CSV = "age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3\n" + + "66,true,1,Twelve,2,Albert Einstein?,3,Big Bang Theory\n" + "32,true,1,,2,Superman,3,Stargate\n" + + "19,true,1,\"Um, how am I supposed to know?\",2,Me,3,\"Last question, can I go now?\"\n" + "4,false,,,,,,\n"; + + private static final String PROCESSORS_CSV = "age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3\n" + + "66,Y,1,Twelve,2,Albert Einstein?,3,Big Bang Theory\n" + + "32,Y,1,,2,Superman,3,Stargate\n" + + "19,Y,1,\"Um, how am I supposed to know?\",2,Me,3,\"Last question, can I go now?\"\n" + "4,N,,,,,,\n"; + + private Writer writer; + + private CsvDozerBeanWriter beanWriter; + private CsvDozerBeanWriter beanWriterWithMapper; + private CsvDozerBeanWriter beanWriterWithConfiguredMapper; + private DozerBeanMapper beanMapper; + private DozerBeanMapper configuredBeanMapper; + + private SurveyResponse response1; + private SurveyResponse response2; + private SurveyResponse response3; + private SurveyResponse response4; + + /** + * Sets up the writer for the tests. + */ + @Before + public void setUp() { + writer = new StringWriter(); + beanWriter = new CsvDozerBeanWriter(writer, PREFS); + + beanMapper = new DozerBeanMapper(); + beanWriterWithMapper = new CsvDozerBeanWriter(writer, PREFS, beanMapper); + + configuredBeanMapper = new DozerBeanMapper(Arrays.asList("reference.xml")); + beanWriterWithConfiguredMapper = new CsvDozerBeanWriter(writer, PREFS, configuredBeanMapper); + } + + /** + * Closes the bean writers after the test. + */ + @After + public void tearDown() throws IOException { + beanWriter.close(); + beanWriterWithMapper.close(); + beanWriterWithConfiguredMapper.close(); + } + + /** + * Creates the survey responses to use in the tests. + */ + @Before + public void createResponses() { + response1 = new SurveyResponse(66, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2, + "Albert Einstein?"), new Answer(3, "Big Bang Theory"))); + response2 = new SurveyResponse(32, true, Arrays.asList(new Answer(1, null), new Answer(2, "Superman"), + new Answer(3, "Stargate"))); + response3 = new SurveyResponse(19, true, Arrays.asList(new Answer(1, "Um, how am I supposed to know?"), + new Answer(2, "Me"), new Answer(3, "Last question, can I go now?"))); + response4 = new SurveyResponse(4, false, null); + } + + /** + * Tests the write() method with a normal bean writer and no processors. + */ + @Test + public void testWriteWithBeanWriter() throws IOException { + testWrite(beanWriter, false, false); + } + + /** + * Tests the write() method with a normal bean writer and processors. + */ + @Test + public void testWriteWithBeanWriterUsingProcessors() throws IOException { + testWrite(beanWriter, true, false); + } + + /** + * Tests the write() method with a bean writer using a custom DozerBeanMapper and no processors. + */ + @Test + public void testWriteWithBeanWriterCustomMapper() throws IOException { + testWrite(beanWriterWithMapper, false, false); + } + + /** + * Tests the write() method with a bean writer using a custom DozerBeanMapper and processors. + */ + @Test + public void testWriteWithBeanWriterCustomMapperUsingProcessors() throws IOException { + testWrite(beanWriterWithMapper, true, false); + } + + /** + * Tests the write() method with a bean writer using a custom DozerBeanMapper and no processors. + */ + @Test + public void testWriteWithBeanWriterConfiguredMapper() throws IOException { + testWrite(beanWriterWithConfiguredMapper, false, true); + } + + /** + * Tests the write() method with a bean writer using a custom DozerBeanMapper and processors. + */ + @Test + public void testWriteWithBeanWriterConfiguredMapperUsingProcessors() throws IOException { + testWrite(beanWriterWithConfiguredMapper, true, true); + } + + /** + * Tests the write() methods with the supplied writer, with or without using processors. + * + * @param beanWriter + * the dozer bean writer to use for the tests + * @param useProcessors + * whether to use processors for the test + * @param configured + * whether the writer is already configured + * @throws IOException + */ + private void testWrite(final CsvDozerBeanWriter beanWriter, final boolean useProcessors, final boolean configured) + throws IOException { + + if (!configured){ + beanWriter.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING); + } + + beanWriter.writeHeader("age", "consentGiven", "questionNo1", "answer1", "questionNo2", "answer2", + "questionNo3", "answer3"); + + if( useProcessors ) { + beanWriter.write(response1, PROCESSORS); + beanWriter.write(response2, PROCESSORS); + beanWriter.write(response3, PROCESSORS); + beanWriter.write(response4, PROCESSORS); + beanWriter.flush(); + assertEquals(PROCESSORS_CSV, writer.toString()); + + } else { + beanWriter.write(response1); + beanWriter.write(response2); + beanWriter.write(response3); + beanWriter.write(response4); + beanWriter.flush(); + assertEquals(CSV, writer.toString()); + } + + } + + /** + * Tests all of the constructors with null values (should throw an Exception). + */ + @Test + public void testConstructorsWithNulls() { + + // constructor one - null Writer + try { + new CsvDozerBeanWriter((Writer) null, PREFS); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor one - null prefs + try { + new CsvDozerBeanWriter(writer, null); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor two - null Writer + try { + new CsvDozerBeanWriter((Writer) null, PREFS, beanMapper); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor two - null prefs + try { + new CsvDozerBeanWriter(writer, null, beanMapper); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + // constructor two - null dozerBeanMapper + try { + new CsvDozerBeanWriter(writer, PREFS, null); + fail("should have thrown NullPointerException"); + } + catch(NullPointerException e) {} + + } + + /** + * Tests the configureBeanMapping() method with a null clazz (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testConfigureBeanMappingWithNullClazz() { + beanWriter.configureBeanMapping(null, FIELD_MAPPING); + } + + /** + * Tests the configureBeanMapping() method with a null fieldMapping array (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testConfigureBeanMappingWithNullFieldMapping() { + beanWriter.configureBeanMapping(SurveyResponse.class, null); + } + + /** + * Tests the configureBeanMapping() method with a null fieldMapping element (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testConfigureBeanMappingWithNullFieldMappingElement() { + beanWriter.configureBeanMapping(SurveyResponse.class, new String[] { "age", null, "consentGiven" }); + } + + /** + * Tests the write() method with a null clazz (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testWriteWithNullClazz() throws IOException { + beanWriter.write(null); + } + + /** + * Tests the write() method (with processors) with a null clazz (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testWriteWithProcessorsWithNullClazz() throws IOException { + beanWriter.write(null, PROCESSORS); + } + + /** + * Tests the write() method (with processors) with a null cell processor array (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testWriteWithProcessorsWithNullProcessors() throws IOException { + beanWriter.write(SurveyResponse.class, (CellProcessor[]) null); + } + +} diff --git a/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/Answer.java b/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/Answer.java index 799f2e73..4f637221 100644 --- a/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/Answer.java +++ b/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/Answer.java @@ -1,56 +1,56 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock.dozer; - -/** - * An individual survey answer. - */ -public class Answer { - - private Integer questionNo; - - private String answer; - - public Answer() { - } - - public Answer(final Integer questionNo, final String answer) { - this.questionNo = questionNo; - this.answer = answer; - } - - public Integer getQuestionNo() { - return questionNo; - } - - public void setQuestionNo(Integer questionNo) { - this.questionNo = questionNo; - } - - public String getAnswer() { - return answer; - } - - public void setAnswer(String answer) { - this.answer = answer; - } - - @Override - public String toString() { - return String.format("Answer [questionNo=%s, answer=%s]", questionNo, answer); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock.dozer; + +/** + * An individual survey answer. + */ +public class Answer { + + private Integer questionNo; + + private String answer; + + public Answer() { + } + + public Answer(final Integer questionNo, final String answer) { + this.questionNo = questionNo; + this.answer = answer; + } + + public Integer getQuestionNo() { + return questionNo; + } + + public void setQuestionNo(Integer questionNo) { + this.questionNo = questionNo; + } + + public String getAnswer() { + return answer; + } + + public void setAnswer(String answer) { + this.answer = answer; + } + + @Override + public String toString() { + return String.format("Answer [questionNo=%s, answer=%s]", questionNo, answer); + } + +} diff --git a/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/SurveyResponse.java b/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/SurveyResponse.java index 72e52cac..9ae53a47 100644 --- a/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/SurveyResponse.java +++ b/super-csv-dozer/src/test/java/org/supercsv/mock/dozer/SurveyResponse.java @@ -1,69 +1,69 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock.dozer; - -import java.util.List; - -/** - * A person's response to a survey. - */ -public class SurveyResponse { - - private Integer age; - - private Boolean consentGiven; - - private List answers; - - public SurveyResponse() { - } - - public SurveyResponse(final Integer age, final Boolean consentGiven, final List answers) { - this.age = age; - this.consentGiven = consentGiven; - this.answers = answers; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public Boolean getConsentGiven() { - return consentGiven; - } - - public void setConsentGiven(Boolean consentGiven) { - this.consentGiven = consentGiven; - } - - public List getAnswers() { - return answers; - } - - public void setAnswers(List answers) { - this.answers = answers; - } - - @Override - public String toString() { - return String.format("SurveyResponse [age=%s, consentGiven=%s, answers=%s]", age, consentGiven, answers); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock.dozer; + +import java.util.List; + +/** + * A person's response to a survey. + */ +public class SurveyResponse { + + private Integer age; + + private Boolean consentGiven; + + private List answers; + + public SurveyResponse() { + } + + public SurveyResponse(final Integer age, final Boolean consentGiven, final List answers) { + this.age = age; + this.consentGiven = consentGiven; + this.answers = answers; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Boolean getConsentGiven() { + return consentGiven; + } + + public void setConsentGiven(Boolean consentGiven) { + this.consentGiven = consentGiven; + } + + public List getAnswers() { + return answers; + } + + public void setAnswers(List answers) { + this.answers = answers; + } + + @Override + public String toString() { + return String.format("SurveyResponse [age=%s, consentGiven=%s, answers=%s]", age, consentGiven, answers); + } + +} diff --git a/super-csv-dozer/src/test/resources/reference.xml b/super-csv-dozer/src/test/resources/reference.xml index b71dbbe5..ec934027 100644 --- a/super-csv-dozer/src/test/resources/reference.xml +++ b/super-csv-dozer/src/test/resources/reference.xml @@ -1,97 +1,97 @@ - - - - - - - org.supercsv.io.dozer.CsvDozerBeanData - org.supercsv.mock.dozer.SurveyResponse - - columns[0] - age - - - columns[1] - consentGiven - - - columns[2] - answers[0].questionNo - - - columns[3] - answers[0].answer - - - columns[4] - answers[1].questionNo - - - columns[5] - answers[1].answer - - - columns[6] - answers[2].questionNo - - - columns[7] - answers[2].answer - - - - - - org.supercsv.mock.dozer.SurveyResponse - org.supercsv.io.dozer.CsvDozerBeanData - - age - columns[0] - - - consentGiven - columns[1] - - - answers[0].questionNo - columns[2] - - - answers[0].answer - columns[3] - - - answers[1].questionNo - columns[4] - - - answers[1].answer - columns[5] - - - answers[2].questionNo - columns[6] - - - answers[2].answer - columns[7] - - - + + + + + + + org.supercsv.io.dozer.CsvDozerBeanData + org.supercsv.mock.dozer.SurveyResponse + + columns[0] + age + + + columns[1] + consentGiven + + + columns[2] + answers[0].questionNo + + + columns[3] + answers[0].answer + + + columns[4] + answers[1].questionNo + + + columns[5] + answers[1].answer + + + columns[6] + answers[2].questionNo + + + columns[7] + answers[2].answer + + + + + + org.supercsv.mock.dozer.SurveyResponse + org.supercsv.io.dozer.CsvDozerBeanData + + age + columns[0] + + + consentGiven + columns[1] + + + answers[0].questionNo + columns[2] + + + answers[0].answer + columns[3] + + + answers[1].questionNo + columns[4] + + + answers[1].answer + columns[5] + + + answers[2].questionNo + columns[6] + + + answers[2].answer + columns[7] + + + \ No newline at end of file diff --git a/super-csv-dozer/src/test/resources/surveyresponses.csv b/super-csv-dozer/src/test/resources/surveyresponses.csv index 83abc82d..1ded5866 100644 --- a/super-csv-dozer/src/test/resources/surveyresponses.csv +++ b/super-csv-dozer/src/test/resources/surveyresponses.csv @@ -1,4 +1,4 @@ -age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3 -18,Y,1,Twelve,2,Albert Einstein,3,Big Bang Theory -,Y,1,Thirteen,2,Nikola Tesla,3,Stargate -42,N,1,,2,Carl Sagan,3,Star Wars +age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3 +18,Y,1,Twelve,2,Albert Einstein,3,Big Bang Theory +,Y,1,Thirteen,2,Nikola Tesla,3,Stargate +42,N,1,,2,Carl Sagan,3,Star Wars diff --git a/super-csv/.classpath b/super-csv/.classpath index b8524985..6d2353b2 100644 --- a/super-csv/.classpath +++ b/super-csv/.classpath @@ -1,14 +1,14 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/super-csv/.project b/super-csv/.project index 6bf746d0..b8265fb5 100644 --- a/super-csv/.project +++ b/super-csv/.project @@ -1,14 +1,14 @@ - - - super-csv - Super CSV is a fast, programmer-friendly, free CSV package for Java. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. - - - - org.eclipse.jdt.core.javabuilder - - - - org.eclipse.jdt.core.javanature - + + + super-csv + Super CSV is a fast, programmer-friendly, free CSV package for Java. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. + + + + org.eclipse.jdt.core.javabuilder + + + + org.eclipse.jdt.core.javanature + \ No newline at end of file diff --git a/super-csv/.settings/org.eclipse.core.resources.prefs b/super-csv/.settings/org.eclipse.core.resources.prefs index 4c28b1a8..f9fe3459 100644 --- a/super-csv/.settings/org.eclipse.core.resources.prefs +++ b/super-csv/.settings/org.eclipse.core.resources.prefs @@ -1,4 +1,4 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/test/java=UTF-8 -encoding/=UTF-8 +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/super-csv/.settings/org.eclipse.jdt.core.prefs b/super-csv/.settings/org.eclipse.jdt.core.prefs index 5d2fa294..e8bc69f0 100644 --- a/super-csv/.settings/org.eclipse.jdt.core.prefs +++ b/super-csv/.settings/org.eclipse.jdt.core.prefs @@ -1,294 +1,294 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.5 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=66 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=20 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=true -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true -org.eclipse.jdt.core.formatter.comment.format_block_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=true -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert -org.eclipse.jdt.core.formatter.comment.line_length=120 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=1 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=true -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=true -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=120 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=false -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=66 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=20 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=true +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=120 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=1 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=true +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=120 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/super-csv/.settings/org.eclipse.jdt.ui.prefs b/super-csv/.settings/org.eclipse.jdt.ui.prefs index 6957d37b..691ecf5d 100644 --- a/super-csv/.settings/org.eclipse.jdt.ui.prefs +++ b/super-csv/.settings/org.eclipse.jdt.ui.prefs @@ -1,57 +1,57 @@ -#Wed Jan 04 13:56:57 EST 2012 -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=true -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_methods=false -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_missing_override_annotations_interface_methods=true -cleanup.add_serial_version_id=true -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=false -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_to_enhanced_for_loop=true -cleanup.correct_indentation=false -cleanup.format_source_code=true -cleanup.format_source_code_changes_only=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=true -cleanup.make_private_fields_final=true -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=true -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=true -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_trailing_whitespaces=true -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=false -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.sort_members=true -cleanup.sort_members_all=false -cleanup.use_blocks=true -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_parentheses_in_expressions=true -cleanup.use_this_for_non_static_field_access=false -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=false -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup_profile=_supercsv_cleanup -cleanup_settings_version=2 -eclipse.preferences.version=1 -formatter_profile=_supercsv -formatter_settings_version=12 +#Wed Jan 04 13:56:57 EST 2012 +cleanup.add_default_serial_version_id=true +cleanup.add_generated_serial_version_id=false +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=true +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=false +cleanup.always_use_this_for_non_static_method_access=false +cleanup.convert_to_enhanced_for_loop=true +cleanup.correct_indentation=false +cleanup.format_source_code=true +cleanup.format_source_code_changes_only=false +cleanup.make_local_variable_final=true +cleanup.make_parameters_final=true +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=true +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=true +cleanup.qualify_static_field_accesses_with_declaring_class=false +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.remove_private_constructors=true +cleanup.remove_trailing_whitespaces=true +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=true +cleanup.sort_members_all=false +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_parentheses_in_expressions=true +cleanup.use_this_for_non_static_field_access=false +cleanup.use_this_for_non_static_field_access_only_if_necessary=true +cleanup.use_this_for_non_static_method_access=false +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup_profile=_supercsv_cleanup +cleanup_settings_version=2 +eclipse.preferences.version=1 +formatter_profile=_supercsv +formatter_settings_version=12 diff --git a/super-csv/pom.xml b/super-csv/pom.xml index 340d5ac6..4c35719d 100644 --- a/super-csv/pom.xml +++ b/super-csv/pom.xml @@ -1,56 +1,56 @@ - - - - - 4.0.0 - - - net.sf.supercsv - super-csv-parent - 2.0.2-SNAPSHOT - - - super-csv - Super CSV Core - Super CSV is a fast, programmer-friendly, free CSV package for Java - jar - - - - - maven-assembly-plugin - - - create-assembly - package - - single - - - - src/assembly/assembly.xml - - - - - - - - - - + + + + + 4.0.0 + + + net.sf.supercsv + super-csv-parent + 2.0.2-SNAPSHOT + + + super-csv + Super CSV Core + Super CSV is a fast, programmer-friendly, free CSV package for Java + jar + + + + + maven-assembly-plugin + + + create-assembly + package + + single + + + + src/assembly/assembly.xml + + + + + + + + + + \ No newline at end of file diff --git a/super-csv/src/assembly/assembly.xml b/super-csv/src/assembly/assembly.xml index 554e23d3..a8d18aaf 100644 --- a/super-csv/src/assembly/assembly.xml +++ b/super-csv/src/assembly/assembly.xml @@ -1,21 +1,21 @@ - - - bin - - zip - - false - - - - target - - - *.jar - - - + + + bin + + zip + + false + + + + target + + + *.jar + + + \ No newline at end of file diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/CellProcessorAdaptor.java b/super-csv/src/main/java/org/supercsv/cellprocessor/CellProcessorAdaptor.java index 7aed3090..d07709c6 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/CellProcessorAdaptor.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/CellProcessorAdaptor.java @@ -1,120 +1,120 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Abstract super class containing shared behaviour of all cell processors. Processors are linked together in a linked - * list. The end element of this list should always be an instance of NullObjectPattern. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public abstract class CellProcessorAdaptor implements CellProcessor { - - /** the next processor in the chain */ - protected final CellProcessor next; - - /** - * Constructor used by CellProcessors to indicate that they are the last processor in the chain. - */ - protected CellProcessorAdaptor() { - super(); - this.next = NullObjectPattern.INSTANCE; - } - - /** - * Constructor used by CellProcessors that require CellProcessor chaining (further processing is required). - * - * @param next - * the next CellProcessor in the chain - * @throws NullPointerException - * if next is null - */ - protected CellProcessorAdaptor(final CellProcessor next) { - super(); - if( next == null ) { - throw new NullPointerException("next CellProcessor should not be null"); - } - this.next = next; - } - - /** - * Checks that the input value is not null, throwing a NullInputException if it is. This method - * should be called by all processors that need to ensure the input is not null. - * - * @param value - * the input value - * @param context - * the CSV context - * @throws SuperCsvCellProcessorException - * if value is null - * @since 2.0.0 - */ - protected final void validateInputNotNull(final Object value, final CsvContext context) { - if( value == null ) { - throw new SuperCsvCellProcessorException( - "this processor does not accept null input - if the column is optional then chain an Optional() processor before this one", - context, this); - } - } - - /** - * Returns the CellProccessor's fully qualified class name. - */ - @Override - public String toString() { - return getClass().getName(); - } - - /** - * This is an implementation-specific processor and should only be used by the CellProcessorAdaptor class. - * It is the implementation of the null object pattern (it does nothing - just returns the value!) and should always - * be the last CellProcessor in the chain. It is implemented as a reusable singleton to avoid unnecessary - * object creation. - * - * @author Kasper B. Graversen - * @author James Bassett - */ - private static final class NullObjectPattern implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, - LongCellProcessor, StringCellProcessor { - - private static final NullObjectPattern INSTANCE = new NullObjectPattern(); - - /* - * This processor must not be instantiated outside of CellProcessorAdaptor. - */ - private NullObjectPattern() { - super(); - } - - /** - * {@inheritDoc} - */ - public Object execute(final Object value, final CsvContext context) { - return value; - } - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Abstract super class containing shared behaviour of all cell processors. Processors are linked together in a linked + * list. The end element of this list should always be an instance of NullObjectPattern. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public abstract class CellProcessorAdaptor implements CellProcessor { + + /** the next processor in the chain */ + protected final CellProcessor next; + + /** + * Constructor used by CellProcessors to indicate that they are the last processor in the chain. + */ + protected CellProcessorAdaptor() { + super(); + this.next = NullObjectPattern.INSTANCE; + } + + /** + * Constructor used by CellProcessors that require CellProcessor chaining (further processing is required). + * + * @param next + * the next CellProcessor in the chain + * @throws NullPointerException + * if next is null + */ + protected CellProcessorAdaptor(final CellProcessor next) { + super(); + if( next == null ) { + throw new NullPointerException("next CellProcessor should not be null"); + } + this.next = next; + } + + /** + * Checks that the input value is not null, throwing a NullInputException if it is. This method + * should be called by all processors that need to ensure the input is not null. + * + * @param value + * the input value + * @param context + * the CSV context + * @throws SuperCsvCellProcessorException + * if value is null + * @since 2.0.0 + */ + protected final void validateInputNotNull(final Object value, final CsvContext context) { + if( value == null ) { + throw new SuperCsvCellProcessorException( + "this processor does not accept null input - if the column is optional then chain an Optional() processor before this one", + context, this); + } + } + + /** + * Returns the CellProccessor's fully qualified class name. + */ + @Override + public String toString() { + return getClass().getName(); + } + + /** + * This is an implementation-specific processor and should only be used by the CellProcessorAdaptor class. + * It is the implementation of the null object pattern (it does nothing - just returns the value!) and should always + * be the last CellProcessor in the chain. It is implemented as a reusable singleton to avoid unnecessary + * object creation. + * + * @author Kasper B. Graversen + * @author James Bassett + */ + private static final class NullObjectPattern implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, + LongCellProcessor, StringCellProcessor { + + private static final NullObjectPattern INSTANCE = new NullObjectPattern(); + + /* + * This processor must not be instantiated outside of CellProcessorAdaptor. + */ + private NullObjectPattern() { + super(); + } + + /** + * {@inheritDoc} + */ + public Object execute(final Object value, final CsvContext context) { + return value; + } + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ConvertNullTo.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ConvertNullTo.java index 2e32bef8..79d94864 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ConvertNullTo.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ConvertNullTo.java @@ -1,85 +1,85 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.util.CsvContext; - -/** - * This processor returns a specified default value if the input is null. This is handy when writing partially - * filled beans, maps and arrays, as for each column a default value can be specified. - *

- * To return the String "" when a null is encountered use - * new ConvertNullTo("\"\""); - * - *

- * If you need further processing of the value in case the value is not null, you can link the processor with - * other processors such as - * new ConvertNullTo("\"\"", new Truncate(3)) - * - * - * @since 1.20 - * @author Kasper B. Graversen - */ -public class ConvertNullTo extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, - DoubleCellProcessor, LongCellProcessor, StringCellProcessor { - - private final Object returnValue; - - /** - * Constructs a new ConvertNullTo processor, which returns a specified default value if the input is - * null. - * - * @param returnValue - * the value to return if the input is null - */ - public ConvertNullTo(final Object returnValue) { - super(); - this.returnValue = returnValue; - } - - /** - * Constructs a new ConvertNullTo processor, which returns a specified default value if the input is - * null. If the input is not null, then the next processor is executed. - * - * @param returnValue - * the value to return if the input is null - * @param next - * the next CellProcessor in the chain - * @throws NullPointerException - * if next is null - */ - public ConvertNullTo(final Object returnValue, final CellProcessor next) { - super(next); - this.returnValue = returnValue; - } - - /** - * {@inheritDoc} - */ - public Object execute(final Object value, final CsvContext context) { - if( value == null ) { - return returnValue; - } - - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.util.CsvContext; + +/** + * This processor returns a specified default value if the input is null. This is handy when writing partially + * filled beans, maps and arrays, as for each column a default value can be specified. + *

+ * To return the String "" when a null is encountered use + * new ConvertNullTo("\"\""); + * + *

+ * If you need further processing of the value in case the value is not null, you can link the processor with + * other processors such as + * new ConvertNullTo("\"\"", new Truncate(3)) + * + * + * @since 1.20 + * @author Kasper B. Graversen + */ +public class ConvertNullTo extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, + DoubleCellProcessor, LongCellProcessor, StringCellProcessor { + + private final Object returnValue; + + /** + * Constructs a new ConvertNullTo processor, which returns a specified default value if the input is + * null. + * + * @param returnValue + * the value to return if the input is null + */ + public ConvertNullTo(final Object returnValue) { + super(); + this.returnValue = returnValue; + } + + /** + * Constructs a new ConvertNullTo processor, which returns a specified default value if the input is + * null. If the input is not null, then the next processor is executed. + * + * @param returnValue + * the value to return if the input is null + * @param next + * the next CellProcessor in the chain + * @throws NullPointerException + * if next is null + */ + public ConvertNullTo(final Object returnValue, final CellProcessor next) { + super(next); + this.returnValue = returnValue; + } + + /** + * {@inheritDoc} + */ + public Object execute(final Object value, final CsvContext context) { + if( value == null ) { + return returnValue; + } + + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/FmtBool.java b/super-csv/src/main/java/org/supercsv/cellprocessor/FmtBool.java index ab389f0a..4c778587 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/FmtBool.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/FmtBool.java @@ -1,84 +1,84 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a Boolean into a formatted string. If you want to convert from a String to a Boolean, use the - * {@link ParseBool} processor. - * - * @since 1.50 - * @author Dominique De Vito - */ -public class FmtBool extends CellProcessorAdaptor implements BoolCellProcessor { - - private final String trueValue; - private final String falseValue; - - /** - * Constructs a new FmtBool processor, which converts a Boolean into a formatted string. - * - * @param trueValue - * the String to use if the value is true - * @param falseValue - * the String to use if the value is false - */ - public FmtBool(final String trueValue, final String falseValue) { - super(); - this.trueValue = trueValue; - this.falseValue = falseValue; - } - - /** - * Constructs a new FmtBool processor, which converts a Boolean into a formatted string, then calls the - * next processor in the chain. - * - * @param trueValue - * the String to use if the value is true - * @param falseValue - * the String to use if the value is false - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public FmtBool(final String trueValue, final String falseValue, final StringCellProcessor next) { - super(next); - this.trueValue = trueValue; - this.falseValue = falseValue; - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null or is not a Boolean - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( !(value instanceof Boolean) ) { - throw new SuperCsvCellProcessorException(Boolean.class, value, context, this); - } - - final String result = ((Boolean) value).booleanValue() ? trueValue : falseValue; - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a Boolean into a formatted string. If you want to convert from a String to a Boolean, use the + * {@link ParseBool} processor. + * + * @since 1.50 + * @author Dominique De Vito + */ +public class FmtBool extends CellProcessorAdaptor implements BoolCellProcessor { + + private final String trueValue; + private final String falseValue; + + /** + * Constructs a new FmtBool processor, which converts a Boolean into a formatted string. + * + * @param trueValue + * the String to use if the value is true + * @param falseValue + * the String to use if the value is false + */ + public FmtBool(final String trueValue, final String falseValue) { + super(); + this.trueValue = trueValue; + this.falseValue = falseValue; + } + + /** + * Constructs a new FmtBool processor, which converts a Boolean into a formatted string, then calls the + * next processor in the chain. + * + * @param trueValue + * the String to use if the value is true + * @param falseValue + * the String to use if the value is false + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public FmtBool(final String trueValue, final String falseValue, final StringCellProcessor next) { + super(next); + this.trueValue = trueValue; + this.falseValue = falseValue; + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null or is not a Boolean + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( !(value instanceof Boolean) ) { + throw new SuperCsvCellProcessorException(Boolean.class, value, context, this); + } + + final String result = ((Boolean) value).booleanValue() ? trueValue : falseValue; + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/FmtDate.java b/super-csv/src/main/java/org/supercsv/cellprocessor/FmtDate.java index 9c92dd0b..2013d710 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/FmtDate.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/FmtDate.java @@ -1,115 +1,115 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a date into a formatted string using the {@link SimpleDateFormat} class. If you want to convert from a - * String to a Date, use the {@link ParseDate} processor. - *

- * Some example date formats you can use are:
- * "dd/MM/yyyy" (formats a date as "25/12/2011")
- * "dd-MMM-yy" (formats a date as "25-Dec-11")
- * "yyyy.MM.dd.HH.mm.ss" (formats a date as "2011.12.25.08.36.33"
- * "E, dd MMM yyyy HH:mm:ss Z" (formats a date as "Tue, 25 Dec 2011 08:36:33 -0500")
- * - * @since 1.50 - * @author Dominique De Vito - * @author James Bassett - */ -public class FmtDate extends CellProcessorAdaptor implements DateCellProcessor { - - private final String dateFormat; - - /** - * Constructs a new FmtDate processor, which converts a date into a formatted string using - * SimpleDateFormat. - * - * @param dateFormat - * the date format String (see {@link SimpleDateFormat}) - * @throws NullPointerException - * if dateFormat is null - */ - public FmtDate(final String dateFormat) { - super(); - checkPreconditions(dateFormat); - this.dateFormat = dateFormat; - } - - /** - * Constructs a new FmtDate processor, which converts a date into a formatted string using - * SimpleDateFormat, then calls the next processor in the chain. - * - * @param dateFormat - * the date format String (see {@link SimpleDateFormat}) - * @param next - * the next processor in the chain - * @throws NullPointerException - * if dateFormat or next is null - */ - public FmtDate(final String dateFormat, final StringCellProcessor next) { - super(next); - checkPreconditions(dateFormat); - this.dateFormat = dateFormat; - } - - /** - * Checks the preconditions for creating a new FmtDate processor. - * - * @param dateFormat - * the date format String - * @throws NullPointerException - * if dateFormat is null - */ - private static void checkPreconditions(final String dateFormat) { - if( dateFormat == null ) { - throw new NullPointerException("dateFormat should not be null"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null or is not a Date, or if dateFormat is not a valid date format - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( !(value instanceof Date) ) { - throw new SuperCsvCellProcessorException(Date.class, value, context, this); - } - - final SimpleDateFormat formatter; - try { - formatter = new SimpleDateFormat(dateFormat); - } - catch(IllegalArgumentException e) { - throw new SuperCsvCellProcessorException(String.format("'%s' is not a valid date format", dateFormat), - context, this, e); - } - - String result = formatter.format((Date) value); - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a date into a formatted string using the {@link SimpleDateFormat} class. If you want to convert from a + * String to a Date, use the {@link ParseDate} processor. + *

+ * Some example date formats you can use are:
+ * "dd/MM/yyyy" (formats a date as "25/12/2011")
+ * "dd-MMM-yy" (formats a date as "25-Dec-11")
+ * "yyyy.MM.dd.HH.mm.ss" (formats a date as "2011.12.25.08.36.33"
+ * "E, dd MMM yyyy HH:mm:ss Z" (formats a date as "Tue, 25 Dec 2011 08:36:33 -0500")
+ * + * @since 1.50 + * @author Dominique De Vito + * @author James Bassett + */ +public class FmtDate extends CellProcessorAdaptor implements DateCellProcessor { + + private final String dateFormat; + + /** + * Constructs a new FmtDate processor, which converts a date into a formatted string using + * SimpleDateFormat. + * + * @param dateFormat + * the date format String (see {@link SimpleDateFormat}) + * @throws NullPointerException + * if dateFormat is null + */ + public FmtDate(final String dateFormat) { + super(); + checkPreconditions(dateFormat); + this.dateFormat = dateFormat; + } + + /** + * Constructs a new FmtDate processor, which converts a date into a formatted string using + * SimpleDateFormat, then calls the next processor in the chain. + * + * @param dateFormat + * the date format String (see {@link SimpleDateFormat}) + * @param next + * the next processor in the chain + * @throws NullPointerException + * if dateFormat or next is null + */ + public FmtDate(final String dateFormat, final StringCellProcessor next) { + super(next); + checkPreconditions(dateFormat); + this.dateFormat = dateFormat; + } + + /** + * Checks the preconditions for creating a new FmtDate processor. + * + * @param dateFormat + * the date format String + * @throws NullPointerException + * if dateFormat is null + */ + private static void checkPreconditions(final String dateFormat) { + if( dateFormat == null ) { + throw new NullPointerException("dateFormat should not be null"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null or is not a Date, or if dateFormat is not a valid date format + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( !(value instanceof Date) ) { + throw new SuperCsvCellProcessorException(Date.class, value, context, this); + } + + final SimpleDateFormat formatter; + try { + formatter = new SimpleDateFormat(dateFormat); + } + catch(IllegalArgumentException e) { + throw new SuperCsvCellProcessorException(String.format("'%s' is not a valid date format", dateFormat), + context, this, e); + } + + String result = formatter.format((Date) value); + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/FmtNumber.java b/super-csv/src/main/java/org/supercsv/cellprocessor/FmtNumber.java index 7dc3af1a..799f7c3e 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/FmtNumber.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/FmtNumber.java @@ -1,180 +1,180 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import java.text.DecimalFormat; - -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a double into a formatted string using the {@link DecimalFormat} class and the default locale. This is - * useful, when you need to show numbers with a specific number of digits. - *

- * Please be aware that the constructors that use DecimalFormat are not thread-safe, so it is generally better - * to use the constructors that accept a date format String. - *

- * In the format string, the following characters are defined as :
- * - *

- * 0   - means Digit
- * #   - means Digit, zero shows as absent (works only as zero padding on the right hand side of the number)
- * .   - means Decimal separator or monetary decimal separator
- * -   - means Minus sign
- * ,   - means Grouping separator
- * 
- * - *
- * If you want to convert from a String to a decimal, use the {@link ParseDouble} or {@link ParseBigDecimal} processor. - * - * @since 1.50 - * @author Kasper B. Graversen - * @author James Bassett - */ -public class FmtNumber extends CellProcessorAdaptor implements DoubleCellProcessor, LongCellProcessor { - - /** the decimal format string */ - private final String decimalFormat; - - /** the decimal format object - not thread safe */ - private final DecimalFormat formatter; - - /** - * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied - * decimal format String. This constructor is thread-safe. - * - * @param decimalFormat - * the decimal format String (see {@link DecimalFormat}) - * @throws NullPointerException - * if decimalFormat is null - */ - public FmtNumber(final String decimalFormat) { - super(); - checkPreconditions(decimalFormat); - this.decimalFormat = decimalFormat; - this.formatter = null; - } - - /** - * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied - * decimal format String, then calls the next processor in the chain. This constructor is thread-safe. - * - * @param decimalFormat - * the decimal format String (see {@link DecimalFormat}) - * @param next - * the next processor in the chain - * @throws NullPointerException - * if decimalFormat or next is null - */ - public FmtNumber(final String decimalFormat, final StringCellProcessor next) { - super(next); - checkPreconditions(decimalFormat); - this.decimalFormat = decimalFormat; - this.formatter = null; - } - - /** - * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied - * decimal format. This constructor is not thread-safe. - * - * @param formatter - * the DecimalFormat - * @throws NullPointerException - * if formatter is null - */ - public FmtNumber(final DecimalFormat formatter) { - super(); - checkPreconditions(formatter); - this.formatter = formatter; - this.decimalFormat = null; - } - - /** - * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied - * decimal format, then calls the next processor in the chain. This constructor is not thread-safe. - * - * @param formatter - * the DecimalFormat - * @param next - * the next processor in the chain - * @throws NullPointerException - * if formatter or next is null - */ - public FmtNumber(final DecimalFormat formatter, final StringCellProcessor next) { - super(next); - checkPreconditions(formatter); - this.formatter = formatter; - this.decimalFormat = null; - } - - /** - * Checks the preconditions for creating a new FmtNumber processor with a date format String. - * - * @param dateFormat - * the date format String - * @throws NullPointerException - * if dateFormat is null - */ - private static void checkPreconditions(final String dateFormat) { - if( dateFormat == null ) { - throw new NullPointerException("dateFormat should not be null"); - } - } - - /** - * Checks the preconditions for creating a new FmtNumber processor with a DecimalFormat. - * - * @param formatter - * the DecimalFormat - * @throws NullPointerException - * if formatter is null - */ - private static void checkPreconditions(final DecimalFormat formatter) { - if( formatter == null ) { - throw new NullPointerException("formatter should not be null"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null or not a Number, or if an invalid decimalFormat String was supplied - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( !(value instanceof Number) ) { - throw new SuperCsvCellProcessorException(Number.class, value, context, this); - } - - // create a new DecimalFormat if one is not supplied - final DecimalFormat decimalFormatter; - try { - decimalFormatter = formatter != null ? formatter : new DecimalFormat(decimalFormat); - } - catch(IllegalArgumentException e) { - throw new SuperCsvCellProcessorException( - String.format("'%s' is not a valid decimal format", decimalFormat), context, this, e); - } - - final String result = decimalFormatter.format(value); - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import java.text.DecimalFormat; + +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a double into a formatted string using the {@link DecimalFormat} class and the default locale. This is + * useful, when you need to show numbers with a specific number of digits. + *

+ * Please be aware that the constructors that use DecimalFormat are not thread-safe, so it is generally better + * to use the constructors that accept a date format String. + *

+ * In the format string, the following characters are defined as :
+ * + *

+ * 0   - means Digit
+ * #   - means Digit, zero shows as absent (works only as zero padding on the right hand side of the number)
+ * .   - means Decimal separator or monetary decimal separator
+ * -   - means Minus sign
+ * ,   - means Grouping separator
+ * 
+ * + *
+ * If you want to convert from a String to a decimal, use the {@link ParseDouble} or {@link ParseBigDecimal} processor. + * + * @since 1.50 + * @author Kasper B. Graversen + * @author James Bassett + */ +public class FmtNumber extends CellProcessorAdaptor implements DoubleCellProcessor, LongCellProcessor { + + /** the decimal format string */ + private final String decimalFormat; + + /** the decimal format object - not thread safe */ + private final DecimalFormat formatter; + + /** + * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied + * decimal format String. This constructor is thread-safe. + * + * @param decimalFormat + * the decimal format String (see {@link DecimalFormat}) + * @throws NullPointerException + * if decimalFormat is null + */ + public FmtNumber(final String decimalFormat) { + super(); + checkPreconditions(decimalFormat); + this.decimalFormat = decimalFormat; + this.formatter = null; + } + + /** + * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied + * decimal format String, then calls the next processor in the chain. This constructor is thread-safe. + * + * @param decimalFormat + * the decimal format String (see {@link DecimalFormat}) + * @param next + * the next processor in the chain + * @throws NullPointerException + * if decimalFormat or next is null + */ + public FmtNumber(final String decimalFormat, final StringCellProcessor next) { + super(next); + checkPreconditions(decimalFormat); + this.decimalFormat = decimalFormat; + this.formatter = null; + } + + /** + * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied + * decimal format. This constructor is not thread-safe. + * + * @param formatter + * the DecimalFormat + * @throws NullPointerException + * if formatter is null + */ + public FmtNumber(final DecimalFormat formatter) { + super(); + checkPreconditions(formatter); + this.formatter = formatter; + this.decimalFormat = null; + } + + /** + * Constructs a new FmtNumber processor, which converts a double into a formatted string using the supplied + * decimal format, then calls the next processor in the chain. This constructor is not thread-safe. + * + * @param formatter + * the DecimalFormat + * @param next + * the next processor in the chain + * @throws NullPointerException + * if formatter or next is null + */ + public FmtNumber(final DecimalFormat formatter, final StringCellProcessor next) { + super(next); + checkPreconditions(formatter); + this.formatter = formatter; + this.decimalFormat = null; + } + + /** + * Checks the preconditions for creating a new FmtNumber processor with a date format String. + * + * @param dateFormat + * the date format String + * @throws NullPointerException + * if dateFormat is null + */ + private static void checkPreconditions(final String dateFormat) { + if( dateFormat == null ) { + throw new NullPointerException("dateFormat should not be null"); + } + } + + /** + * Checks the preconditions for creating a new FmtNumber processor with a DecimalFormat. + * + * @param formatter + * the DecimalFormat + * @throws NullPointerException + * if formatter is null + */ + private static void checkPreconditions(final DecimalFormat formatter) { + if( formatter == null ) { + throw new NullPointerException("formatter should not be null"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null or not a Number, or if an invalid decimalFormat String was supplied + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( !(value instanceof Number) ) { + throw new SuperCsvCellProcessorException(Number.class, value, context, this); + } + + // create a new DecimalFormat if one is not supplied + final DecimalFormat decimalFormatter; + try { + decimalFormatter = formatter != null ? formatter : new DecimalFormat(decimalFormat); + } + catch(IllegalArgumentException e) { + throw new SuperCsvCellProcessorException( + String.format("'%s' is not a valid decimal format", decimalFormat), context, this, e); + } + + final String result = decimalFormatter.format(value); + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/HashMapper.java b/super-csv/src/main/java/org/supercsv/cellprocessor/HashMapper.java index e6f69a92..e784fe0a 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/HashMapper.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/HashMapper.java @@ -1,157 +1,157 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import java.util.Map; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Maps from one object to another, by looking up a Map with the input as the key, and returning its - * corresponding value. - * - * @since 1.50 - * @author Dominique De Vito - * @author James Bassett - */ -public class HashMapper extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, - DoubleCellProcessor, LongCellProcessor, StringCellProcessor { - - private final Map mapping; - private final Object defaultValue; - - /** - * Constructs a new HashMapper processor, which maps from one object to another, by looking up a - * Map with the input as the key, and returning its corresponding value. If no mapping is found, then - * null is returned. - * - * @param mapping - * the Map - * @throws NullPointerException - * if mapping is null - * @throws IllegalArgumentException - * if mapping is empty - */ - public HashMapper(final Map mapping) { - this(mapping, (Object) null); - } - - /** - * Constructs a new HashMapper processor, which maps from one object to another, by looking up a - * Map with the input as the key, and returning its corresponding value. If no mapping is found, then the - * supplied default value is returned. - * - * @param mapping - * the Map - * @param defaultValue - * the value to return if no mapping is found - * @throws NullPointerException - * if mapping is null - * @throws IllegalArgumentException - * if mapping is empty - */ - public HashMapper(final Map mapping, final Object defaultValue) { - super(); - checkPreconditions(mapping); - this.mapping = mapping; - this.defaultValue = defaultValue; - - } - - /** - * Constructs a new HashMapper processor, which maps from one object to another, by looking up a - * Map with the input as the key, and returning its corresponding value. If no mapping is found, then - * null is returned. Regardless of whether a mapping is found, the next processor in the chain will be - * called. - * - * @param mapping - * the Map - * @param next - * the next processor in the chain - * @throws NullPointerException - * if mapping or next is null - * @throws IllegalArgumentException - * if mapping is empty - */ - public HashMapper(final Map mapping, final BoolCellProcessor next) { - this(mapping, null, next); - } - - /** - * Constructs a new HashMapper processor, which maps from one object to another, by looking up a - * Map with the input as the key, and returning its corresponding value. If no mapping is found, then the - * supplied default value is returned. Regardless of whether a mapping is found, the next processor in the chain - * will be called. - * - * @param mapping - * the Map - * @param defaultValue - * the value to return if no mapping is found - * @param next - * the next processor in the chain - * @throws NullPointerException - * if mapping or next is null - * @throws IllegalArgumentException - * if mapping is empty - */ - public HashMapper(final Map mapping, final Object defaultValue, final BoolCellProcessor next) { - super(next); - checkPreconditions(mapping); - this.mapping = mapping; - this.defaultValue = defaultValue; - } - - /** - * Checks the preconditions for creating a new HashMapper processor. - * - * @param mapping - * the Map - * @throws NullPointerException - * if mapping is null - * @throws IllegalArgumentException - * if mapping is empty - */ - private static void checkPreconditions(final Map mapping) { - if( mapping == null ) { - throw new NullPointerException("mapping should not be null"); - } else if( mapping.isEmpty() ) { - throw new IllegalArgumentException("mapping should not be empty"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - Object result = mapping.get(value); - if( result == null ) { - result = defaultValue; - } - - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import java.util.Map; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Maps from one object to another, by looking up a Map with the input as the key, and returning its + * corresponding value. + * + * @since 1.50 + * @author Dominique De Vito + * @author James Bassett + */ +public class HashMapper extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, + DoubleCellProcessor, LongCellProcessor, StringCellProcessor { + + private final Map mapping; + private final Object defaultValue; + + /** + * Constructs a new HashMapper processor, which maps from one object to another, by looking up a + * Map with the input as the key, and returning its corresponding value. If no mapping is found, then + * null is returned. + * + * @param mapping + * the Map + * @throws NullPointerException + * if mapping is null + * @throws IllegalArgumentException + * if mapping is empty + */ + public HashMapper(final Map mapping) { + this(mapping, (Object) null); + } + + /** + * Constructs a new HashMapper processor, which maps from one object to another, by looking up a + * Map with the input as the key, and returning its corresponding value. If no mapping is found, then the + * supplied default value is returned. + * + * @param mapping + * the Map + * @param defaultValue + * the value to return if no mapping is found + * @throws NullPointerException + * if mapping is null + * @throws IllegalArgumentException + * if mapping is empty + */ + public HashMapper(final Map mapping, final Object defaultValue) { + super(); + checkPreconditions(mapping); + this.mapping = mapping; + this.defaultValue = defaultValue; + + } + + /** + * Constructs a new HashMapper processor, which maps from one object to another, by looking up a + * Map with the input as the key, and returning its corresponding value. If no mapping is found, then + * null is returned. Regardless of whether a mapping is found, the next processor in the chain will be + * called. + * + * @param mapping + * the Map + * @param next + * the next processor in the chain + * @throws NullPointerException + * if mapping or next is null + * @throws IllegalArgumentException + * if mapping is empty + */ + public HashMapper(final Map mapping, final BoolCellProcessor next) { + this(mapping, null, next); + } + + /** + * Constructs a new HashMapper processor, which maps from one object to another, by looking up a + * Map with the input as the key, and returning its corresponding value. If no mapping is found, then the + * supplied default value is returned. Regardless of whether a mapping is found, the next processor in the chain + * will be called. + * + * @param mapping + * the Map + * @param defaultValue + * the value to return if no mapping is found + * @param next + * the next processor in the chain + * @throws NullPointerException + * if mapping or next is null + * @throws IllegalArgumentException + * if mapping is empty + */ + public HashMapper(final Map mapping, final Object defaultValue, final BoolCellProcessor next) { + super(next); + checkPreconditions(mapping); + this.mapping = mapping; + this.defaultValue = defaultValue; + } + + /** + * Checks the preconditions for creating a new HashMapper processor. + * + * @param mapping + * the Map + * @throws NullPointerException + * if mapping is null + * @throws IllegalArgumentException + * if mapping is empty + */ + private static void checkPreconditions(final Map mapping) { + if( mapping == null ) { + throw new NullPointerException("mapping should not be null"); + } else if( mapping.isEmpty() ) { + throw new IllegalArgumentException("mapping should not be empty"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + Object result = mapping.get(value); + if( result == null ) { + result = defaultValue; + } + + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/Optional.java b/super-csv/src/main/java/org/supercsv/cellprocessor/Optional.java index d4faf68b..6bcc85c9 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/Optional.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/Optional.java @@ -1,52 +1,52 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.CellProcessor; - -/** - * This processor is used to indicate that a cell is optional, and will avoid executing further processors if it - * encounters null. It is a simple customization of ConvertNullTo. - *

- * Prior to version 2.0.0, this processor returned null for empty String (""), but was updated because - * Tokenizer now reads empty columns as null. It also means that Optional can now be used when writing as well - * (instead of using {@code ConvertNullTo("")}). - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class Optional extends ConvertNullTo { - - /** - * Constructs a new Optional processor, which when encountering null will return null, - * for all other values it will return the value unchanged. - */ - public Optional() { - super(null); - } - - /** - * Constructs a new Optional processor, which when encountering null will return null , - * for all other values it will call the next processor in the chain. - * - * @throws NullPointerException - * if next is null - */ - public Optional(final CellProcessor next) { - super(null, next); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.CellProcessor; + +/** + * This processor is used to indicate that a cell is optional, and will avoid executing further processors if it + * encounters null. It is a simple customization of ConvertNullTo. + *

+ * Prior to version 2.0.0, this processor returned null for empty String (""), but was updated because + * Tokenizer now reads empty columns as null. It also means that Optional can now be used when writing as well + * (instead of using {@code ConvertNullTo("")}). + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class Optional extends ConvertNullTo { + + /** + * Constructs a new Optional processor, which when encountering null will return null, + * for all other values it will return the value unchanged. + */ + public Optional() { + super(null); + } + + /** + * Constructs a new Optional processor, which when encountering null will return null , + * for all other values it will call the next processor in the chain. + * + * @throws NullPointerException + * if next is null + */ + public Optional(final CellProcessor next) { + super(null, next); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBigDecimal.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBigDecimal.java index 95015119..e41298ca 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBigDecimal.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBigDecimal.java @@ -1,141 +1,141 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import java.math.BigDecimal; -import java.text.DecimalFormatSymbols; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Convert a String to a BigDecimal. It uses the String constructor of BigDecimal (new BigDecimal("0.1")) as it - * yields predictable results (see {@link BigDecimal}). - *

- * If the data uses a character other than "." as a decimal separator (France uses "," for example), then use the - * constructor that accepts a DecimalFormatSymbols object, as it will convert the character to a "." before - * creating the BigDecimal. - * - * @since 1.30 - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseBigDecimal extends CellProcessorAdaptor implements StringCellProcessor { - - private static final char DEFAULT_DECIMAL_SEPARATOR = '.'; - - private final char decimalSeparator; - - /** - * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal. - */ - public ParseBigDecimal() { - this.decimalSeparator = DEFAULT_DECIMAL_SEPARATOR; - } - - /** - * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal using the supplied - * DecimalFormatSymbols object to convert any decimal separator to a "." before creating the BigDecimal. - * - * @param symbols - * the decimal format symbols, containing the decimal separator - * @throws NullPointerException - * if symbols is null - */ - public ParseBigDecimal(final DecimalFormatSymbols symbols) { - super(); - checkPreconditions(symbols); - this.decimalSeparator = symbols.getDecimalSeparator(); - } - - /** - * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal then calls the next - * processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public ParseBigDecimal(final CellProcessor next) { - super(next); - this.decimalSeparator = DEFAULT_DECIMAL_SEPARATOR; - } - - /** - * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal using the supplied - * DecimalFormatSymbols object to convert any decimal separator to a "." before creating the BigDecimal, - * then calls the next processor in the chain. - * - * @param symbols - * the decimal format symbols, containing the decimal separator - * @param next - * the next processor in the chain - * @throws NullPointerException - * if symbols or next is null - */ - public ParseBigDecimal(final DecimalFormatSymbols symbols, final CellProcessor next) { - super(next); - checkPreconditions(symbols); - this.decimalSeparator = symbols.getDecimalSeparator(); - } - - /** - * Checks the preconditions for creating a new ParseBigDecimal processor. - * - * @param symbols - * the decimal format symbols, containing the decimal separator - * @throws NullPointerException - * if symbols is null - */ - private static void checkPreconditions(final DecimalFormatSymbols symbols) { - if( symbols == null ) { - throw new NullPointerException("symbols should not be null"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null, isn't a String, or can't be parsed as a BigDecimal - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final BigDecimal result; - if( value instanceof String ) { - final String s = (String) value; - try { - if( decimalSeparator == DEFAULT_DECIMAL_SEPARATOR ) { - result = new BigDecimal(s); - } else { - result = new BigDecimal(s.replace(decimalSeparator, DEFAULT_DECIMAL_SEPARATOR)); - } - } - catch(final NumberFormatException e) { - throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a BigDecimal", value), context, - this, e); - } - } else { - throw new SuperCsvCellProcessorException(String.class, value, context, this); - } - - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import java.math.BigDecimal; +import java.text.DecimalFormatSymbols; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Convert a String to a BigDecimal. It uses the String constructor of BigDecimal (new BigDecimal("0.1")) as it + * yields predictable results (see {@link BigDecimal}). + *

+ * If the data uses a character other than "." as a decimal separator (France uses "," for example), then use the + * constructor that accepts a DecimalFormatSymbols object, as it will convert the character to a "." before + * creating the BigDecimal. + * + * @since 1.30 + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseBigDecimal extends CellProcessorAdaptor implements StringCellProcessor { + + private static final char DEFAULT_DECIMAL_SEPARATOR = '.'; + + private final char decimalSeparator; + + /** + * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal. + */ + public ParseBigDecimal() { + this.decimalSeparator = DEFAULT_DECIMAL_SEPARATOR; + } + + /** + * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal using the supplied + * DecimalFormatSymbols object to convert any decimal separator to a "." before creating the BigDecimal. + * + * @param symbols + * the decimal format symbols, containing the decimal separator + * @throws NullPointerException + * if symbols is null + */ + public ParseBigDecimal(final DecimalFormatSymbols symbols) { + super(); + checkPreconditions(symbols); + this.decimalSeparator = symbols.getDecimalSeparator(); + } + + /** + * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal then calls the next + * processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public ParseBigDecimal(final CellProcessor next) { + super(next); + this.decimalSeparator = DEFAULT_DECIMAL_SEPARATOR; + } + + /** + * Constructs a new ParseBigDecimal processor, which converts a String to a BigDecimal using the supplied + * DecimalFormatSymbols object to convert any decimal separator to a "." before creating the BigDecimal, + * then calls the next processor in the chain. + * + * @param symbols + * the decimal format symbols, containing the decimal separator + * @param next + * the next processor in the chain + * @throws NullPointerException + * if symbols or next is null + */ + public ParseBigDecimal(final DecimalFormatSymbols symbols, final CellProcessor next) { + super(next); + checkPreconditions(symbols); + this.decimalSeparator = symbols.getDecimalSeparator(); + } + + /** + * Checks the preconditions for creating a new ParseBigDecimal processor. + * + * @param symbols + * the decimal format symbols, containing the decimal separator + * @throws NullPointerException + * if symbols is null + */ + private static void checkPreconditions(final DecimalFormatSymbols symbols) { + if( symbols == null ) { + throw new NullPointerException("symbols should not be null"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null, isn't a String, or can't be parsed as a BigDecimal + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final BigDecimal result; + if( value instanceof String ) { + final String s = (String) value; + try { + if( decimalSeparator == DEFAULT_DECIMAL_SEPARATOR ) { + result = new BigDecimal(s); + } else { + result = new BigDecimal(s.replace(decimalSeparator, DEFAULT_DECIMAL_SEPARATOR)); + } + } + catch(final NumberFormatException e) { + throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a BigDecimal", value), context, + this, e); + } + } else { + throw new SuperCsvCellProcessorException(String.class, value, context, this); + } + + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBool.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBool.java index f5443aa9..2cca264d 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBool.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseBool.java @@ -1,224 +1,224 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a String to a Boolean. - *

- * The default values for true are: "true", "1", "y", "t" - *

- * The default values for false are: "false", "0", "n", "f" - *

- * The input is converted to lowercase before comparison against the true/false values (to handle all variations of case - * in the input), so if you supply your own true/false values then ensure they are lowercase. - * - * @author Kasper B. Graversen - * @author Dominique De Vito - * @author James Bassett - * @since 1.0 - */ -public class ParseBool extends CellProcessorAdaptor implements StringCellProcessor { - - private static final String[] DEFAULT_TRUE_VALUES = new String[] { "1", "true", "t", "y" }; - private static final String[] DEFAULT_FALSE_VALUES = new String[] { "0", "false", "f", "n" }; - - private final Set trueValues = new HashSet(); - private final Set falseValues = new HashSet(); - - /** - * Constructs a new ParseBool processor, which converts a String to a Boolean using the default values. - */ - public ParseBool() { - this(DEFAULT_TRUE_VALUES, DEFAULT_FALSE_VALUES); - } - - /** - * Constructs a new ParseBool processor, which converts a String to a Boolean using the default values, - * then calls the next processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public ParseBool(final BoolCellProcessor next) { - this(DEFAULT_TRUE_VALUES, DEFAULT_FALSE_VALUES, next); - } - - /** - * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false - * values. - * - * @param trueValue - * the String which represents true - * @param falseValue - * the String which represents false - * @throws NullPointerException - * if trueValue or falseValue is null - */ - public ParseBool(final String trueValue, final String falseValue) { - super(); - checkPreconditions(trueValue, falseValue); - trueValues.add(trueValue); - falseValues.add(falseValue); - } - - /** - * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false - * values. - * - * @param trueValues - * the array of Strings which represent true - * @param falseValues - * the array of Strings which represent false - * @throws IllegalArgumentException - * if trueValues or falseValues is empty - * @throws NullPointerException - * if trueValues or falseValues is null - */ - public ParseBool(final String[] trueValues, final String[] falseValues) { - super(); - checkPreconditions(trueValues, falseValues); - Collections.addAll(this.trueValues, trueValues); - Collections.addAll(this.falseValues, falseValues); - } - - /** - * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false - * values, then calls the next processor in the chain. - * - * @param trueValue - * the String which represents true - * @param falseValue - * the String which represents false - * @param next - * the next processor in the chain - * @throws NullPointerException - * if trueValue, falseValue or next is null - */ - public ParseBool(final String trueValue, final String falseValue, final BoolCellProcessor next) { - super(next); - checkPreconditions(trueValue, falseValue); - trueValues.add(trueValue); - falseValues.add(falseValue); - } - - /** - * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false - * values, then calls the next processor in the chain. - * - * @param trueValues - * the array of Strings which represent true - * @param falseValues - * the array of Strings which represent false - * @param next - * the next processor in the chain - * @throws IllegalArgumentException - * if trueValues or falseValues is empty - * @throws NullPointerException - * if trueValues, falseValues, or next is null - */ - public ParseBool(final String[] trueValues, final String[] falseValues, final BoolCellProcessor next) { - super(next); - checkPreconditions(trueValues, falseValues); - Collections.addAll(this.trueValues, trueValues); - Collections.addAll(this.falseValues, falseValues); - } - - /** - * Checks the preconditions for constructing a new ParseBool processor. - * - * @param trueValue - * the String which represents true - * @param falseValue - * the String which represents false - * @throws NullPointerException - * if trueValue or falseValue is null - */ - private static void checkPreconditions(final String trueValue, final String falseValue) { - if( trueValue == null ) { - throw new NullPointerException("trueValue should not be null"); - } - if( falseValue == null ) { - throw new NullPointerException("falseValue should not be null"); - } - } - - /** - * Checks the preconditions for constructing a new ParseBool processor. - * - * @param trueValues - * the array of Strings which represent true - * @param falseValues - * the array of Strings which represent false - * @throws IllegalArgumentException - * if trueValues or falseValues is empty - * @throws NullPointerException - * if trueValues or falseValues is null - */ - private static void checkPreconditions(final String[] trueValues, final String[] falseValues) { - - if( trueValues == null ) { - throw new NullPointerException("trueValues should not be null"); - } else if( trueValues.length == 0 ) { - throw new IllegalArgumentException("trueValues should not be empty"); - } - - if( falseValues == null ) { - throw new NullPointerException("falseValues should not be null"); - } else if( falseValues.length == 0 ) { - throw new IllegalArgumentException("falseValues should not be empty"); - } - - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null, not a String, or can't be parsed to a Boolean - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( !(value instanceof String) ) { - throw new SuperCsvCellProcessorException(String.class, value, context, this); - } - - final String stringValue = ((String) value).toLowerCase(); - final Boolean result; - if( trueValues.contains(stringValue) ) { - result = Boolean.TRUE; - } else if( falseValues.contains(stringValue) ) { - result = Boolean.FALSE; - } else { - throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Boolean", value), - context, this); - } - - return next.execute(result, context); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a String to a Boolean. + *

+ * The default values for true are: "true", "1", "y", "t" + *

+ * The default values for false are: "false", "0", "n", "f" + *

+ * The input is converted to lowercase before comparison against the true/false values (to handle all variations of case + * in the input), so if you supply your own true/false values then ensure they are lowercase. + * + * @author Kasper B. Graversen + * @author Dominique De Vito + * @author James Bassett + * @since 1.0 + */ +public class ParseBool extends CellProcessorAdaptor implements StringCellProcessor { + + private static final String[] DEFAULT_TRUE_VALUES = new String[] { "1", "true", "t", "y" }; + private static final String[] DEFAULT_FALSE_VALUES = new String[] { "0", "false", "f", "n" }; + + private final Set trueValues = new HashSet(); + private final Set falseValues = new HashSet(); + + /** + * Constructs a new ParseBool processor, which converts a String to a Boolean using the default values. + */ + public ParseBool() { + this(DEFAULT_TRUE_VALUES, DEFAULT_FALSE_VALUES); + } + + /** + * Constructs a new ParseBool processor, which converts a String to a Boolean using the default values, + * then calls the next processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public ParseBool(final BoolCellProcessor next) { + this(DEFAULT_TRUE_VALUES, DEFAULT_FALSE_VALUES, next); + } + + /** + * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false + * values. + * + * @param trueValue + * the String which represents true + * @param falseValue + * the String which represents false + * @throws NullPointerException + * if trueValue or falseValue is null + */ + public ParseBool(final String trueValue, final String falseValue) { + super(); + checkPreconditions(trueValue, falseValue); + trueValues.add(trueValue); + falseValues.add(falseValue); + } + + /** + * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false + * values. + * + * @param trueValues + * the array of Strings which represent true + * @param falseValues + * the array of Strings which represent false + * @throws IllegalArgumentException + * if trueValues or falseValues is empty + * @throws NullPointerException + * if trueValues or falseValues is null + */ + public ParseBool(final String[] trueValues, final String[] falseValues) { + super(); + checkPreconditions(trueValues, falseValues); + Collections.addAll(this.trueValues, trueValues); + Collections.addAll(this.falseValues, falseValues); + } + + /** + * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false + * values, then calls the next processor in the chain. + * + * @param trueValue + * the String which represents true + * @param falseValue + * the String which represents false + * @param next + * the next processor in the chain + * @throws NullPointerException + * if trueValue, falseValue or next is null + */ + public ParseBool(final String trueValue, final String falseValue, final BoolCellProcessor next) { + super(next); + checkPreconditions(trueValue, falseValue); + trueValues.add(trueValue); + falseValues.add(falseValue); + } + + /** + * Constructs a new ParseBool processor, which converts a String to a Boolean using the supplied true/false + * values, then calls the next processor in the chain. + * + * @param trueValues + * the array of Strings which represent true + * @param falseValues + * the array of Strings which represent false + * @param next + * the next processor in the chain + * @throws IllegalArgumentException + * if trueValues or falseValues is empty + * @throws NullPointerException + * if trueValues, falseValues, or next is null + */ + public ParseBool(final String[] trueValues, final String[] falseValues, final BoolCellProcessor next) { + super(next); + checkPreconditions(trueValues, falseValues); + Collections.addAll(this.trueValues, trueValues); + Collections.addAll(this.falseValues, falseValues); + } + + /** + * Checks the preconditions for constructing a new ParseBool processor. + * + * @param trueValue + * the String which represents true + * @param falseValue + * the String which represents false + * @throws NullPointerException + * if trueValue or falseValue is null + */ + private static void checkPreconditions(final String trueValue, final String falseValue) { + if( trueValue == null ) { + throw new NullPointerException("trueValue should not be null"); + } + if( falseValue == null ) { + throw new NullPointerException("falseValue should not be null"); + } + } + + /** + * Checks the preconditions for constructing a new ParseBool processor. + * + * @param trueValues + * the array of Strings which represent true + * @param falseValues + * the array of Strings which represent false + * @throws IllegalArgumentException + * if trueValues or falseValues is empty + * @throws NullPointerException + * if trueValues or falseValues is null + */ + private static void checkPreconditions(final String[] trueValues, final String[] falseValues) { + + if( trueValues == null ) { + throw new NullPointerException("trueValues should not be null"); + } else if( trueValues.length == 0 ) { + throw new IllegalArgumentException("trueValues should not be empty"); + } + + if( falseValues == null ) { + throw new NullPointerException("falseValues should not be null"); + } else if( falseValues.length == 0 ) { + throw new IllegalArgumentException("falseValues should not be empty"); + } + + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null, not a String, or can't be parsed to a Boolean + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( !(value instanceof String) ) { + throw new SuperCsvCellProcessorException(String.class, value, context, this); + } + + final String stringValue = ((String) value).toLowerCase(); + final Boolean result; + if( trueValues.contains(stringValue) ) { + result = Boolean.TRUE; + } else if( falseValues.contains(stringValue) ) { + result = Boolean.FALSE; + } else { + throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Boolean", value), + context, this); + } + + return next.execute(result, context); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseChar.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseChar.java index 884e9f30..b2b86f21 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseChar.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseChar.java @@ -1,81 +1,81 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a String to a Character. If the String has a length > 1, then an Exception is thrown. - * - * @since 1.10 - * @author Kasper B. Graversen - */ -public class ParseChar extends CellProcessorAdaptor implements StringCellProcessor { - - /** - * Constructs a new ParseChar processor, which converts a String to a Character. - */ - public ParseChar() { - super(); - } - - /** - * Constructs a new ParseChar processor, which converts a String to a Character, then calls the next - * processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public ParseChar(final DoubleCellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null, isn't a Character or String, or is a String of multiple characters - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final Character result; - if( value instanceof Character ) { - result = (Character) value; - } else if( value instanceof String ) { - final String stringValue = (String) value; - if( stringValue.length() == 1 ) { - result = Character.valueOf(stringValue.charAt(0)); - } else { - throw new SuperCsvCellProcessorException(String.format( - "'%s' cannot be parsed as a char as it is a String longer than 1 character", stringValue), context, - this); - } - } else { - final String actualClassName = value.getClass().getName(); - throw new SuperCsvCellProcessorException(String.format( - "the input value should be of type Character or String but is of type %s", actualClassName), context, - this); - } - - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a String to a Character. If the String has a length > 1, then an Exception is thrown. + * + * @since 1.10 + * @author Kasper B. Graversen + */ +public class ParseChar extends CellProcessorAdaptor implements StringCellProcessor { + + /** + * Constructs a new ParseChar processor, which converts a String to a Character. + */ + public ParseChar() { + super(); + } + + /** + * Constructs a new ParseChar processor, which converts a String to a Character, then calls the next + * processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public ParseChar(final DoubleCellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null, isn't a Character or String, or is a String of multiple characters + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final Character result; + if( value instanceof Character ) { + result = (Character) value; + } else if( value instanceof String ) { + final String stringValue = (String) value; + if( stringValue.length() == 1 ) { + result = Character.valueOf(stringValue.charAt(0)); + } else { + throw new SuperCsvCellProcessorException(String.format( + "'%s' cannot be parsed as a char as it is a String longer than 1 character", stringValue), context, + this); + } + } else { + final String actualClassName = value.getClass().getName(); + throw new SuperCsvCellProcessorException(String.format( + "the input value should be of type Character or String but is of type %s", actualClassName), context, + this); + } + + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDate.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDate.java index 01621559..d5cd4308 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDate.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDate.java @@ -1,152 +1,152 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a String to a Date using the {@link SimpleDateFormat} class. If you want to convert from a Date to a String, - * use the {@link FmtDate} processor. - *

- * Some example date formats you can use are:
- * "dd/MM/yyyy" (parses a date formatted as "25/12/2011")
- * "dd-MMM-yy" (parses a date formatted as "25-Dec-11")
- * "yyyy.MM.dd.HH.mm.ss" (parses a date formatted as "2011.12.25.08.36.33"
- * "E, dd MMM yyyy HH:mm:ss Z" (parses a date formatted as "Tue, 25 Dec 2011 08:36:33 -0500")
- *

- * This processor caters for lenient or non-lenient date interpretations (the default is false for constructors without - * a 'lenient' parameter). See {@link SimpleDateFormat#setLenient(boolean)} for more information. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseDate extends CellProcessorAdaptor implements StringCellProcessor { - - private final String dateFormat; - - private final boolean lenient; - - /** - * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format. - * This constructor uses non-lenient Date interpretation. - * - * @param dateFormat - * the date format to use - * @throws NullPointerException - * if dateFormat is null - */ - public ParseDate(final String dateFormat) { - this(dateFormat, false); - } - - /** - * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format. - * - * @param dateFormat - * the date format to use - * @param lenient - * whether date interpretation is lenient - * @throws NullPointerException - * if dateFormat is null - */ - public ParseDate(final String dateFormat, final boolean lenient) { - super(); - checkPreconditions(dateFormat); - this.dateFormat = dateFormat; - this.lenient = lenient; - } - - /** - * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format, - * then calls the next processor in the chain. This constructor uses non-lenient Date interpretation. - * - * @param dateFormat - * the date format to use - * @param next - * the next processor in the chain - * @throws NullPointerException - * if dateFormat or next is null - */ - public ParseDate(final String dateFormat, final DateCellProcessor next) { - this(dateFormat, false, next); - } - - /** - * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format, - * then calls the next processor in the chain. - * - * @param dateFormat - * the date format to use - * @param lenient - * whether date interpretation is lenient - * @param next - * the next processor in the chain - * @throws NullPointerException - * if dateFormat or next is null - */ - public ParseDate(final String dateFormat, final boolean lenient, final DateCellProcessor next) { - super(next); - checkPreconditions(dateFormat); - this.dateFormat = dateFormat; - this.lenient = lenient; - } - - /** - * Checks the preconditions for creating a new ParseDate processor. - * - * @param dateFormat - * the date format to use - * @throws NullPointerException - * if dateFormat is null - */ - private static void checkPreconditions(final String dateFormat) { - if( dateFormat == null ) { - throw new NullPointerException("dateFormat should not be null"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null, isn't a String, or can't be parsed to a Date - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( !(value instanceof String) ) { - throw new SuperCsvCellProcessorException(String.class, value, context, this); - } - - try { - final SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); - formatter.setLenient(lenient); - final Date result = formatter.parse((String) value); - return next.execute(result, context); - } - catch(final ParseException e) { - throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Date", value), - context, this, e); - } - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a String to a Date using the {@link SimpleDateFormat} class. If you want to convert from a Date to a String, + * use the {@link FmtDate} processor. + *

+ * Some example date formats you can use are:
+ * "dd/MM/yyyy" (parses a date formatted as "25/12/2011")
+ * "dd-MMM-yy" (parses a date formatted as "25-Dec-11")
+ * "yyyy.MM.dd.HH.mm.ss" (parses a date formatted as "2011.12.25.08.36.33"
+ * "E, dd MMM yyyy HH:mm:ss Z" (parses a date formatted as "Tue, 25 Dec 2011 08:36:33 -0500")
+ *

+ * This processor caters for lenient or non-lenient date interpretations (the default is false for constructors without + * a 'lenient' parameter). See {@link SimpleDateFormat#setLenient(boolean)} for more information. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseDate extends CellProcessorAdaptor implements StringCellProcessor { + + private final String dateFormat; + + private final boolean lenient; + + /** + * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format. + * This constructor uses non-lenient Date interpretation. + * + * @param dateFormat + * the date format to use + * @throws NullPointerException + * if dateFormat is null + */ + public ParseDate(final String dateFormat) { + this(dateFormat, false); + } + + /** + * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format. + * + * @param dateFormat + * the date format to use + * @param lenient + * whether date interpretation is lenient + * @throws NullPointerException + * if dateFormat is null + */ + public ParseDate(final String dateFormat, final boolean lenient) { + super(); + checkPreconditions(dateFormat); + this.dateFormat = dateFormat; + this.lenient = lenient; + } + + /** + * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format, + * then calls the next processor in the chain. This constructor uses non-lenient Date interpretation. + * + * @param dateFormat + * the date format to use + * @param next + * the next processor in the chain + * @throws NullPointerException + * if dateFormat or next is null + */ + public ParseDate(final String dateFormat, final DateCellProcessor next) { + this(dateFormat, false, next); + } + + /** + * Constructs a new ParseDate processor which converts a String to a Date using the supplied date format, + * then calls the next processor in the chain. + * + * @param dateFormat + * the date format to use + * @param lenient + * whether date interpretation is lenient + * @param next + * the next processor in the chain + * @throws NullPointerException + * if dateFormat or next is null + */ + public ParseDate(final String dateFormat, final boolean lenient, final DateCellProcessor next) { + super(next); + checkPreconditions(dateFormat); + this.dateFormat = dateFormat; + this.lenient = lenient; + } + + /** + * Checks the preconditions for creating a new ParseDate processor. + * + * @param dateFormat + * the date format to use + * @throws NullPointerException + * if dateFormat is null + */ + private static void checkPreconditions(final String dateFormat) { + if( dateFormat == null ) { + throw new NullPointerException("dateFormat should not be null"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null, isn't a String, or can't be parsed to a Date + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( !(value instanceof String) ) { + throw new SuperCsvCellProcessorException(String.class, value, context, this); + } + + try { + final SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); + formatter.setLenient(lenient); + final Date result = formatter.parse((String) value); + return next.execute(result, context); + } + catch(final ParseException e) { + throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Date", value), + context, this, e); + } + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDouble.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDouble.java index 3e41142b..6348a23e 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDouble.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseDouble.java @@ -1,78 +1,78 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a String to a Double. - * - * @author Kasper B. Graversen - */ -public class ParseDouble extends CellProcessorAdaptor implements StringCellProcessor { - - /** - * Constructs a new ParseDouble processor, which converts a String to a Double. - */ - public ParseDouble() { - super(); - } - - /** - * Constructs a new ParseDouble processor, which converts a String to a Double, then calls the next - * processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public ParseDouble(final DoubleCellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null, isn't a Double or String, or can't be parsed as a Double - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final Double result; - if( value instanceof Double ) { - result = (Double) value; - } else if( value instanceof String ) { - try { - result = new Double((String) value); - } - catch(final NumberFormatException e) { - throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Double", value), - context, this, e); - } - } else { - final String actualClassName = value.getClass().getName(); - throw new SuperCsvCellProcessorException(String.format( - "the input value should be of type Double or String but is of type %s", actualClassName), context, this); - } - - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a String to a Double. + * + * @author Kasper B. Graversen + */ +public class ParseDouble extends CellProcessorAdaptor implements StringCellProcessor { + + /** + * Constructs a new ParseDouble processor, which converts a String to a Double. + */ + public ParseDouble() { + super(); + } + + /** + * Constructs a new ParseDouble processor, which converts a String to a Double, then calls the next + * processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public ParseDouble(final DoubleCellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null, isn't a Double or String, or can't be parsed as a Double + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final Double result; + if( value instanceof Double ) { + result = (Double) value; + } else if( value instanceof String ) { + try { + result = new Double((String) value); + } + catch(final NumberFormatException e) { + throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Double", value), + context, this, e); + } + } else { + final String actualClassName = value.getClass().getName(); + throw new SuperCsvCellProcessorException(String.format( + "the input value should be of type Double or String but is of type %s", actualClassName), context, this); + } + + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseInt.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseInt.java index f24783c8..3fab8ceb 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseInt.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseInt.java @@ -1,79 +1,79 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a String to an Integer. - * - * @author Kasper B. Graversen - */ -public class ParseInt extends CellProcessorAdaptor implements StringCellProcessor { - - /** - * Constructs a new ParseInt processor, which converts a String to an Integer. - */ - public ParseInt() { - super(); - } - - /** - * Constructs a new ParseInt processor, which converts a String to an Integer, then calls the next - * processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public ParseInt(final LongCellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null, isn't an Integer or String, or can't be parsed as an Integer - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final Integer result; - if( value instanceof Integer ) { - result = (Integer) value; - } else if( value instanceof String ) { - try { - result = Integer.valueOf((String) value); - } - catch(final NumberFormatException e) { - throw new SuperCsvCellProcessorException( - String.format("'%s' could not be parsed as an Integer", value), context, this, e); - } - } else { - final String actualClassName = value.getClass().getName(); - throw new SuperCsvCellProcessorException(String.format( - "the input value should be of type Integer or String but is of type %s", actualClassName), context, - this); - } - - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a String to an Integer. + * + * @author Kasper B. Graversen + */ +public class ParseInt extends CellProcessorAdaptor implements StringCellProcessor { + + /** + * Constructs a new ParseInt processor, which converts a String to an Integer. + */ + public ParseInt() { + super(); + } + + /** + * Constructs a new ParseInt processor, which converts a String to an Integer, then calls the next + * processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public ParseInt(final LongCellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null, isn't an Integer or String, or can't be parsed as an Integer + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final Integer result; + if( value instanceof Integer ) { + result = (Integer) value; + } else if( value instanceof String ) { + try { + result = Integer.valueOf((String) value); + } + catch(final NumberFormatException e) { + throw new SuperCsvCellProcessorException( + String.format("'%s' could not be parsed as an Integer", value), context, this, e); + } + } else { + final String actualClassName = value.getClass().getName(); + throw new SuperCsvCellProcessorException(String.format( + "the input value should be of type Integer or String but is of type %s", actualClassName), context, + this); + } + + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseLong.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseLong.java index 22dc7960..0c3e484d 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ParseLong.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ParseLong.java @@ -1,78 +1,78 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Converts a String to a Long. - * - * @author Kasper B. Graversen - */ -public class ParseLong extends CellProcessorAdaptor implements StringCellProcessor { - - /** - * Constructs a new ParseLong processor, which converts a String to a Long. - */ - public ParseLong() { - super(); - } - - /** - * Constructs a new ParseLong processor, which converts a String to a Long, then calls the next processor - * in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public ParseLong(final LongCellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null, isn't a Long or String, or can't be parsed as a Long - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final Long result; - if( value instanceof Long ) { - result = (Long) value; - } else if( value instanceof String ) { - try { - result = Long.parseLong((String) value); - } - catch(final NumberFormatException e) { - throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as an Long", value), - context, this, e); - } - } else { - final String actualClassName = value.getClass().getName(); - throw new SuperCsvCellProcessorException(String.format( - "the input value should be of type Long or String but is of type %s", actualClassName), context, this); - } - - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Converts a String to a Long. + * + * @author Kasper B. Graversen + */ +public class ParseLong extends CellProcessorAdaptor implements StringCellProcessor { + + /** + * Constructs a new ParseLong processor, which converts a String to a Long. + */ + public ParseLong() { + super(); + } + + /** + * Constructs a new ParseLong processor, which converts a String to a Long, then calls the next processor + * in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public ParseLong(final LongCellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null, isn't a Long or String, or can't be parsed as a Long + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final Long result; + if( value instanceof Long ) { + result = (Long) value; + } else if( value instanceof String ) { + try { + result = Long.parseLong((String) value); + } + catch(final NumberFormatException e) { + throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as an Long", value), + context, this, e); + } + } else { + final String actualClassName = value.getClass().getName(); + throw new SuperCsvCellProcessorException(String.format( + "the input value should be of type Long or String but is of type %s", actualClassName), context, this); + } + + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/StrReplace.java b/super-csv/src/main/java/org/supercsv/cellprocessor/StrReplace.java index e12c14b0..ad78f106 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/StrReplace.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/StrReplace.java @@ -1,125 +1,125 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Replaces each substring of the input string that matches the given regular expression with the given replacement. The - * regular expression pattern is compiled once then reused for efficiency. - * - * @author Kasper B. Graversen - * @author Dominique De Vito - * @author James Bassett - */ -public class StrReplace extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, - DoubleCellProcessor, LongCellProcessor, StringCellProcessor { - - private final Pattern regexPattern; - private final String replacement; - - /** - * Constructs a new StrReplace processor, which replaces each substring of the input that matches the regex - * with the supplied replacement. - * - * @param regex - * the regular expression to match - * @param replacement - * the string to be substituted for each match - * @throws IllegalArgumentException - * if regex is empty - * @throws NullPointerException - * if regex or replacement is null - * @throws PatternSyntaxException - * if regex is not a valid regular expression - */ - public StrReplace(final String regex, final String replacement) { - super(); - checkPreconditions(regex, replacement); - this.regexPattern = Pattern.compile(regex); - this.replacement = replacement; - } - - /** - * Constructs a new StrReplace processor, which replaces each substring of the input that matches the regex - * with the supplied replacement, then calls the next processor in the chain. - * - * @param regex - * the regular expression to match - * @param replacement - * the string to be substituted for each match - * @param next - * the next processor in the chain - * @throws IllegalArgumentException - * if regex is empty - * @throws NullPointerException - * if regex or replacement is null - * @throws PatternSyntaxException - * if regex is not a valid regular expression - */ - public StrReplace(final String regex, final String replacement, final StringCellProcessor next) { - super(next); - checkPreconditions(regex, replacement); - this.regexPattern = Pattern.compile(regex); - this.replacement = replacement; - } - - /** - * Checks the preconditions for creating a new StrRegExReplace processor. - * - * @param regex - * the supplied regular expression - * @param replacement - * the supplied replacement text - * @throws IllegalArgumentException - * if regex is empty - * @throws NullPointerException - * if regex or replacement is null - */ - private static void checkPreconditions(final String regex, final String replacement) { - if( regex == null ) { - throw new NullPointerException("regex should not be null"); - } else if( regex.length() == 0 ) { - throw new IllegalArgumentException("regex should not be empty"); - } - - if( replacement == null ) { - throw new NullPointerException("replacement should not be null"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - String result = regexPattern.matcher(value.toString()).replaceAll(replacement); - return next.execute(result, context); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Replaces each substring of the input string that matches the given regular expression with the given replacement. The + * regular expression pattern is compiled once then reused for efficiency. + * + * @author Kasper B. Graversen + * @author Dominique De Vito + * @author James Bassett + */ +public class StrReplace extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, + DoubleCellProcessor, LongCellProcessor, StringCellProcessor { + + private final Pattern regexPattern; + private final String replacement; + + /** + * Constructs a new StrReplace processor, which replaces each substring of the input that matches the regex + * with the supplied replacement. + * + * @param regex + * the regular expression to match + * @param replacement + * the string to be substituted for each match + * @throws IllegalArgumentException + * if regex is empty + * @throws NullPointerException + * if regex or replacement is null + * @throws PatternSyntaxException + * if regex is not a valid regular expression + */ + public StrReplace(final String regex, final String replacement) { + super(); + checkPreconditions(regex, replacement); + this.regexPattern = Pattern.compile(regex); + this.replacement = replacement; + } + + /** + * Constructs a new StrReplace processor, which replaces each substring of the input that matches the regex + * with the supplied replacement, then calls the next processor in the chain. + * + * @param regex + * the regular expression to match + * @param replacement + * the string to be substituted for each match + * @param next + * the next processor in the chain + * @throws IllegalArgumentException + * if regex is empty + * @throws NullPointerException + * if regex or replacement is null + * @throws PatternSyntaxException + * if regex is not a valid regular expression + */ + public StrReplace(final String regex, final String replacement, final StringCellProcessor next) { + super(next); + checkPreconditions(regex, replacement); + this.regexPattern = Pattern.compile(regex); + this.replacement = replacement; + } + + /** + * Checks the preconditions for creating a new StrRegExReplace processor. + * + * @param regex + * the supplied regular expression + * @param replacement + * the supplied replacement text + * @throws IllegalArgumentException + * if regex is empty + * @throws NullPointerException + * if regex or replacement is null + */ + private static void checkPreconditions(final String regex, final String replacement) { + if( regex == null ) { + throw new NullPointerException("regex should not be null"); + } else if( regex.length() == 0 ) { + throw new IllegalArgumentException("regex should not be empty"); + } + + if( replacement == null ) { + throw new NullPointerException("replacement should not be null"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + String result = regexPattern.matcher(value.toString()).replaceAll(replacement); + return next.execute(result, context); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/Token.java b/super-csv/src/main/java/org/supercsv/cellprocessor/Token.java index c69b10bf..7cd7aab0 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/Token.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/Token.java @@ -1,96 +1,96 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * This processor is used in the situations you want to be able to check for the presence of a "special - * token". Such a token could be the string "[empty]" which could denote that a column is different from the empty - * string "". - *

- * For example, to convert the String "[empty]" to -1 (an int representing 'empty') you could use - * new Token("[empty]", -1) - * - *

- * Comparison between the input and the token is based on the object's equals() method. - * - * @since 1.02 - * @author Kasper B. Graversen - */ -public class Token extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, - LongCellProcessor, StringCellProcessor { - - private final Object returnValue; - private final Object token; - - /** - * Constructs a new Token processor, which returns the supplied value if the token is encountered, - * otherwise it returns the input unchanged. - * - * @param token - * the token - * @param returnValue - * the value to return if the token is encountered - */ - public Token(final Object token, final Object returnValue) { - super(); - this.token = token; - this.returnValue = returnValue; - } - - /** - * Constructs a new Token processor, which returns the supplied value if the token is encountered, - * otherwise it passes the input unchanged to the next processor in the chain. - * - * @param token - * the token - * @param returnValue - * the value to return if the token is encountered - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public Token(final Object token, final Object returnValue, final CellProcessor next) { - super(next); - this.token = token; - this.returnValue = returnValue; - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( value.equals(token) ) { - return returnValue; - } - - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * This processor is used in the situations you want to be able to check for the presence of a "special + * token". Such a token could be the string "[empty]" which could denote that a column is different from the empty + * string "". + *

+ * For example, to convert the String "[empty]" to -1 (an int representing 'empty') you could use + * new Token("[empty]", -1) + * + *

+ * Comparison between the input and the token is based on the object's equals() method. + * + * @since 1.02 + * @author Kasper B. Graversen + */ +public class Token extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, + LongCellProcessor, StringCellProcessor { + + private final Object returnValue; + private final Object token; + + /** + * Constructs a new Token processor, which returns the supplied value if the token is encountered, + * otherwise it returns the input unchanged. + * + * @param token + * the token + * @param returnValue + * the value to return if the token is encountered + */ + public Token(final Object token, final Object returnValue) { + super(); + this.token = token; + this.returnValue = returnValue; + } + + /** + * Constructs a new Token processor, which returns the supplied value if the token is encountered, + * otherwise it passes the input unchanged to the next processor in the chain. + * + * @param token + * the token + * @param returnValue + * the value to return if the token is encountered + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public Token(final Object token, final Object returnValue, final CellProcessor next) { + super(next); + this.token = token; + this.returnValue = returnValue; + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( value.equals(token) ) { + return returnValue; + } + + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/Trim.java b/super-csv/src/main/java/org/supercsv/cellprocessor/Trim.java index 42307559..f84f453c 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/Trim.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/Trim.java @@ -1,69 +1,69 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Ensure that Strings or String-representations of objects are trimmed (contain no surrounding whitespace). - *

- * Prior to 2.0.0, this processor truncated Strings - this functionality can now be found in the {@link Truncate} - * processor. - * - * @author James Bassett - */ -public class Trim extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, - LongCellProcessor, StringCellProcessor { - - /** - * Constructs a new Trim processor, which trims a String to ensure it has no surrounding whitespace. - */ - public Trim() { - super(); - } - - /** - * Constructs a new Trim processor, which trims a String to ensure it has no surrounding whitespace then - * calls the next processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public Trim(final StringCellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final String result = value.toString().trim(); - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Ensure that Strings or String-representations of objects are trimmed (contain no surrounding whitespace). + *

+ * Prior to 2.0.0, this processor truncated Strings - this functionality can now be found in the {@link Truncate} + * processor. + * + * @author James Bassett + */ +public class Trim extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, + LongCellProcessor, StringCellProcessor { + + /** + * Constructs a new Trim processor, which trims a String to ensure it has no surrounding whitespace. + */ + public Trim() { + super(); + } + + /** + * Constructs a new Trim processor, which trims a String to ensure it has no surrounding whitespace then + * calls the next processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public Trim(final StringCellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final String result = value.toString().trim(); + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/Truncate.java b/super-csv/src/main/java/org/supercsv/cellprocessor/Truncate.java index a8260eb8..63a36bf5 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/Truncate.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/Truncate.java @@ -1,156 +1,156 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * Ensure that Strings or String-representations of objects are truncated to a maximum size. If you desire, you can - * append a String to denote that the data has been truncated (e.g. "..."). - *

- * As of 2.0.0, this functionality was moved from the {@link Trim} processor to this processor, to allow a clear - * distinction between trimming and truncating. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class Truncate extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, - DoubleCellProcessor, LongCellProcessor, StringCellProcessor { - - private static final String EMPTY_STRING = ""; - - private final int maxSize; - private final String suffix; - - /** - * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the - * specified size. - * - * @param maxSize - * the maximum size of the String - * @throws IllegalArgumentException - * if maxSize <= 0 - */ - public Truncate(final int maxSize) { - this(maxSize, EMPTY_STRING); - } - - /** - * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the - * specified size, then appends the suffix String to indicate that the String has been truncated. - * - * @param maxSize - * the maximum size of the String - * @param suffix - * the String to append if the input is truncated (e.g. "...") - * @throws IllegalArgumentException - * if maxSize <= 0 - * @throws NullPointerException - * if suffix is null - */ - public Truncate(final int maxSize, final String suffix) { - checkPreconditions(maxSize, suffix); - this.maxSize = maxSize; - this.suffix = suffix; - } - - /** - * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the - * specified size, then appends the suffix String to indicate that the String has been truncated and - * calls the next processor in the chain. - * - * @param maxSize - * the maximum size of the String - * @param suffix - * the String to append if the input is truncated (e.g. "...") - * @param next - * the next processor in the chain - * @throws IllegalArgumentException - * if maxSize <= 0 - * @throws NullPointerException - * if suffix or next is null - */ - public Truncate(final int maxSize, final String suffix, final StringCellProcessor next) { - super(next); - checkPreconditions(maxSize, suffix); - this.maxSize = maxSize; - this.suffix = suffix; - } - - /** - * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the - * specified size, then calls the next processor in the chain. - * - * @param maxSize - * the maximum size of the String - * @param next - * the next processor in the chain - * @throws IllegalArgumentException - * if maxSize <= 0 - * @throws NullPointerException - * if next is null - */ - public Truncate(final int maxSize, final StringCellProcessor next) { - this(maxSize, EMPTY_STRING, next); - } - - /** - * Checks the preconditions for creating a new Truncate processor. - * - * @param maxSize - * the maximum size of the String - * @param suffix - * the String to append if the input is truncated (e.g. "...") - * @throws IllegalArgumentException - * if maxSize <= 0 - * @throws NullPointerException - * if suffix is null - */ - private static void checkPreconditions(final int maxSize, final String suffix) { - if( maxSize <= 0 ) { - throw new IllegalArgumentException(String.format("maxSize should be > 0 but was %d", maxSize)); - } - if( suffix == null ) { - throw new NullPointerException("suffix should not be null"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final String stringValue = value.toString(); - final String result; - if( stringValue.length() <= maxSize ) { - result = stringValue; - } else { - result = stringValue.substring(0, maxSize) + suffix; - } - - return next.execute(result, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * Ensure that Strings or String-representations of objects are truncated to a maximum size. If you desire, you can + * append a String to denote that the data has been truncated (e.g. "..."). + *

+ * As of 2.0.0, this functionality was moved from the {@link Trim} processor to this processor, to allow a clear + * distinction between trimming and truncating. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class Truncate extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, + DoubleCellProcessor, LongCellProcessor, StringCellProcessor { + + private static final String EMPTY_STRING = ""; + + private final int maxSize; + private final String suffix; + + /** + * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the + * specified size. + * + * @param maxSize + * the maximum size of the String + * @throws IllegalArgumentException + * if maxSize <= 0 + */ + public Truncate(final int maxSize) { + this(maxSize, EMPTY_STRING); + } + + /** + * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the + * specified size, then appends the suffix String to indicate that the String has been truncated. + * + * @param maxSize + * the maximum size of the String + * @param suffix + * the String to append if the input is truncated (e.g. "...") + * @throws IllegalArgumentException + * if maxSize <= 0 + * @throws NullPointerException + * if suffix is null + */ + public Truncate(final int maxSize, final String suffix) { + checkPreconditions(maxSize, suffix); + this.maxSize = maxSize; + this.suffix = suffix; + } + + /** + * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the + * specified size, then appends the suffix String to indicate that the String has been truncated and + * calls the next processor in the chain. + * + * @param maxSize + * the maximum size of the String + * @param suffix + * the String to append if the input is truncated (e.g. "...") + * @param next + * the next processor in the chain + * @throws IllegalArgumentException + * if maxSize <= 0 + * @throws NullPointerException + * if suffix or next is null + */ + public Truncate(final int maxSize, final String suffix, final StringCellProcessor next) { + super(next); + checkPreconditions(maxSize, suffix); + this.maxSize = maxSize; + this.suffix = suffix; + } + + /** + * Constructs a new Truncate processor, which truncates a String to ensure it is no longer than the + * specified size, then calls the next processor in the chain. + * + * @param maxSize + * the maximum size of the String + * @param next + * the next processor in the chain + * @throws IllegalArgumentException + * if maxSize <= 0 + * @throws NullPointerException + * if next is null + */ + public Truncate(final int maxSize, final StringCellProcessor next) { + this(maxSize, EMPTY_STRING, next); + } + + /** + * Checks the preconditions for creating a new Truncate processor. + * + * @param maxSize + * the maximum size of the String + * @param suffix + * the String to append if the input is truncated (e.g. "...") + * @throws IllegalArgumentException + * if maxSize <= 0 + * @throws NullPointerException + * if suffix is null + */ + private static void checkPreconditions(final int maxSize, final String suffix) { + if( maxSize <= 0 ) { + throw new IllegalArgumentException(String.format("maxSize should be > 0 but was %d", maxSize)); + } + if( suffix == null ) { + throw new NullPointerException("suffix should not be null"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final String stringValue = value.toString(); + final String result; + if( stringValue.length() <= maxSize ) { + result = stringValue; + } else { + result = stringValue.substring(0, maxSize) + suffix; + } + + return next.execute(result, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/DMinMax.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/DMinMax.java index ecdd9e02..9483d572 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/DMinMax.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/DMinMax.java @@ -1,157 +1,157 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * Converts the input data to a Double and ensures that number is within a specified numeric range (inclusive). If the - * data has no upper bound (or lower bound), you should use either of MIN or MAX constants - * provided in the class. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class DMinMax extends CellProcessorAdaptor { - - /** Maximum value for a Double */ - public static final double MAX_DOUBLE = Double.MAX_VALUE; - - /** Minimum value for a Double */ - public static final double MIN_DOUBLE = Double.MIN_VALUE; - - /** Maximum value for a Short */ - public static final double MAX_SHORT = Short.MAX_VALUE; - - /** Minimum value for a Short */ - public static final double MIN_SHORT = Short.MIN_VALUE; - - /** Maximum value for a Character */ - public static final double MAX_CHAR = Character.MAX_VALUE; - - /** Minimum value for a Character */ - public static final double MIN_CHAR = Character.MIN_VALUE; - - /** Maximum value for 8 bits (unsigned) */ - public static final int MAX_8_BIT_UNSIGNED = 255; - - /** Minimum value for 8 bits (unsigned) */ - public static final int MIN_8_BIT_UNSIGNED = 0; - - /** Maximum value for 8 bits (signed) */ - public static final int MAX_8_BIT_SIGNED = Byte.MAX_VALUE; - - /** Minimum value for 8 bits (signed) */ - public static final int MIN_8_BIT_SIGNED = Byte.MIN_VALUE; - - private final double min; - - private final double max; - - /** - * Constructs a new DMinMax processor, which converts the input to a Double and ensures the value is - * between the supplied min and max values. - * - * @param min - * the minimum value (inclusive) - * @param max - * the maximum value (inclusive) - * @throws IllegalArgumentException - * if max < min - */ - public DMinMax(final double min, final double max) { - super(); - checkPreconditions(min, max); - this.min = min; - this.max = max; - } - - /** - * Constructs a new DMinMax processor, which converts the input to a Double, ensures the value is between - * the supplied min and max values, then calls the next processor in the chain. - * - * @param min - * the minimum value (inclusive) - * @param max - * the maximum value (inclusive) - * @param next - * the next processor in the chain - * @throws IllegalArgumentException - * if max < min - * @throws NullPointerException - * if next is null - */ - public DMinMax(final double min, final double max, final DoubleCellProcessor next) { - super(next); - checkPreconditions(min, max); - this.min = min; - this.max = max; - } - - /** - * Checks the preconditions for creating a new DMinMax processor. - * - * @param min - * the minimum value (inclusive) - * @param max - * the maximum value (inclusive) - * @throws IllegalArgumentException - * if max < min - */ - private static void checkPreconditions(final double min, final double max) { - if( max < min ) { - throw new IllegalArgumentException(String.format("max (%f) should not be < min (%f)", max, min)); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null or can't be parsed as a Double - * @throws SuperCsvConstraintViolationException - * if value doesn't lie between min and max (inclusive) - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final Double result; - if( value instanceof Double ) { - result = (Double) value; - } else { - try { - result = Double.parseDouble(value.toString()); - } - catch(final NumberFormatException e) { - throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Double", value), - context, this, e); - } - } - - if( result < min || result > max ) { - throw new SuperCsvConstraintViolationException(String.format( - "%f does not lie between the min (%f) and max (%f) values (inclusive)", result, min, max), context, - this); - } - - return next.execute(result, context); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * Converts the input data to a Double and ensures that number is within a specified numeric range (inclusive). If the + * data has no upper bound (or lower bound), you should use either of MIN or MAX constants + * provided in the class. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class DMinMax extends CellProcessorAdaptor { + + /** Maximum value for a Double */ + public static final double MAX_DOUBLE = Double.MAX_VALUE; + + /** Minimum value for a Double */ + public static final double MIN_DOUBLE = Double.MIN_VALUE; + + /** Maximum value for a Short */ + public static final double MAX_SHORT = Short.MAX_VALUE; + + /** Minimum value for a Short */ + public static final double MIN_SHORT = Short.MIN_VALUE; + + /** Maximum value for a Character */ + public static final double MAX_CHAR = Character.MAX_VALUE; + + /** Minimum value for a Character */ + public static final double MIN_CHAR = Character.MIN_VALUE; + + /** Maximum value for 8 bits (unsigned) */ + public static final int MAX_8_BIT_UNSIGNED = 255; + + /** Minimum value for 8 bits (unsigned) */ + public static final int MIN_8_BIT_UNSIGNED = 0; + + /** Maximum value for 8 bits (signed) */ + public static final int MAX_8_BIT_SIGNED = Byte.MAX_VALUE; + + /** Minimum value for 8 bits (signed) */ + public static final int MIN_8_BIT_SIGNED = Byte.MIN_VALUE; + + private final double min; + + private final double max; + + /** + * Constructs a new DMinMax processor, which converts the input to a Double and ensures the value is + * between the supplied min and max values. + * + * @param min + * the minimum value (inclusive) + * @param max + * the maximum value (inclusive) + * @throws IllegalArgumentException + * if max < min + */ + public DMinMax(final double min, final double max) { + super(); + checkPreconditions(min, max); + this.min = min; + this.max = max; + } + + /** + * Constructs a new DMinMax processor, which converts the input to a Double, ensures the value is between + * the supplied min and max values, then calls the next processor in the chain. + * + * @param min + * the minimum value (inclusive) + * @param max + * the maximum value (inclusive) + * @param next + * the next processor in the chain + * @throws IllegalArgumentException + * if max < min + * @throws NullPointerException + * if next is null + */ + public DMinMax(final double min, final double max, final DoubleCellProcessor next) { + super(next); + checkPreconditions(min, max); + this.min = min; + this.max = max; + } + + /** + * Checks the preconditions for creating a new DMinMax processor. + * + * @param min + * the minimum value (inclusive) + * @param max + * the maximum value (inclusive) + * @throws IllegalArgumentException + * if max < min + */ + private static void checkPreconditions(final double min, final double max) { + if( max < min ) { + throw new IllegalArgumentException(String.format("max (%f) should not be < min (%f)", max, min)); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null or can't be parsed as a Double + * @throws SuperCsvConstraintViolationException + * if value doesn't lie between min and max (inclusive) + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final Double result; + if( value instanceof Double ) { + result = (Double) value; + } else { + try { + result = Double.parseDouble(value.toString()); + } + catch(final NumberFormatException e) { + throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Double", value), + context, this, e); + } + } + + if( result < min || result > max ) { + throw new SuperCsvConstraintViolationException(String.format( + "%f does not lie between the min (%f) and max (%f) values (inclusive)", result, min, max), context, + this); + } + + return next.execute(result, context); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Equals.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Equals.java index 592abef5..c4c8de3d 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Equals.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Equals.java @@ -1,133 +1,133 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This constraint ensures that all input data is equal (to each other, or to a supplied constant value). - * - * @author Dominique De Vito - * @author James Bassett - * @since 1.50 - */ -public class Equals extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, - LongCellProcessor, StringCellProcessor { - - private static final Object UNKNOWN = new Object(); - - private Object constantValue; - private boolean constantSupplied; - - /** - * Constructs a new Equals processor, which ensures all input data is equal. - */ - public Equals() { - super(); - this.constantValue = UNKNOWN; - this.constantSupplied = false; - } - - /** - * Constructs a new Equals processor, which ensures all input data is equal to the supplied constant value. - * - * @param constantValue - * the constant value that all input must equal - */ - public Equals(Object constantValue) { - super(); - this.constantValue = constantValue; - this.constantSupplied = true; - } - - /** - * Constructs a new Equals processor, which ensures all input data is equal, then calls the the next - * processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public Equals(final CellProcessor next) { - super(next); - this.constantValue = UNKNOWN; - this.constantSupplied = false; - } - - /** - * Constructs a new Equals processor, which ensures all input data is equal to the supplied constant value, - * then calls the the next processor in the chain. - * - * @param constantValue - * the constant value that all input must equal - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public Equals(final Object constantValue, final CellProcessor next) { - super(next); - this.constantValue = constantValue; - this.constantSupplied = true; - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvConstraintViolationException - * if value isn't equal to the constant value (or previously encountered value if a constant wasn't - * supplied) - */ - public Object execute(final Object value, final CsvContext context) { - if( UNKNOWN.equals(constantValue) ) { - constantValue = value; // no constant supplied, so remember the first value encountered - } else { - if( !equals(constantValue, value) ) { - if( constantSupplied ) { - throw new SuperCsvConstraintViolationException(String.format("'%s' is not equal to the supplied constant '%s'", value, - constantValue), context, this); - } else { - throw new SuperCsvConstraintViolationException(String.format("'%s' is not equal to the previous value(s) of '%s'", - value, constantValue), context, this); - } - } - } - return next.execute(value, context); - } - - /** - * Returns true if both objects are null or equal, otherwise false. - * - * @param o1 - * the first object - * @param o2 - * the second object - * @return true if both objects are null or equal, otherwise false - */ - private static boolean equals(Object o1, Object o2) { - return (o1 == null) ? (o2 == null) : o1.equals(o2); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This constraint ensures that all input data is equal (to each other, or to a supplied constant value). + * + * @author Dominique De Vito + * @author James Bassett + * @since 1.50 + */ +public class Equals extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, + LongCellProcessor, StringCellProcessor { + + private static final Object UNKNOWN = new Object(); + + private Object constantValue; + private boolean constantSupplied; + + /** + * Constructs a new Equals processor, which ensures all input data is equal. + */ + public Equals() { + super(); + this.constantValue = UNKNOWN; + this.constantSupplied = false; + } + + /** + * Constructs a new Equals processor, which ensures all input data is equal to the supplied constant value. + * + * @param constantValue + * the constant value that all input must equal + */ + public Equals(Object constantValue) { + super(); + this.constantValue = constantValue; + this.constantSupplied = true; + } + + /** + * Constructs a new Equals processor, which ensures all input data is equal, then calls the the next + * processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public Equals(final CellProcessor next) { + super(next); + this.constantValue = UNKNOWN; + this.constantSupplied = false; + } + + /** + * Constructs a new Equals processor, which ensures all input data is equal to the supplied constant value, + * then calls the the next processor in the chain. + * + * @param constantValue + * the constant value that all input must equal + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public Equals(final Object constantValue, final CellProcessor next) { + super(next); + this.constantValue = constantValue; + this.constantSupplied = true; + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvConstraintViolationException + * if value isn't equal to the constant value (or previously encountered value if a constant wasn't + * supplied) + */ + public Object execute(final Object value, final CsvContext context) { + if( UNKNOWN.equals(constantValue) ) { + constantValue = value; // no constant supplied, so remember the first value encountered + } else { + if( !equals(constantValue, value) ) { + if( constantSupplied ) { + throw new SuperCsvConstraintViolationException(String.format("'%s' is not equal to the supplied constant '%s'", value, + constantValue), context, this); + } else { + throw new SuperCsvConstraintViolationException(String.format("'%s' is not equal to the previous value(s) of '%s'", + value, constantValue), context, this); + } + } + } + return next.execute(value, context); + } + + /** + * Returns true if both objects are null or equal, otherwise false. + * + * @param o1 + * the first object + * @param o2 + * the second object + * @return true if both objects are null or equal, otherwise false + */ + private static boolean equals(Object o1, Object o2) { + return (o1 == null) ? (o2 == null) : o1.equals(o2); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/ForbidSubStr.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/ForbidSubStr.java index 6797fafe..4a9244d3 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/ForbidSubStr.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/ForbidSubStr.java @@ -1,215 +1,215 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * Converts the input to a String and ensures that it doesn't contain any of the supplied substrings. For example, this - * constraint might be handy when reading/writing filenames and wanting to ensure no filename contains ":", "/", etc. - * - * @since 1.10 - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ForbidSubStr extends CellProcessorAdaptor implements StringCellProcessor { - - private final List forbiddenSubStrings = new ArrayList(); - - /** - * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied - * substrings. - * - * @param forbiddenSubStrings - * the List of forbidden substrings - * @throws NullPointerException - * if forbiddenSubStrings or one of its elements is null - * @throws IllegalArgumentException - * if forbiddenSubStrings is empty - */ - public ForbidSubStr(final List forbiddenSubStrings) { - super(); - checkPreconditions(forbiddenSubStrings); - checkAndAddForbiddenStrings(forbiddenSubStrings); - } - - /** - * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied - * substrings. - * - * @param forbiddenSubStrings - * the forbidden substrings - * @throws NullPointerException - * if forbiddenSubStrings or one of its elements is null - * @throws IllegalArgumentException - * if forbiddenSubStrings is empty - */ - public ForbidSubStr(final String... forbiddenSubStrings) { - super(); - checkPreconditions(forbiddenSubStrings); - checkAndAddForbiddenStrings(forbiddenSubStrings); - } - - /** - * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied - * substrings, then calls the next processor in the chain. - * - * @param forbiddenSubStrings - * the List of forbidden substrings - * @param next - * the next processor in the chain - * @throws NullPointerException - * if forbiddenSubStrings, one of its elements or next is null - * @throws IllegalArgumentException - * if forbiddenSubStrings is empty - */ - public ForbidSubStr(final List forbiddenSubStrings, final CellProcessor next) { - super(next); - checkPreconditions(forbiddenSubStrings); - checkAndAddForbiddenStrings(forbiddenSubStrings); - } - - /** - * Constructs a new ForbidSubStr processor which ensures the input doesn't contain the supplied substring, - * then calls the next processor in the chain. - * - * @param forbiddenSubString - * the forbidden substring - * @param next - * the next processor in the chain - * @throws NullPointerException - * if forbiddenSubString or next is null - */ - public ForbidSubStr(final String forbiddenSubString, final CellProcessor next) { - this(new String[] { forbiddenSubString }, next); - } - - /** - * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied - * substrings, then calls the next processor in the chain. - * - * @param forbiddenSubStrings - * the forbidden substrings - * @param next - * the next processor in the chain - * @throws NullPointerException - * if forbiddenSubStrings, one of its elements or next is null - * @throws IllegalArgumentException - * if forbiddenSubStrings is empty - */ - public ForbidSubStr(final String[] forbiddenSubStrings, final CellProcessor next) { - super(next); - checkPreconditions(forbiddenSubStrings); - checkAndAddForbiddenStrings(forbiddenSubStrings); - } - - /** - * Checks the preconditions for creating a new ForbidSubStr processor with a List of forbidden substrings. - * - * @param forbiddenSubStrings - * the forbidden substrings - * @throws NullPointerException - * if forbiddenSubStrings is null - * @throws IllegalArgumentException - * if forbiddenSubStrings is empty - */ - private static void checkPreconditions(final List forbiddenSubStrings) { - if( forbiddenSubStrings == null ) { - throw new NullPointerException("forbiddenSubStrings list should not be null"); - } else if( forbiddenSubStrings.isEmpty() ) { - throw new IllegalArgumentException("forbiddenSubStrings list should not be empty"); - } - } - - /** - * Checks the preconditions for creating a new ForbidSubStr processor with an array of forbidden substrings. - * - * @param forbiddenSubStrings - * the forbidden substrings - * @throws NullPointerException - * if forbiddenSubStrings is null - * @throws IllegalArgumentException - * if forbiddenSubStrings is empty - */ - private static void checkPreconditions(final String... forbiddenSubStrings) { - if( forbiddenSubStrings == null ) { - throw new NullPointerException("forbiddenSubStrings array should not be null"); - } else if( forbiddenSubStrings.length == 0 ) { - throw new IllegalArgumentException("forbiddenSubStrings array should not be empty"); - } - } - - /** - * Adds each forbidden substring, checking that it's not null. - * - * @param forbiddenSubStrings - * the forbidden substrings - * @throws NullPointerException - * if a forbidden substring is null - */ - private void checkAndAddForbiddenStrings(final String... forbiddenSubStrings) { - checkAndAddForbiddenStrings(Arrays.asList(forbiddenSubStrings)); - } - - /** - * Adds each forbidden substring, checking that it's not null. - * - * @param forbiddenSubStrings - * the forbidden substrings - * @throws NullPointerException - * if a forbidden substring is null - */ - private void checkAndAddForbiddenStrings(final List forbiddenSubStrings) { - for( String forbidden : forbiddenSubStrings ) { - if( forbidden == null ) { - throw new NullPointerException("forbidden substring should not be null"); - } - this.forbiddenSubStrings.add(forbidden); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if value is in the forbidden list - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final String stringValue = value.toString(); - - for( String forbidden : forbiddenSubStrings ) { - if( stringValue.contains(forbidden) ) { - throw new SuperCsvConstraintViolationException(String.format( - "'%s' contains the forbidden substring '%s'", value, forbidden), context, this); - } - } - - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * Converts the input to a String and ensures that it doesn't contain any of the supplied substrings. For example, this + * constraint might be handy when reading/writing filenames and wanting to ensure no filename contains ":", "/", etc. + * + * @since 1.10 + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ForbidSubStr extends CellProcessorAdaptor implements StringCellProcessor { + + private final List forbiddenSubStrings = new ArrayList(); + + /** + * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied + * substrings. + * + * @param forbiddenSubStrings + * the List of forbidden substrings + * @throws NullPointerException + * if forbiddenSubStrings or one of its elements is null + * @throws IllegalArgumentException + * if forbiddenSubStrings is empty + */ + public ForbidSubStr(final List forbiddenSubStrings) { + super(); + checkPreconditions(forbiddenSubStrings); + checkAndAddForbiddenStrings(forbiddenSubStrings); + } + + /** + * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied + * substrings. + * + * @param forbiddenSubStrings + * the forbidden substrings + * @throws NullPointerException + * if forbiddenSubStrings or one of its elements is null + * @throws IllegalArgumentException + * if forbiddenSubStrings is empty + */ + public ForbidSubStr(final String... forbiddenSubStrings) { + super(); + checkPreconditions(forbiddenSubStrings); + checkAndAddForbiddenStrings(forbiddenSubStrings); + } + + /** + * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied + * substrings, then calls the next processor in the chain. + * + * @param forbiddenSubStrings + * the List of forbidden substrings + * @param next + * the next processor in the chain + * @throws NullPointerException + * if forbiddenSubStrings, one of its elements or next is null + * @throws IllegalArgumentException + * if forbiddenSubStrings is empty + */ + public ForbidSubStr(final List forbiddenSubStrings, final CellProcessor next) { + super(next); + checkPreconditions(forbiddenSubStrings); + checkAndAddForbiddenStrings(forbiddenSubStrings); + } + + /** + * Constructs a new ForbidSubStr processor which ensures the input doesn't contain the supplied substring, + * then calls the next processor in the chain. + * + * @param forbiddenSubString + * the forbidden substring + * @param next + * the next processor in the chain + * @throws NullPointerException + * if forbiddenSubString or next is null + */ + public ForbidSubStr(final String forbiddenSubString, final CellProcessor next) { + this(new String[] { forbiddenSubString }, next); + } + + /** + * Constructs a new ForbidSubStr processor which ensures the input doesn't contain any of the supplied + * substrings, then calls the next processor in the chain. + * + * @param forbiddenSubStrings + * the forbidden substrings + * @param next + * the next processor in the chain + * @throws NullPointerException + * if forbiddenSubStrings, one of its elements or next is null + * @throws IllegalArgumentException + * if forbiddenSubStrings is empty + */ + public ForbidSubStr(final String[] forbiddenSubStrings, final CellProcessor next) { + super(next); + checkPreconditions(forbiddenSubStrings); + checkAndAddForbiddenStrings(forbiddenSubStrings); + } + + /** + * Checks the preconditions for creating a new ForbidSubStr processor with a List of forbidden substrings. + * + * @param forbiddenSubStrings + * the forbidden substrings + * @throws NullPointerException + * if forbiddenSubStrings is null + * @throws IllegalArgumentException + * if forbiddenSubStrings is empty + */ + private static void checkPreconditions(final List forbiddenSubStrings) { + if( forbiddenSubStrings == null ) { + throw new NullPointerException("forbiddenSubStrings list should not be null"); + } else if( forbiddenSubStrings.isEmpty() ) { + throw new IllegalArgumentException("forbiddenSubStrings list should not be empty"); + } + } + + /** + * Checks the preconditions for creating a new ForbidSubStr processor with an array of forbidden substrings. + * + * @param forbiddenSubStrings + * the forbidden substrings + * @throws NullPointerException + * if forbiddenSubStrings is null + * @throws IllegalArgumentException + * if forbiddenSubStrings is empty + */ + private static void checkPreconditions(final String... forbiddenSubStrings) { + if( forbiddenSubStrings == null ) { + throw new NullPointerException("forbiddenSubStrings array should not be null"); + } else if( forbiddenSubStrings.length == 0 ) { + throw new IllegalArgumentException("forbiddenSubStrings array should not be empty"); + } + } + + /** + * Adds each forbidden substring, checking that it's not null. + * + * @param forbiddenSubStrings + * the forbidden substrings + * @throws NullPointerException + * if a forbidden substring is null + */ + private void checkAndAddForbiddenStrings(final String... forbiddenSubStrings) { + checkAndAddForbiddenStrings(Arrays.asList(forbiddenSubStrings)); + } + + /** + * Adds each forbidden substring, checking that it's not null. + * + * @param forbiddenSubStrings + * the forbidden substrings + * @throws NullPointerException + * if a forbidden substring is null + */ + private void checkAndAddForbiddenStrings(final List forbiddenSubStrings) { + for( String forbidden : forbiddenSubStrings ) { + if( forbidden == null ) { + throw new NullPointerException("forbidden substring should not be null"); + } + this.forbiddenSubStrings.add(forbidden); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if value is in the forbidden list + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final String stringValue = value.toString(); + + for( String forbidden : forbiddenSubStrings ) { + if( stringValue.contains(forbidden) ) { + throw new SuperCsvConstraintViolationException(String.format( + "'%s' contains the forbidden substring '%s'", value, forbidden), context, this); + } + } + + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/IsIncludedIn.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/IsIncludedIn.java index df03d89b..8e47e848 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/IsIncludedIn.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/IsIncludedIn.java @@ -1,171 +1,171 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This processor ensures that the input value belongs to a specific set of given values. - * - * @since 1.50 - * @author Dominique De Vito - * @author James Bassett - */ -public class IsIncludedIn extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, - DoubleCellProcessor, LongCellProcessor, StringCellProcessor { - - private final Set possibleValues = new HashSet(); - - /** - * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of - * given values. - * - * @param possibleValues - * the Set of values - * @throws NullPointerException - * if possibleValues is null - * @throws IllegalArgumentException - * if possibleValues is empty - */ - public IsIncludedIn(final Set possibleValues) { - super(); - checkPreconditions(possibleValues); - this.possibleValues.addAll(possibleValues); - } - - /** - * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of - * given values, then calls the next processor in the chain. - * - * @param possibleValues - * the Set of values - * @param next - * the next processor in the chain - * @throws NullPointerException - * if possibleValues or next is null - * @throws IllegalArgumentException - * if possibleValues is empty - */ - public IsIncludedIn(final Set possibleValues, final CellProcessor next) { - super(next); - checkPreconditions(possibleValues); - this.possibleValues.addAll(possibleValues); - } - - /** - * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of - * given values. - * - * @param possibleValues - * the array of values - * @throws NullPointerException - * if possibleValues is null - * @throws IllegalArgumentException - * if possibleValues is empty - */ - public IsIncludedIn(final Object[] possibleValues) { - super(); - checkPreconditions(possibleValues); - Collections.addAll(this.possibleValues, possibleValues); - } - - /** - * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of - * given values, then calls the next processor in the chain. - * - * @param possibleValues - * the array of values - * @param next - * the next processor in the chain - * @throws NullPointerException - * if possibleValues or next is null - * @throws IllegalArgumentException - * if possibleValues is empty - */ - public IsIncludedIn(final Object[] possibleValues, final CellProcessor next) { - super(next); - checkPreconditions(possibleValues); - Collections.addAll(this.possibleValues, possibleValues); - } - - /** - * Checks the preconditions for creating a new IsIncludedIn processor with a Set of Objects. - * - * @param possibleValues - * the Set of possible values - * @throws NullPointerException - * if possibleValues is null - * @throws IllegalArgumentException - * if possibleValues is empty - */ - private static void checkPreconditions(final Set possibleValues) { - if( possibleValues == null ) { - throw new NullPointerException("possibleValues Set should not be null"); - } else if( possibleValues.isEmpty() ) { - throw new IllegalArgumentException("possibleValues Set should not be empty"); - } - } - - /** - * Checks the preconditions for creating a new IsIncludedIn processor with a array of Objects. - * - * @param possibleValues - * the array of possible values - * @throws NullPointerException - * if possibleValues is null - * @throws IllegalArgumentException - * if possibleValues is empty - */ - private static void checkPreconditions(final Object... possibleValues) { - if( possibleValues == null ) { - throw new NullPointerException("possibleValues array should not be null"); - } else if( possibleValues.length == 0 ) { - throw new IllegalArgumentException("possibleValues array should not be empty"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if value isn't one of the possible values - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( !possibleValues.contains(value) ) { - throw new SuperCsvConstraintViolationException(String.format("'%s' is not included in the allowed set of values", value), - context, this); - } - - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This processor ensures that the input value belongs to a specific set of given values. + * + * @since 1.50 + * @author Dominique De Vito + * @author James Bassett + */ +public class IsIncludedIn extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, + DoubleCellProcessor, LongCellProcessor, StringCellProcessor { + + private final Set possibleValues = new HashSet(); + + /** + * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of + * given values. + * + * @param possibleValues + * the Set of values + * @throws NullPointerException + * if possibleValues is null + * @throws IllegalArgumentException + * if possibleValues is empty + */ + public IsIncludedIn(final Set possibleValues) { + super(); + checkPreconditions(possibleValues); + this.possibleValues.addAll(possibleValues); + } + + /** + * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of + * given values, then calls the next processor in the chain. + * + * @param possibleValues + * the Set of values + * @param next + * the next processor in the chain + * @throws NullPointerException + * if possibleValues or next is null + * @throws IllegalArgumentException + * if possibleValues is empty + */ + public IsIncludedIn(final Set possibleValues, final CellProcessor next) { + super(next); + checkPreconditions(possibleValues); + this.possibleValues.addAll(possibleValues); + } + + /** + * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of + * given values. + * + * @param possibleValues + * the array of values + * @throws NullPointerException + * if possibleValues is null + * @throws IllegalArgumentException + * if possibleValues is empty + */ + public IsIncludedIn(final Object[] possibleValues) { + super(); + checkPreconditions(possibleValues); + Collections.addAll(this.possibleValues, possibleValues); + } + + /** + * Constructs a new IsIncludedIn processor, which ensures that the input value belongs to a specific set of + * given values, then calls the next processor in the chain. + * + * @param possibleValues + * the array of values + * @param next + * the next processor in the chain + * @throws NullPointerException + * if possibleValues or next is null + * @throws IllegalArgumentException + * if possibleValues is empty + */ + public IsIncludedIn(final Object[] possibleValues, final CellProcessor next) { + super(next); + checkPreconditions(possibleValues); + Collections.addAll(this.possibleValues, possibleValues); + } + + /** + * Checks the preconditions for creating a new IsIncludedIn processor with a Set of Objects. + * + * @param possibleValues + * the Set of possible values + * @throws NullPointerException + * if possibleValues is null + * @throws IllegalArgumentException + * if possibleValues is empty + */ + private static void checkPreconditions(final Set possibleValues) { + if( possibleValues == null ) { + throw new NullPointerException("possibleValues Set should not be null"); + } else if( possibleValues.isEmpty() ) { + throw new IllegalArgumentException("possibleValues Set should not be empty"); + } + } + + /** + * Checks the preconditions for creating a new IsIncludedIn processor with a array of Objects. + * + * @param possibleValues + * the array of possible values + * @throws NullPointerException + * if possibleValues is null + * @throws IllegalArgumentException + * if possibleValues is empty + */ + private static void checkPreconditions(final Object... possibleValues) { + if( possibleValues == null ) { + throw new NullPointerException("possibleValues array should not be null"); + } else if( possibleValues.length == 0 ) { + throw new IllegalArgumentException("possibleValues array should not be empty"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if value isn't one of the possible values + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( !possibleValues.contains(value) ) { + throw new SuperCsvConstraintViolationException(String.format("'%s' is not included in the allowed set of values", value), + context, this); + } + + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/LMinMax.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/LMinMax.java index b11dbcb8..5889fc4b 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/LMinMax.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/LMinMax.java @@ -1,163 +1,163 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * Converts the input data to a Long and and ensures the value is between the supplied min and max values (inclusive). - * If the data has no upper or lower bound, you should use either of MIN or MAX constants - * provided in the class. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class LMinMax extends CellProcessorAdaptor { - - /** Maximum value for a Long */ - public static final long MAX_LONG = Long.MAX_VALUE; - - /** Minimum value for a Long */ - public static final long MIN_LONG = Long.MIN_VALUE; - - /** Maximum value for an Integer */ - public static final int MAX_INTEGER = Integer.MAX_VALUE; - - /** Minimum value for an Integer */ - public static final int MIN_INTEGER = Integer.MIN_VALUE; - - /** Maximum value for a Short */ - public static final short MAX_SHORT = Short.MAX_VALUE; - - /** Minimum value for a Short */ - public static final short MIN_SHORT = Short.MIN_VALUE; - - /** Maximum value for a Character */ - public static final int MAX_CHAR = Character.MAX_VALUE; - - /** Minimum value for a Character */ - public static final int MIN_CHAR = Character.MIN_VALUE; - - /** Maximum value for 8 bits (unsigned) */ - public static final int MAX_8_BIT_UNSIGNED = 255; - - /** Minimum value for 8 bits (unsigned) */ - public static final int MIN_8_BIT_UNSIGNED = 0; - - /** Maximum value for 8 bits (signed) */ - public static final int MAX_8_BIT_SIGNED = Byte.MAX_VALUE; - - /** Minimum value for 8 bits (signed) */ - public static final int MIN_8_BIT_SIGNED = Byte.MIN_VALUE; - - private final long min; - - private final long max; - - /** - * Constructs a new LMinMax processor, which converts the input data to a Long and and ensures the value is - * between the supplied min and max values. - * - * @param min - * the minimum value (inclusive) - * @param max - * the maximum value (inclusive) - * @throws IllegalArgumentException - * if max < min - */ - public LMinMax(final long min, final long max) { - super(); - checkPreconditions(min, max); - this.min = min; - this.max = max; - } - - /** - * Constructs a new LMinMax processor, which converts the input data to a Long and and ensures the value is - * between the supplied min and max values, then calls the next processor in the chain. - * - * @param min - * the minimum value (inclusive) - * @param max - * the maximum value (inclusive) - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - * @throws IllegalArgumentException - * if max < min - */ - public LMinMax(final long min, final long max, final LongCellProcessor next) { - super(next); - checkPreconditions(min, max); - this.min = min; - this.max = max; - } - - /** - * Checks the preconditions for creating a new LMinMax processor. - * - * @param min - * the minimum value (inclusive) - * @param max - * the maximum value (inclusive) - * @throws IllegalArgumentException - * if max < min - */ - private static void checkPreconditions(final long min, final long max) { - if( max < min ) { - throw new IllegalArgumentException(String.format("max (%d) should not be < min (%d)", max, min)); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null or can't be parsed as a Long - * @throws SuperCsvConstraintViolationException - * if value, or doesn't lie between min and max (inclusive) - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final Long result; - if( value instanceof Long ) { - result = (Long) value; - } else { - try { - result = Long.parseLong(value.toString()); - } - catch(final NumberFormatException e) { - throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Long", value), context, this, - e); - } - } - - if( result < min || result > max ) { - throw new SuperCsvConstraintViolationException(String.format( - "%d does not lie between the min (%d) and max (%d) values (inclusive)", result, min, max), context, - this); - } - - return next.execute(result, context); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * Converts the input data to a Long and and ensures the value is between the supplied min and max values (inclusive). + * If the data has no upper or lower bound, you should use either of MIN or MAX constants + * provided in the class. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class LMinMax extends CellProcessorAdaptor { + + /** Maximum value for a Long */ + public static final long MAX_LONG = Long.MAX_VALUE; + + /** Minimum value for a Long */ + public static final long MIN_LONG = Long.MIN_VALUE; + + /** Maximum value for an Integer */ + public static final int MAX_INTEGER = Integer.MAX_VALUE; + + /** Minimum value for an Integer */ + public static final int MIN_INTEGER = Integer.MIN_VALUE; + + /** Maximum value for a Short */ + public static final short MAX_SHORT = Short.MAX_VALUE; + + /** Minimum value for a Short */ + public static final short MIN_SHORT = Short.MIN_VALUE; + + /** Maximum value for a Character */ + public static final int MAX_CHAR = Character.MAX_VALUE; + + /** Minimum value for a Character */ + public static final int MIN_CHAR = Character.MIN_VALUE; + + /** Maximum value for 8 bits (unsigned) */ + public static final int MAX_8_BIT_UNSIGNED = 255; + + /** Minimum value for 8 bits (unsigned) */ + public static final int MIN_8_BIT_UNSIGNED = 0; + + /** Maximum value for 8 bits (signed) */ + public static final int MAX_8_BIT_SIGNED = Byte.MAX_VALUE; + + /** Minimum value for 8 bits (signed) */ + public static final int MIN_8_BIT_SIGNED = Byte.MIN_VALUE; + + private final long min; + + private final long max; + + /** + * Constructs a new LMinMax processor, which converts the input data to a Long and and ensures the value is + * between the supplied min and max values. + * + * @param min + * the minimum value (inclusive) + * @param max + * the maximum value (inclusive) + * @throws IllegalArgumentException + * if max < min + */ + public LMinMax(final long min, final long max) { + super(); + checkPreconditions(min, max); + this.min = min; + this.max = max; + } + + /** + * Constructs a new LMinMax processor, which converts the input data to a Long and and ensures the value is + * between the supplied min and max values, then calls the next processor in the chain. + * + * @param min + * the minimum value (inclusive) + * @param max + * the maximum value (inclusive) + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + * @throws IllegalArgumentException + * if max < min + */ + public LMinMax(final long min, final long max, final LongCellProcessor next) { + super(next); + checkPreconditions(min, max); + this.min = min; + this.max = max; + } + + /** + * Checks the preconditions for creating a new LMinMax processor. + * + * @param min + * the minimum value (inclusive) + * @param max + * the maximum value (inclusive) + * @throws IllegalArgumentException + * if max < min + */ + private static void checkPreconditions(final long min, final long max) { + if( max < min ) { + throw new IllegalArgumentException(String.format("max (%d) should not be < min (%d)", max, min)); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null or can't be parsed as a Long + * @throws SuperCsvConstraintViolationException + * if value, or doesn't lie between min and max (inclusive) + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final Long result; + if( value instanceof Long ) { + result = (Long) value; + } else { + try { + result = Long.parseLong(value.toString()); + } + catch(final NumberFormatException e) { + throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Long", value), context, this, + e); + } + } + + if( result < min || result > max ) { + throw new SuperCsvConstraintViolationException(String.format( + "%d does not lie between the min (%d) and max (%d) values (inclusive)", result, min, max), context, + this); + } + + return next.execute(result, context); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/NotNull.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/NotNull.java index 33e22b27..f247291c 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/NotNull.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/NotNull.java @@ -1,75 +1,75 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This processor ensures that the input is not null. - *

- * You should only use this processor when a column must be non-null, but you do not need to apply any other processor - * to the column (i.e. a mandatory String column with no other conversions or constraints) - *

- * If you apply other processors to the column, you can safely omit this processor as all other processors should do a - * null-check on its input. - * - * @since 1.50 - * @author Dominique De Vito - */ -public class NotNull extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, - LongCellProcessor, StringCellProcessor { - - /** - * Constructs a new NotNull which ensures that the input is not null. - */ - public NotNull() { - super(); - } - - /** - * Constructs a new NotNull which ensures that the input is not null, then calls the next - * processor in the chain. All other processor should check for null inputs, so this constructor is not - * typically required. - * - * @param next - * the next processor in the chain - */ - public NotNull(final CellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - */ - public Object execute(final Object value, final CsvContext context) { - if (value == null){ - throw new SuperCsvConstraintViolationException("null value encountered", context, this); - } - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This processor ensures that the input is not null. + *

+ * You should only use this processor when a column must be non-null, but you do not need to apply any other processor + * to the column (i.e. a mandatory String column with no other conversions or constraints) + *

+ * If you apply other processors to the column, you can safely omit this processor as all other processors should do a + * null-check on its input. + * + * @since 1.50 + * @author Dominique De Vito + */ +public class NotNull extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, + LongCellProcessor, StringCellProcessor { + + /** + * Constructs a new NotNull which ensures that the input is not null. + */ + public NotNull() { + super(); + } + + /** + * Constructs a new NotNull which ensures that the input is not null, then calls the next + * processor in the chain. All other processor should check for null inputs, so this constructor is not + * typically required. + * + * @param next + * the next processor in the chain + */ + public NotNull(final CellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + */ + public Object execute(final Object value, final CsvContext context) { + if (value == null){ + throw new SuperCsvConstraintViolationException("null value encountered", context, this); + } + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireHashCode.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireHashCode.java index 3651550c..47c3c9eb 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireHashCode.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireHashCode.java @@ -1,144 +1,144 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.HashSet; -import java.util.Set; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This processor converts the input to a String, and ensures that the input's hash function matches any of a given set - * of hashcodes. Lookup time is O(1). - *

- * This constraint is a very efficient way of ensuring constant expressions are present in certain columns of the CSV - * file, such as "BOSS", "EMPLOYEE", or when a column denotes an action to be taken for the input line such as "D" - * (delete), "I" (insert), ... - *

- * - * @since 1.50 - * @author Kasper B. Graversen - * @author James Bassett - */ -public class RequireHashCode extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, - DoubleCellProcessor, LongCellProcessor, StringCellProcessor { - - private final Set requiredHashCodes = new HashSet(); - - /** - * Constructs a new RequireHashCode processor, which converts the input to a String, and ensures that the - * input's hash function matches any of a given set of hashcodes. - * - * @param requiredHashcodes - * one or more hashcodes - * @throws NullPointerException - * if requiredHashcodes is null - * @throws IllegalArgumentException - * if requiredHashcodes is empty - */ - public RequireHashCode(final int... requiredHashcodes) { - super(); - checkPreconditions(requiredHashcodes); - for( final int hash : requiredHashcodes ) { - this.requiredHashCodes.add(hash); - } - } - - /** - * Constructs a new RequireHashCode processor, which converts the input to a String, ensures that the - * input's hash function matches the supplied hashcode, then calls the next processor in the chain. - * - * @param requiredHashcode - * the required hashcode - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public RequireHashCode(final int requiredHashcode, final CellProcessor next) { - this(new int[] { requiredHashcode }, next); - } - - /** - * Constructs a new RequireHashCode processor, which converts the input to a String, ensures that the - * input's hash function matches any of a given set of hashcodes, then calls the next processor in the chain. - * - * @param requiredHashcodes - * one or more hashcodes - * @param next - * the next processor in the chain - * @throws NullPointerException - * if requiredHashcodes or next is null - * @throws IllegalArgumentException - * if requiredHashcodes is empty - */ - public RequireHashCode(final int[] requiredHashcodes, final CellProcessor next) { - super(next); - checkPreconditions(requiredHashcodes); - for( final int hash : requiredHashcodes ) { - this.requiredHashCodes.add(hash); - } - } - - /** - * Checks the preconditions for creating a new RequireHashCode processor. - * - * @param requiredHashcodes - * the supplied hashcodes - * @throws NullPointerException - * if requiredHashcodes is null - * @throws IllegalArgumentException - * if requiredHashcodes is empty - */ - private static void checkPreconditions(final int... requiredHashcodes) { - if( requiredHashcodes == null ) { - throw new NullPointerException("requiredHashcodes should not be null"); - } else if( requiredHashcodes.length == 0 ) { - throw new IllegalArgumentException("requiredHashcodes should not be empty"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if value isn't one of the required hash codes - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - int hash = value.hashCode(); - if( !requiredHashCodes.contains(hash) ) { - throw new SuperCsvConstraintViolationException(String.format( - "the hashcode of %d for value '%s' does not match any of the required hashcodes", hash, value), - context, this); - } - - return next.execute(value, context); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.HashSet; +import java.util.Set; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This processor converts the input to a String, and ensures that the input's hash function matches any of a given set + * of hashcodes. Lookup time is O(1). + *

+ * This constraint is a very efficient way of ensuring constant expressions are present in certain columns of the CSV + * file, such as "BOSS", "EMPLOYEE", or when a column denotes an action to be taken for the input line such as "D" + * (delete), "I" (insert), ... + *

+ * + * @since 1.50 + * @author Kasper B. Graversen + * @author James Bassett + */ +public class RequireHashCode extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, + DoubleCellProcessor, LongCellProcessor, StringCellProcessor { + + private final Set requiredHashCodes = new HashSet(); + + /** + * Constructs a new RequireHashCode processor, which converts the input to a String, and ensures that the + * input's hash function matches any of a given set of hashcodes. + * + * @param requiredHashcodes + * one or more hashcodes + * @throws NullPointerException + * if requiredHashcodes is null + * @throws IllegalArgumentException + * if requiredHashcodes is empty + */ + public RequireHashCode(final int... requiredHashcodes) { + super(); + checkPreconditions(requiredHashcodes); + for( final int hash : requiredHashcodes ) { + this.requiredHashCodes.add(hash); + } + } + + /** + * Constructs a new RequireHashCode processor, which converts the input to a String, ensures that the + * input's hash function matches the supplied hashcode, then calls the next processor in the chain. + * + * @param requiredHashcode + * the required hashcode + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public RequireHashCode(final int requiredHashcode, final CellProcessor next) { + this(new int[] { requiredHashcode }, next); + } + + /** + * Constructs a new RequireHashCode processor, which converts the input to a String, ensures that the + * input's hash function matches any of a given set of hashcodes, then calls the next processor in the chain. + * + * @param requiredHashcodes + * one or more hashcodes + * @param next + * the next processor in the chain + * @throws NullPointerException + * if requiredHashcodes or next is null + * @throws IllegalArgumentException + * if requiredHashcodes is empty + */ + public RequireHashCode(final int[] requiredHashcodes, final CellProcessor next) { + super(next); + checkPreconditions(requiredHashcodes); + for( final int hash : requiredHashcodes ) { + this.requiredHashCodes.add(hash); + } + } + + /** + * Checks the preconditions for creating a new RequireHashCode processor. + * + * @param requiredHashcodes + * the supplied hashcodes + * @throws NullPointerException + * if requiredHashcodes is null + * @throws IllegalArgumentException + * if requiredHashcodes is empty + */ + private static void checkPreconditions(final int... requiredHashcodes) { + if( requiredHashcodes == null ) { + throw new NullPointerException("requiredHashcodes should not be null"); + } else if( requiredHashcodes.length == 0 ) { + throw new IllegalArgumentException("requiredHashcodes should not be empty"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if value isn't one of the required hash codes + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + int hash = value.hashCode(); + if( !requiredHashCodes.contains(hash) ) { + throw new SuperCsvConstraintViolationException(String.format( + "the hashcode of %d for value '%s' does not match any of the required hashcodes", hash, value), + context, this); + } + + return next.execute(value, context); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireSubStr.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireSubStr.java index 1ee7fe45..547587ab 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireSubStr.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireSubStr.java @@ -1,198 +1,198 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * Converts the input to a String and ensures that the input contains at least one of the specified substrings. - * - * @since 1.10 - * @author Kasper B. Graversen - * @author James Bassett - */ -public class RequireSubStr extends CellProcessorAdaptor implements StringCellProcessor { - - private final List requiredSubStrings = new ArrayList(); - - /** - * Converts the input to a String and ensures that the input contains at least one of the specified substrings. - * - * @param requiredSubStrings - * the required substrings - * @throws NullPointerException - * if requiredSubStrings or one of its elements is null - * @throws IllegalArgumentException - * if requiredSubStrings is empty - */ - public RequireSubStr(final String... requiredSubStrings) { - super(); - checkPreconditions(requiredSubStrings); - checkAndAddRequiredSubStrings(requiredSubStrings); - } - - /** - * Converts the input to a String, ensures that the input contains at least one of the specified substrings, then - * calls the next processor in the chain. - * - * @param requiredSubStrings - * the List of required substrings - * @param next - * the next processor in the chain - * @throws NullPointerException - * if requiredSubStrings, one of its elements or next is null - * @throws IllegalArgumentException - * if requiredSubStrings is empty - */ - public RequireSubStr(final List requiredSubStrings, final CellProcessor next) { - super(next); - checkPreconditions(requiredSubStrings); - checkAndAddRequiredSubStrings(requiredSubStrings); - } - - /** - * Converts the input to a String, ensures that the input contains the specified substring, then calls the next - * processor in the chain. - * - * @param requiredSubString - * the required substring - * @param next - * the next processor in the chain - * @throws NullPointerException - * if requiredSubString or next is null - */ - public RequireSubStr(final String requiredSubString, final CellProcessor next) { - super(next); - checkPreconditions(requiredSubString); - checkAndAddRequiredSubStrings(requiredSubString); - } - - /** - * Converts the input to a String, ensures that the input contains at least one of the specified substrings, then - * calls the next processor in the chain. - * - * @param requiredSubStrings - * the List of required substrings - * @param next - * the next processor in the chain - * @throws NullPointerException - * if requiredSubStrings, one of its elements or next is null - * @throws IllegalArgumentException - * if requiredSubStrings is empty - */ - public RequireSubStr(final String[] requiredSubStrings, final CellProcessor next) { - super(next); - checkPreconditions(requiredSubStrings); - checkAndAddRequiredSubStrings(requiredSubStrings); - } - - /** - * Checks the preconditions for creating a new RequireSubStr processor with an array of Strings. - * - * @param requiredSubStrings - * the required substrings - * @throws NullPointerException - * if requiredSubStrings or one of its elements is null - * @throws IllegalArgumentException - * if requiredSubStrings is empty - */ - private static void checkPreconditions(String... requiredSubStrings) { - if( requiredSubStrings == null ) { - throw new NullPointerException("requiredSubStrings array should not be null"); - } else if( requiredSubStrings.length == 0 ) { - throw new IllegalArgumentException("requiredSubStrings array should not be empty"); - } - } - - /** - * Checks the preconditions for creating a new RequireSubStr processor with a List of Strings. - * - * @param requiredSubStrings - * the required substrings - * @throws NullPointerException - * if requiredSubStrings or one of its elements is null - * @throws IllegalArgumentException - * if requiredSubStrings is empty - */ - private static void checkPreconditions(List requiredSubStrings) { - if( requiredSubStrings == null ) { - throw new NullPointerException("requiredSubStrings List should not be null"); - } else if( requiredSubStrings.isEmpty() ) { - throw new IllegalArgumentException("requiredSubStrings List should not be empty"); - } - } - - /** - * Adds each required substring, checking that it's not null. - * - * @param requiredSubStrings - * the required substrings - * @throws NullPointerException - * if a required substring is null - */ - private void checkAndAddRequiredSubStrings(final List requiredSubStrings) { - for( String required : requiredSubStrings ) { - if( required == null ) { - throw new NullPointerException("required substring should not be null"); - } - this.requiredSubStrings.add(required); - } - } - - /** - * Adds each required substring, checking that it's not null. - * - * @param requiredSubStrings - * the required substrings - * @throws NullPointerException - * if a required substring is null - */ - private void checkAndAddRequiredSubStrings(final String... requiredSubStrings) { - checkAndAddRequiredSubStrings(Arrays.asList(requiredSubStrings)); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if value doesn't contain any of the required substrings - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final String stringValue = value.toString(); - - for( final String required : requiredSubStrings ) { - if( stringValue.contains(required) ) { - return next.execute(value, context); // just need to match a single substring - } - } - - throw new SuperCsvConstraintViolationException(String.format("'%s' does not contain any of the required substrings", value), - context, this); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * Converts the input to a String and ensures that the input contains at least one of the specified substrings. + * + * @since 1.10 + * @author Kasper B. Graversen + * @author James Bassett + */ +public class RequireSubStr extends CellProcessorAdaptor implements StringCellProcessor { + + private final List requiredSubStrings = new ArrayList(); + + /** + * Converts the input to a String and ensures that the input contains at least one of the specified substrings. + * + * @param requiredSubStrings + * the required substrings + * @throws NullPointerException + * if requiredSubStrings or one of its elements is null + * @throws IllegalArgumentException + * if requiredSubStrings is empty + */ + public RequireSubStr(final String... requiredSubStrings) { + super(); + checkPreconditions(requiredSubStrings); + checkAndAddRequiredSubStrings(requiredSubStrings); + } + + /** + * Converts the input to a String, ensures that the input contains at least one of the specified substrings, then + * calls the next processor in the chain. + * + * @param requiredSubStrings + * the List of required substrings + * @param next + * the next processor in the chain + * @throws NullPointerException + * if requiredSubStrings, one of its elements or next is null + * @throws IllegalArgumentException + * if requiredSubStrings is empty + */ + public RequireSubStr(final List requiredSubStrings, final CellProcessor next) { + super(next); + checkPreconditions(requiredSubStrings); + checkAndAddRequiredSubStrings(requiredSubStrings); + } + + /** + * Converts the input to a String, ensures that the input contains the specified substring, then calls the next + * processor in the chain. + * + * @param requiredSubString + * the required substring + * @param next + * the next processor in the chain + * @throws NullPointerException + * if requiredSubString or next is null + */ + public RequireSubStr(final String requiredSubString, final CellProcessor next) { + super(next); + checkPreconditions(requiredSubString); + checkAndAddRequiredSubStrings(requiredSubString); + } + + /** + * Converts the input to a String, ensures that the input contains at least one of the specified substrings, then + * calls the next processor in the chain. + * + * @param requiredSubStrings + * the List of required substrings + * @param next + * the next processor in the chain + * @throws NullPointerException + * if requiredSubStrings, one of its elements or next is null + * @throws IllegalArgumentException + * if requiredSubStrings is empty + */ + public RequireSubStr(final String[] requiredSubStrings, final CellProcessor next) { + super(next); + checkPreconditions(requiredSubStrings); + checkAndAddRequiredSubStrings(requiredSubStrings); + } + + /** + * Checks the preconditions for creating a new RequireSubStr processor with an array of Strings. + * + * @param requiredSubStrings + * the required substrings + * @throws NullPointerException + * if requiredSubStrings or one of its elements is null + * @throws IllegalArgumentException + * if requiredSubStrings is empty + */ + private static void checkPreconditions(String... requiredSubStrings) { + if( requiredSubStrings == null ) { + throw new NullPointerException("requiredSubStrings array should not be null"); + } else if( requiredSubStrings.length == 0 ) { + throw new IllegalArgumentException("requiredSubStrings array should not be empty"); + } + } + + /** + * Checks the preconditions for creating a new RequireSubStr processor with a List of Strings. + * + * @param requiredSubStrings + * the required substrings + * @throws NullPointerException + * if requiredSubStrings or one of its elements is null + * @throws IllegalArgumentException + * if requiredSubStrings is empty + */ + private static void checkPreconditions(List requiredSubStrings) { + if( requiredSubStrings == null ) { + throw new NullPointerException("requiredSubStrings List should not be null"); + } else if( requiredSubStrings.isEmpty() ) { + throw new IllegalArgumentException("requiredSubStrings List should not be empty"); + } + } + + /** + * Adds each required substring, checking that it's not null. + * + * @param requiredSubStrings + * the required substrings + * @throws NullPointerException + * if a required substring is null + */ + private void checkAndAddRequiredSubStrings(final List requiredSubStrings) { + for( String required : requiredSubStrings ) { + if( required == null ) { + throw new NullPointerException("required substring should not be null"); + } + this.requiredSubStrings.add(required); + } + } + + /** + * Adds each required substring, checking that it's not null. + * + * @param requiredSubStrings + * the required substrings + * @throws NullPointerException + * if a required substring is null + */ + private void checkAndAddRequiredSubStrings(final String... requiredSubStrings) { + checkAndAddRequiredSubStrings(Arrays.asList(requiredSubStrings)); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if value doesn't contain any of the required substrings + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final String stringValue = value.toString(); + + for( final String required : requiredSubStrings ) { + if( stringValue.contains(required) ) { + return next.execute(value, context); // just need to match a single substring + } + } + + throw new SuperCsvConstraintViolationException(String.format("'%s' does not contain any of the required substrings", value), + context, this); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrMinMax.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrMinMax.java index daa33dac..1b4e0340 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrMinMax.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrMinMax.java @@ -1,118 +1,118 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This constraint ensures that the input data has a string length between the supplied min and max values (both - * inclusive). Should the input be anything different from a String, it will be converted to a string using the input's - * toString() method. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class StrMinMax extends CellProcessorAdaptor implements StringCellProcessor { - - private final long min; - private final long max; - - /** - * Constructs a new StrMinMax processor, which ensures that the input data has a string length between the - * supplied min and max values (both inclusive). - * - * @param min - * the minimum String length - * @param max - * the maximum String length - * @throws IllegalArgumentException - * if max < min, or min is < 0 - */ - public StrMinMax(final long min, final long max) { - super(); - checkPreconditions(min, max); - this.min = min; - this.max = max; - } - - /** - * Constructs a new StrMinMax processor, which ensures that the input data has a string length between the - * supplied min and max values (both inclusive), then calls the next processor in the chain. - * - * @param min - * the minimum String length - * @param max - * the maximum String length - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - * @throws IllegalArgumentException - * if max < min, or min is < 0 - */ - public StrMinMax(final long min, final long max, final CellProcessor next) { - super(next); - checkPreconditions(min, max); - this.min = min; - this.max = max; - } - - /** - * Checks the preconditions for creating a new StrMinMax processor. - * - * @param min - * the minimum String length - * @param max - * the maximum String length - * @throws IllegalArgumentException - * if max < min, or min is < 0 - */ - private static void checkPreconditions(final long min, final long max) { - if( max < min ) { - throw new IllegalArgumentException(String.format("max (%d) should not be < min (%d)", max, min)); - } - if( min < 0 ) { - throw new IllegalArgumentException(String.format("min length (%d) should not be < 0", min)); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if length is < min or length > max - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final String stringValue = value.toString(); - final int length = stringValue.length(); - if( length < min || length > max ) { - throw new SuperCsvConstraintViolationException(String.format( - "the length (%d) of value '%s' does not lie between the min (%d) and max (%d) values (inclusive)", - length, stringValue, min, max), context, this); - } - - return next.execute(stringValue, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This constraint ensures that the input data has a string length between the supplied min and max values (both + * inclusive). Should the input be anything different from a String, it will be converted to a string using the input's + * toString() method. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class StrMinMax extends CellProcessorAdaptor implements StringCellProcessor { + + private final long min; + private final long max; + + /** + * Constructs a new StrMinMax processor, which ensures that the input data has a string length between the + * supplied min and max values (both inclusive). + * + * @param min + * the minimum String length + * @param max + * the maximum String length + * @throws IllegalArgumentException + * if max < min, or min is < 0 + */ + public StrMinMax(final long min, final long max) { + super(); + checkPreconditions(min, max); + this.min = min; + this.max = max; + } + + /** + * Constructs a new StrMinMax processor, which ensures that the input data has a string length between the + * supplied min and max values (both inclusive), then calls the next processor in the chain. + * + * @param min + * the minimum String length + * @param max + * the maximum String length + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + * @throws IllegalArgumentException + * if max < min, or min is < 0 + */ + public StrMinMax(final long min, final long max, final CellProcessor next) { + super(next); + checkPreconditions(min, max); + this.min = min; + this.max = max; + } + + /** + * Checks the preconditions for creating a new StrMinMax processor. + * + * @param min + * the minimum String length + * @param max + * the maximum String length + * @throws IllegalArgumentException + * if max < min, or min is < 0 + */ + private static void checkPreconditions(final long min, final long max) { + if( max < min ) { + throw new IllegalArgumentException(String.format("max (%d) should not be < min (%d)", max, min)); + } + if( min < 0 ) { + throw new IllegalArgumentException(String.format("min length (%d) should not be < 0", min)); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if length is < min or length > max + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final String stringValue = value.toString(); + final int length = stringValue.length(); + if( length < min || length > max ) { + throw new SuperCsvConstraintViolationException(String.format( + "the length (%d) of value '%s' does not lie between the min (%d) and max (%d) values (inclusive)", + length, stringValue, min, max), context, this); + } + + return next.execute(stringValue, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmpty.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmpty.java index 68e8b154..4819bb33 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmpty.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmpty.java @@ -1,84 +1,84 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This processor checks if the input is null or an empty string, and raises an exception in that case. In all - * other cases, the next processor in the chain is invoked. - *

- * You should only use this processor, when a column must be non-null, but you do not need to apply any other processor - * to the column. - *

- * If you apply other processors to the column, you can safely omit this processor as all other processors should do a - * null-check on its input. - * - * @since 1.50 - * @author Dominique De Vito - */ -public class StrNotNullOrEmpty extends CellProcessorAdaptor implements StringCellProcessor { - - /** - * Constructs a new StrNotNullOrEmpty processor, which checks for null/empty Strings. - */ - public StrNotNullOrEmpty() { - super(); - } - - /** - * Constructs a new StrNotNullOrEmpty processor, which checks for null/empty Strings, then calls the next - * processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public StrNotNullOrEmpty(final CellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null or isn't a String - * @throws SuperCsvConstraintViolationException - * if value is an empty String - */ - public Object execute(final Object value, final CsvContext context) { - if (value == null){ - throw new SuperCsvConstraintViolationException("the String should not be null", context, this); - } - - if( value instanceof String ) { - final String stringValue = (String) value; - if( stringValue.length() == 0 ) { - throw new SuperCsvConstraintViolationException("the String should not be empty", context, this); - } - } else { - throw new SuperCsvCellProcessorException(String.class, value, context, this); - } - - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This processor checks if the input is null or an empty string, and raises an exception in that case. In all + * other cases, the next processor in the chain is invoked. + *

+ * You should only use this processor, when a column must be non-null, but you do not need to apply any other processor + * to the column. + *

+ * If you apply other processors to the column, you can safely omit this processor as all other processors should do a + * null-check on its input. + * + * @since 1.50 + * @author Dominique De Vito + */ +public class StrNotNullOrEmpty extends CellProcessorAdaptor implements StringCellProcessor { + + /** + * Constructs a new StrNotNullOrEmpty processor, which checks for null/empty Strings. + */ + public StrNotNullOrEmpty() { + super(); + } + + /** + * Constructs a new StrNotNullOrEmpty processor, which checks for null/empty Strings, then calls the next + * processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public StrNotNullOrEmpty(final CellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null or isn't a String + * @throws SuperCsvConstraintViolationException + * if value is an empty String + */ + public Object execute(final Object value, final CsvContext context) { + if (value == null){ + throw new SuperCsvConstraintViolationException("the String should not be null", context, this); + } + + if( value instanceof String ) { + final String stringValue = (String) value; + if( stringValue.length() == 0 ) { + throw new SuperCsvConstraintViolationException("the String should not be empty", context, this); + } + } else { + throw new SuperCsvCellProcessorException(String.class, value, context, this); + } + + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrRegEx.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrRegEx.java index 15683002..86682c2b 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrRegEx.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrRegEx.java @@ -1,143 +1,143 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This constraint ensures that the input data matches the given regular expression. - * - * @author Dominique De Vito - * @author James Bassett - * @since 1.50 - */ -public class StrRegEx extends CellProcessorAdaptor implements StringCellProcessor { - - private final String regex; - private final Pattern regexPattern; - - private static final Map REGEX_MSGS = new HashMap(); - - /** - * Constructs a new StrRegEx processor, which ensures that the input data matches the given regular - * expression. - * - * @param regex - * the regular expression to match - * @throws NullPointerException - * if regex is null - * @throws IllegalArgumentException - * if regex is empty - * @throws PatternSyntaxException - * if regex is not a valid regular expression - */ - public StrRegEx(final String regex) { - super(); - checkPreconditions(regex); - this.regexPattern = Pattern.compile(regex); - this.regex = regex; - } - - /** - * Constructs a new StrRegEx processor, which ensures that the input data matches the given regular - * expression, then calls the next processor in the chain. - * - * @param regex - * the regular expression to match - * @param next - * the next processor in the chain - * @throws NullPointerException - * if regex is null - * @throws IllegalArgumentException - * if regex is empty - * @throws PatternSyntaxException - * if regex is not a valid regular expression - */ - public StrRegEx(final String regex, final StringCellProcessor next) { - super(next); - checkPreconditions(regex); - this.regexPattern = Pattern.compile(regex); - this.regex = regex; - } - - /** - * Checks the preconditions for creating a new StrRegEx processor. - * - * @param regex - * the regular expression to match - * @throws NullPointerException - * if regex is null - * @throws IllegalArgumentException - * if regex is empty - */ - private static void checkPreconditions(final String regex) { - if( regex == null ) { - throw new NullPointerException("regex should not be null"); - } else if( regex.length() == 0 ) { - throw new IllegalArgumentException("regex should not be empty"); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if value doesn't match the regular expression - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final boolean matches = regexPattern.matcher((String) value).matches(); - if( !matches ) { - final String msg = REGEX_MSGS.get(regex); - if( msg == null ) { - throw new SuperCsvConstraintViolationException(String.format( - "'%s' does not match the regular expression '%s'", value, regex), context, this); - } else { - throw new SuperCsvConstraintViolationException( - String.format("'%s' does not match the constraint '%s' defined by the regular expression '%s'", - value, msg, regex), context, this); - } - } - return next.execute(value, context); - } - - /** - * Register a message detailing in plain language the constraint representing a regular expression. For example, the - * regular expression \d{0,6}(\.\d{0,3})? could be associated with the message - * "up to 6 digits whole digits, followed by up to 3 fractional digits". - * - * @param regex - * the regular expression - * @param message - * the message to associate with the regex - */ - public static void registerMessage(String regex, String message) { - REGEX_MSGS.put(regex, message); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This constraint ensures that the input data matches the given regular expression. + * + * @author Dominique De Vito + * @author James Bassett + * @since 1.50 + */ +public class StrRegEx extends CellProcessorAdaptor implements StringCellProcessor { + + private final String regex; + private final Pattern regexPattern; + + private static final Map REGEX_MSGS = new HashMap(); + + /** + * Constructs a new StrRegEx processor, which ensures that the input data matches the given regular + * expression. + * + * @param regex + * the regular expression to match + * @throws NullPointerException + * if regex is null + * @throws IllegalArgumentException + * if regex is empty + * @throws PatternSyntaxException + * if regex is not a valid regular expression + */ + public StrRegEx(final String regex) { + super(); + checkPreconditions(regex); + this.regexPattern = Pattern.compile(regex); + this.regex = regex; + } + + /** + * Constructs a new StrRegEx processor, which ensures that the input data matches the given regular + * expression, then calls the next processor in the chain. + * + * @param regex + * the regular expression to match + * @param next + * the next processor in the chain + * @throws NullPointerException + * if regex is null + * @throws IllegalArgumentException + * if regex is empty + * @throws PatternSyntaxException + * if regex is not a valid regular expression + */ + public StrRegEx(final String regex, final StringCellProcessor next) { + super(next); + checkPreconditions(regex); + this.regexPattern = Pattern.compile(regex); + this.regex = regex; + } + + /** + * Checks the preconditions for creating a new StrRegEx processor. + * + * @param regex + * the regular expression to match + * @throws NullPointerException + * if regex is null + * @throws IllegalArgumentException + * if regex is empty + */ + private static void checkPreconditions(final String regex) { + if( regex == null ) { + throw new NullPointerException("regex should not be null"); + } else if( regex.length() == 0 ) { + throw new IllegalArgumentException("regex should not be empty"); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if value doesn't match the regular expression + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final boolean matches = regexPattern.matcher((String) value).matches(); + if( !matches ) { + final String msg = REGEX_MSGS.get(regex); + if( msg == null ) { + throw new SuperCsvConstraintViolationException(String.format( + "'%s' does not match the regular expression '%s'", value, regex), context, this); + } else { + throw new SuperCsvConstraintViolationException( + String.format("'%s' does not match the constraint '%s' defined by the regular expression '%s'", + value, msg, regex), context, this); + } + } + return next.execute(value, context); + } + + /** + * Register a message detailing in plain language the constraint representing a regular expression. For example, the + * regular expression \d{0,6}(\.\d{0,3})? could be associated with the message + * "up to 6 digits whole digits, followed by up to 3 fractional digits". + * + * @param regex + * the regular expression + * @param message + * the message to associate with the regex + */ + public static void registerMessage(String regex, String message) { + REGEX_MSGS.put(regex, message); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Strlen.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Strlen.java index 9af51bfc..fb9be446 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Strlen.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Strlen.java @@ -1,150 +1,150 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.HashSet; -import java.util.Set; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * This processor ensures that the input String has a length equal to any of the supplied lengths. The length - * constraints must all be > 0 or an exception is thrown. Lookup time is O(1). - * - * @author Kasper B. Graversen - * @author Dominique De Vito - * @author James Bassett - */ -public class Strlen extends CellProcessorAdaptor implements StringCellProcessor { - - private final Set requiredLengths = new HashSet(); - - /** - * Constructs a new Strlen processor, which ensures that the input String has a length equal to any of the - * supplied lengths. - * - * @param requiredLengths - * one or more required lengths - * @throws NullPointerException - * if requiredLengths is null - * @throws IllegalArgumentException - * if requiredLengths is empty or contains a negative length - */ - public Strlen(final int... requiredLengths) { - super(); - checkPreconditions(requiredLengths); - checkAndAddLengths(requiredLengths); - } - - /** - * Constructs a new Strlen processor, which ensures that the input String has a length equal to the - * supplied length, then calls the next processor in the chain. - * - * @param requiredLength - * the required length - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - * @throws IllegalArgumentException - * if requiredLength is negative - */ - public Strlen(final int requiredLength, final CellProcessor next) { - this(new int[] { requiredLength }, next); - } - - /** - * Constructs a new Strlen processor, which ensures that the input String has a length equal to any of the - * supplied lengths, then calls the next processor in the chain. - * - * @param requiredLengths - * one or more required lengths - * @param next - * the next processor in the chain - * @throws NullPointerException - * if requiredLengths or next is null - * @throws IllegalArgumentException - * if requiredLengths is empty or contains a negative length - */ - public Strlen(final int[] requiredLengths, final CellProcessor next) { - super(next); - checkPreconditions(requiredLengths); - checkAndAddLengths(requiredLengths); - } - - /** - * Checks the preconditions for creating a new Strlen processor. - * - * @param requiredLengths - * one or more required lengths - * @throws NullPointerException - * if requiredLengths is null - * @throws IllegalArgumentException - * if requiredLengths is empty - */ - private static void checkPreconditions(final int... requiredLengths) { - if( requiredLengths == null ) { - throw new NullPointerException("requiredLengths should not be null"); - } else if( requiredLengths.length == 0 ) { - throw new IllegalArgumentException("requiredLengths should not be empty"); - } - } - - /** - * Adds each required length, ensuring it isn't negative. - * - * @param requiredLengths - * one or more required lengths - * @throws IllegalArgumentException - * if a supplied length is negative - */ - private void checkAndAddLengths(final int... requiredLengths) { - for( final int length : requiredLengths ) { - if( length < 0 ) { - throw new IllegalArgumentException(String.format("required length cannot be negative but was %d", - length)); - } - this.requiredLengths.add(length); - } - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if the length of value isn't one of the required lengths - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - final String stringValue = value.toString(); - final int length = stringValue.length(); - if( !requiredLengths.contains(length) ) { - throw new SuperCsvConstraintViolationException(String.format("the length (%d) of value '%s' not any of the required lengths", - length, stringValue), context, this); - } - - return next.execute(value, context); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.HashSet; +import java.util.Set; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * This processor ensures that the input String has a length equal to any of the supplied lengths. The length + * constraints must all be > 0 or an exception is thrown. Lookup time is O(1). + * + * @author Kasper B. Graversen + * @author Dominique De Vito + * @author James Bassett + */ +public class Strlen extends CellProcessorAdaptor implements StringCellProcessor { + + private final Set requiredLengths = new HashSet(); + + /** + * Constructs a new Strlen processor, which ensures that the input String has a length equal to any of the + * supplied lengths. + * + * @param requiredLengths + * one or more required lengths + * @throws NullPointerException + * if requiredLengths is null + * @throws IllegalArgumentException + * if requiredLengths is empty or contains a negative length + */ + public Strlen(final int... requiredLengths) { + super(); + checkPreconditions(requiredLengths); + checkAndAddLengths(requiredLengths); + } + + /** + * Constructs a new Strlen processor, which ensures that the input String has a length equal to the + * supplied length, then calls the next processor in the chain. + * + * @param requiredLength + * the required length + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + * @throws IllegalArgumentException + * if requiredLength is negative + */ + public Strlen(final int requiredLength, final CellProcessor next) { + this(new int[] { requiredLength }, next); + } + + /** + * Constructs a new Strlen processor, which ensures that the input String has a length equal to any of the + * supplied lengths, then calls the next processor in the chain. + * + * @param requiredLengths + * one or more required lengths + * @param next + * the next processor in the chain + * @throws NullPointerException + * if requiredLengths or next is null + * @throws IllegalArgumentException + * if requiredLengths is empty or contains a negative length + */ + public Strlen(final int[] requiredLengths, final CellProcessor next) { + super(next); + checkPreconditions(requiredLengths); + checkAndAddLengths(requiredLengths); + } + + /** + * Checks the preconditions for creating a new Strlen processor. + * + * @param requiredLengths + * one or more required lengths + * @throws NullPointerException + * if requiredLengths is null + * @throws IllegalArgumentException + * if requiredLengths is empty + */ + private static void checkPreconditions(final int... requiredLengths) { + if( requiredLengths == null ) { + throw new NullPointerException("requiredLengths should not be null"); + } else if( requiredLengths.length == 0 ) { + throw new IllegalArgumentException("requiredLengths should not be empty"); + } + } + + /** + * Adds each required length, ensuring it isn't negative. + * + * @param requiredLengths + * one or more required lengths + * @throws IllegalArgumentException + * if a supplied length is negative + */ + private void checkAndAddLengths(final int... requiredLengths) { + for( final int length : requiredLengths ) { + if( length < 0 ) { + throw new IllegalArgumentException(String.format("required length cannot be negative but was %d", + length)); + } + this.requiredLengths.add(length); + } + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if the length of value isn't one of the required lengths + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + final String stringValue = value.toString(); + final int length = stringValue.length(); + if( !requiredLengths.contains(length) ) { + throw new SuperCsvConstraintViolationException(String.format("the length (%d) of value '%s' not any of the required lengths", + length, stringValue), context, this); + } + + return next.execute(value, context); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Unique.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Unique.java index 6dbaab74..43b52293 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Unique.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/Unique.java @@ -1,81 +1,81 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.HashSet; -import java.util.Set; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * Ensure that upon processing a CSV file (reading or writing), that values of the column all are unique. Comparison is - * based upon each elements equals() method of the objects and lookup takes O(1). - *

- * Compared to {@link UniqueHashCode} this processor potentially uses more memory, as it stores references to each - * encountered object rather than just their hashcodes. On reading huge files this can be a real memory-hazard, however, - * it ensures a true uniqueness check. - * - * @since 1.50 - * @author Kasper B. Graversen - * @author Dominique De Vito - * @author James Bassett - */ -public class Unique extends CellProcessorAdaptor { - - private final Set encounteredElements = new HashSet(); - - /** - * Constructs a new Unique processor, which ensures that all rows in a column are unique. - */ - public Unique() { - super(); - } - - /** - * Constructs a new Unique processor, which ensures that all rows in a column are unique, then calls the - * next processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public Unique(final CellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if a non-unique value is encountered - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - if( !encounteredElements.add(value) ) { - throw new SuperCsvConstraintViolationException(String.format("duplicate value '%s' encountered", value), context, this); - } - - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.HashSet; +import java.util.Set; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * Ensure that upon processing a CSV file (reading or writing), that values of the column all are unique. Comparison is + * based upon each elements equals() method of the objects and lookup takes O(1). + *

+ * Compared to {@link UniqueHashCode} this processor potentially uses more memory, as it stores references to each + * encountered object rather than just their hashcodes. On reading huge files this can be a real memory-hazard, however, + * it ensures a true uniqueness check. + * + * @since 1.50 + * @author Kasper B. Graversen + * @author Dominique De Vito + * @author James Bassett + */ +public class Unique extends CellProcessorAdaptor { + + private final Set encounteredElements = new HashSet(); + + /** + * Constructs a new Unique processor, which ensures that all rows in a column are unique. + */ + public Unique() { + super(); + } + + /** + * Constructs a new Unique processor, which ensures that all rows in a column are unique, then calls the + * next processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public Unique(final CellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if a non-unique value is encountered + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + if( !encounteredElements.add(value) ) { + throw new SuperCsvConstraintViolationException(String.format("duplicate value '%s' encountered", value), context, this); + } + + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/UniqueHashCode.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/UniqueHashCode.java index 20e96ac3..1340fa03 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/UniqueHashCode.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/UniqueHashCode.java @@ -1,83 +1,83 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import java.util.HashSet; -import java.util.Set; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.util.CsvContext; - -/** - * Ensure that upon processing a CSV file (reading or writing), that values of the column are all unique. Comparison is - * based upon each elements hashCode() method and lookup takes O(1). - *

- * Compared to {@link Unique} this processor is much more memory efficient as it only stores the set of encountered - * hashcodes rather than storing references to all encountered objects. The tradeoff being possible false positives. - *

- * Prior to v1.50 this class was named Unique but has been renamed to clarify its inner workings. - * - * @author Kasper B. Graversen - * @author Dominique De Vito - * @author James Bassett - */ -public class UniqueHashCode extends CellProcessorAdaptor { - - private final Set uniqueSet = new HashSet(); - - /** - * Constructs a new UniqueHashCode processor, which ensures that all rows in a column are unique. - */ - public UniqueHashCode() { - super(); - } - - /** - * Constructs a new UniqueHashCode processor, which ensures that all rows in a column are unique, then - * calls the next processor in the chain. - * - * @param next - * the next processor in the chain - * @throws NullPointerException - * if next is null - */ - public UniqueHashCode(final CellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - * - * @throws SuperCsvCellProcessorException - * if value is null - * @throws SuperCsvConstraintViolationException - * if a non-unique value is encountered - */ - public Object execute(final Object value, final CsvContext context) { - validateInputNotNull(value, context); - - int hash = value.hashCode(); - if( !uniqueSet.add(hash) ) { - throw new SuperCsvConstraintViolationException( - String.format("duplicate value '%s' encountered with hashcode %d", value, hash), context, this); - } - - return next.execute(value, context); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import java.util.HashSet; +import java.util.Set; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.util.CsvContext; + +/** + * Ensure that upon processing a CSV file (reading or writing), that values of the column are all unique. Comparison is + * based upon each elements hashCode() method and lookup takes O(1). + *

+ * Compared to {@link Unique} this processor is much more memory efficient as it only stores the set of encountered + * hashcodes rather than storing references to all encountered objects. The tradeoff being possible false positives. + *

+ * Prior to v1.50 this class was named Unique but has been renamed to clarify its inner workings. + * + * @author Kasper B. Graversen + * @author Dominique De Vito + * @author James Bassett + */ +public class UniqueHashCode extends CellProcessorAdaptor { + + private final Set uniqueSet = new HashSet(); + + /** + * Constructs a new UniqueHashCode processor, which ensures that all rows in a column are unique. + */ + public UniqueHashCode() { + super(); + } + + /** + * Constructs a new UniqueHashCode processor, which ensures that all rows in a column are unique, then + * calls the next processor in the chain. + * + * @param next + * the next processor in the chain + * @throws NullPointerException + * if next is null + */ + public UniqueHashCode(final CellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + * + * @throws SuperCsvCellProcessorException + * if value is null + * @throws SuperCsvConstraintViolationException + * if a non-unique value is encountered + */ + public Object execute(final Object value, final CsvContext context) { + validateInputNotNull(value, context); + + int hash = value.hashCode(); + if( !uniqueSet.add(hash) ) { + throw new SuperCsvConstraintViolationException( + String.format("duplicate value '%s' encountered with hashcode %d", value, hash), context, this); + } + + return next.execute(value, context); + } +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/package-info.java b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/package-info.java index c1b1df10..b30ead72 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/package-info.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/package-info.java @@ -1,23 +1,23 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides CellProcessor classes for enforcing constraints. - *

- * Note however, that in order for these processors to carry out their constraint logic, they may convert the input - * data. For example, the Strlen constraint, given the number 17, converts it to the string "17" before doing its length - * check. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides CellProcessor classes for enforcing constraints. + *

+ * Note however, that in order for these processors to carry out their constraint logic, they may convert the input + * data. For example, the Strlen constraint, given the number 17, converts it to the string "17" before doing its length + * check. + */ package org.supercsv.cellprocessor.constraint; \ No newline at end of file diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/BoolCellProcessor.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/BoolCellProcessor.java index 5fc15ddc..a5f54423 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/BoolCellProcessor.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/BoolCellProcessor.java @@ -1,22 +1,22 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.ift; - -/** - * Interface to indicate the a CellProcessor is capable of processing Boolean values. - */ -public interface BoolCellProcessor extends CellProcessor { -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.ift; + +/** + * Interface to indicate the a CellProcessor is capable of processing Boolean values. + */ +public interface BoolCellProcessor extends CellProcessor { +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/CellProcessor.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/CellProcessor.java index 74006f5e..92cd3287 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/CellProcessor.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/CellProcessor.java @@ -1,31 +1,31 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.ift; - -import org.supercsv.util.CsvContext; - -/** - * Defines the interface of all CellProcessors. - */ -public interface CellProcessor { - - /** - * This method is invoked by the framework when the processor needs to process data or check constraints. - * - * @since 1.0 - */ - Object execute(final Object value, final CsvContext context); -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.ift; + +import org.supercsv.util.CsvContext; + +/** + * Defines the interface of all CellProcessors. + */ +public interface CellProcessor { + + /** + * This method is invoked by the framework when the processor needs to process data or check constraints. + * + * @since 1.0 + */ + Object execute(final Object value, final CsvContext context); +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DateCellProcessor.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DateCellProcessor.java index 33628e59..cf5ec545 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DateCellProcessor.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DateCellProcessor.java @@ -1,22 +1,22 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.ift; - -/** - * Interface to indicate the a CellProcessor is capable of processing Date values. - */ -public interface DateCellProcessor extends CellProcessor { -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.ift; + +/** + * Interface to indicate the a CellProcessor is capable of processing Date values. + */ +public interface DateCellProcessor extends CellProcessor { +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DoubleCellProcessor.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DoubleCellProcessor.java index 7a4506e7..d6f26593 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DoubleCellProcessor.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/DoubleCellProcessor.java @@ -1,22 +1,22 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.ift; - -/** - * Interface to indicate the a CellProcessor is capable of processing Double values. - */ -public interface DoubleCellProcessor extends CellProcessor { -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.ift; + +/** + * Interface to indicate the a CellProcessor is capable of processing Double values. + */ +public interface DoubleCellProcessor extends CellProcessor { +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/LongCellProcessor.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/LongCellProcessor.java index 085486b5..42427025 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/LongCellProcessor.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/LongCellProcessor.java @@ -1,22 +1,22 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.ift; - -/** - * Interface to indicate the a CellProcessor is capable of processing Long values. - */ -public interface LongCellProcessor extends CellProcessor { -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.ift; + +/** + * Interface to indicate the a CellProcessor is capable of processing Long values. + */ +public interface LongCellProcessor extends CellProcessor { +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/StringCellProcessor.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/StringCellProcessor.java index 73cac131..f06566a8 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/StringCellProcessor.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/StringCellProcessor.java @@ -1,22 +1,22 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.ift; - -/** - * Interface to indicate the a CellProcessor is capable of processing String values. - */ -public interface StringCellProcessor extends CellProcessor { -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.ift; + +/** + * Interface to indicate the a CellProcessor is capable of processing String values. + */ +public interface StringCellProcessor extends CellProcessor { +} diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/package-info.java b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/package-info.java index ae0e90b0..75a6075d 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/ift/package-info.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/ift/package-info.java @@ -1,19 +1,19 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides CellProcessor interfaces, used to control/restrict how processors can be chained together. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides CellProcessor interfaces, used to control/restrict how processors can be chained together. + */ package org.supercsv.cellprocessor.ift; \ No newline at end of file diff --git a/super-csv/src/main/java/org/supercsv/cellprocessor/package-info.java b/super-csv/src/main/java/org/supercsv/cellprocessor/package-info.java index 8882c33c..b586a5a5 100644 --- a/super-csv/src/main/java/org/supercsv/cellprocessor/package-info.java +++ b/super-csv/src/main/java/org/supercsv/cellprocessor/package-info.java @@ -1,19 +1,19 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides CellProcessor classes for conversion, formatting and parsing. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides CellProcessor classes for conversion, formatting and parsing. + */ package org.supercsv.cellprocessor; \ No newline at end of file diff --git a/super-csv/src/main/java/org/supercsv/exception/SuperCsvCellProcessorException.java b/super-csv/src/main/java/org/supercsv/exception/SuperCsvCellProcessorException.java index 37f399c9..c1129fb9 100644 --- a/super-csv/src/main/java/org/supercsv/exception/SuperCsvCellProcessorException.java +++ b/super-csv/src/main/java/org/supercsv/exception/SuperCsvCellProcessorException.java @@ -1,124 +1,124 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.util.CsvContext; - -/** - * Exception thrown when CellProcessor execution fails (typically due to invalid input) - constraint validating - * CellProcessors should throw {@link SuperCsvConstraintViolationException} for constraint validation failures. - * - * @author James Bassett - * @since 2.0.0 - */ -public class SuperCsvCellProcessorException extends SuperCsvException { - - private static final long serialVersionUID = 1L; - - private final CellProcessor processor; - - /** - * Constructs a new SuperCsvCellProcessorException. - * - * @param msg - * the exception message - * @param context - * the CSV context - * @param processor - * the cell processor that was executing - */ - public SuperCsvCellProcessorException(final String msg, final CsvContext context, final CellProcessor processor) { - super(msg, context); - this.processor = processor; - } - - /** - * Constructs a new SuperCsvCellProcessorException. - * - * @param msg - * the exception message - * @param context - * the CSV context - * @param processor - * the cell processor that was executing - * @param t - * the nested exception - */ - public SuperCsvCellProcessorException(final String msg, final CsvContext context, final CellProcessor processor, - final Throwable t) { - super(msg, context, t); - this.processor = processor; - } - - /** - * Constructs a new SuperCsvCellProcessorException to indicate that the value received by a CellProcessor - * wasn't of the correct type. - * - * @param expectedType - * the expected type - * @param actualValue - * the value received by the CellProcessor - * @param context - * the CSV context - * @param processor - * the cell processor that was executing - */ - public SuperCsvCellProcessorException(final Class expectedType, final Object actualValue, - final CsvContext context, final CellProcessor processor) { - super(getUnexpectedTypeMessage(expectedType, actualValue), context); - this.processor = processor; - } - - /** - * Assembles the exception message when the value received by a CellProcessor isn't of the correct type. - * - * @param expectedType - * the expected type - * @param actualValue - * the value received by the CellProcessor - * @return the message - * @throws NullPointerException - * if expectedType is null - */ - private static String getUnexpectedTypeMessage(final Class expectedType, final Object actualValue) { - if( expectedType == null ) { - throw new NullPointerException("expectedType should not be null"); - } - String expectedClassName = expectedType.getName(); - String actualClassName = (actualValue != null) ? actualValue.getClass().getName() : "null"; - return String.format("the input value should be of type %s but is %s", expectedClassName, actualClassName); - } - - /** - * Gets the processor that was executing. - * - * @return the processor that was executing - */ - public CellProcessor getProcessor() { - return processor; - } - - /** - * Returns the String representation of this exception. - */ - @Override - public String toString() { - return String.format("%s: %s%nprocessor=%s%ncontext=%s", getClass().getName(), getMessage(), processor, - getCsvContext()); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.util.CsvContext; + +/** + * Exception thrown when CellProcessor execution fails (typically due to invalid input) - constraint validating + * CellProcessors should throw {@link SuperCsvConstraintViolationException} for constraint validation failures. + * + * @author James Bassett + * @since 2.0.0 + */ +public class SuperCsvCellProcessorException extends SuperCsvException { + + private static final long serialVersionUID = 1L; + + private final CellProcessor processor; + + /** + * Constructs a new SuperCsvCellProcessorException. + * + * @param msg + * the exception message + * @param context + * the CSV context + * @param processor + * the cell processor that was executing + */ + public SuperCsvCellProcessorException(final String msg, final CsvContext context, final CellProcessor processor) { + super(msg, context); + this.processor = processor; + } + + /** + * Constructs a new SuperCsvCellProcessorException. + * + * @param msg + * the exception message + * @param context + * the CSV context + * @param processor + * the cell processor that was executing + * @param t + * the nested exception + */ + public SuperCsvCellProcessorException(final String msg, final CsvContext context, final CellProcessor processor, + final Throwable t) { + super(msg, context, t); + this.processor = processor; + } + + /** + * Constructs a new SuperCsvCellProcessorException to indicate that the value received by a CellProcessor + * wasn't of the correct type. + * + * @param expectedType + * the expected type + * @param actualValue + * the value received by the CellProcessor + * @param context + * the CSV context + * @param processor + * the cell processor that was executing + */ + public SuperCsvCellProcessorException(final Class expectedType, final Object actualValue, + final CsvContext context, final CellProcessor processor) { + super(getUnexpectedTypeMessage(expectedType, actualValue), context); + this.processor = processor; + } + + /** + * Assembles the exception message when the value received by a CellProcessor isn't of the correct type. + * + * @param expectedType + * the expected type + * @param actualValue + * the value received by the CellProcessor + * @return the message + * @throws NullPointerException + * if expectedType is null + */ + private static String getUnexpectedTypeMessage(final Class expectedType, final Object actualValue) { + if( expectedType == null ) { + throw new NullPointerException("expectedType should not be null"); + } + String expectedClassName = expectedType.getName(); + String actualClassName = (actualValue != null) ? actualValue.getClass().getName() : "null"; + return String.format("the input value should be of type %s but is %s", expectedClassName, actualClassName); + } + + /** + * Gets the processor that was executing. + * + * @return the processor that was executing + */ + public CellProcessor getProcessor() { + return processor; + } + + /** + * Returns the String representation of this exception. + */ + @Override + public String toString() { + return String.format("%s: %s%nprocessor=%s%ncontext=%s", getClass().getName(), getMessage(), processor, + getCsvContext()); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/exception/SuperCsvConstraintViolationException.java b/super-csv/src/main/java/org/supercsv/exception/SuperCsvConstraintViolationException.java index 7f220056..5f375ab5 100644 --- a/super-csv/src/main/java/org/supercsv/exception/SuperCsvConstraintViolationException.java +++ b/super-csv/src/main/java/org/supercsv/exception/SuperCsvConstraintViolationException.java @@ -1,66 +1,66 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.util.CsvContext; - -/** - * Exception thrown by CellProcessors when constraint validation fails. - *

- * Prior to 2.0.0, there was no way to distinguish between constraint validation failures and other exceptions thrown - * during CellProcessor execution - this class exists for that purpose. - * - * @author James Bassett - * @since 2.0.0 - */ -public class SuperCsvConstraintViolationException extends SuperCsvCellProcessorException { - - private static final long serialVersionUID = 1L; - - /** - * Constructs a new SuperCsvConstraintViolationException. - * - * @param msg - * the exception message - * @param context - * the CSV context - * @param processor - * the cell processor that was executing - */ - public SuperCsvConstraintViolationException(final String msg, final CsvContext context, - final CellProcessor processor) { - super(msg, context, processor); - } - - /** - * Constructs a new SuperCsvConstraintViolationException. - * - * @param msg - * the exception message - * @param context - * the CSV context - * @param processor - * the cell processor that was executing - * @param t - * the nested exception - */ - public SuperCsvConstraintViolationException(final String msg, final CsvContext context, - final CellProcessor processor, final Throwable t) { - super(msg, context, processor, t); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.util.CsvContext; + +/** + * Exception thrown by CellProcessors when constraint validation fails. + *

+ * Prior to 2.0.0, there was no way to distinguish between constraint validation failures and other exceptions thrown + * during CellProcessor execution - this class exists for that purpose. + * + * @author James Bassett + * @since 2.0.0 + */ +public class SuperCsvConstraintViolationException extends SuperCsvCellProcessorException { + + private static final long serialVersionUID = 1L; + + /** + * Constructs a new SuperCsvConstraintViolationException. + * + * @param msg + * the exception message + * @param context + * the CSV context + * @param processor + * the cell processor that was executing + */ + public SuperCsvConstraintViolationException(final String msg, final CsvContext context, + final CellProcessor processor) { + super(msg, context, processor); + } + + /** + * Constructs a new SuperCsvConstraintViolationException. + * + * @param msg + * the exception message + * @param context + * the CSV context + * @param processor + * the cell processor that was executing + * @param t + * the nested exception + */ + public SuperCsvConstraintViolationException(final String msg, final CsvContext context, + final CellProcessor processor, final Throwable t) { + super(msg, context, processor, t); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/exception/SuperCsvException.java b/super-csv/src/main/java/org/supercsv/exception/SuperCsvException.java index 892fa5f5..038f7c8a 100644 --- a/super-csv/src/main/java/org/supercsv/exception/SuperCsvException.java +++ b/super-csv/src/main/java/org/supercsv/exception/SuperCsvException.java @@ -1,87 +1,87 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -import org.supercsv.util.CsvContext; - -/** - * Generic SuperCSV Exception class. It contains the CSV context (line number, column number and raw line) from when the - * exception occurred. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class SuperCsvException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private CsvContext csvContext; - - /** - * Constructs a new SuperCsvException. - * - * @param msg - * the exception message - */ - public SuperCsvException(final String msg) { - super(msg); - } - - /** - * Constructs a new SuperCsvException. - * - * @param msg - * the exception message - * @param context - * the CSV context - */ - public SuperCsvException(final String msg, final CsvContext context) { - super(msg); - this.csvContext = context; - } - - /** - * Constructs a new SuperCsvException. - * - * @param msg - * the exception message - * @param context - * the CSV context - * @param t - * the nested exception - */ - public SuperCsvException(final String msg, final CsvContext context, final Throwable t) { - super(msg, t); - this.csvContext = context; - } - - /** - * Gets the current CSV context. - * - * @return the current CSV context, or null if none is available - */ - public CsvContext getCsvContext() { - return csvContext; - } - - /** - * Returns the String representation of this exception. - */ - @Override - public String toString() { - return String.format("%s: %s%ncontext=%s", getClass().getName(), getMessage(), csvContext); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +import org.supercsv.util.CsvContext; + +/** + * Generic SuperCSV Exception class. It contains the CSV context (line number, column number and raw line) from when the + * exception occurred. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class SuperCsvException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private CsvContext csvContext; + + /** + * Constructs a new SuperCsvException. + * + * @param msg + * the exception message + */ + public SuperCsvException(final String msg) { + super(msg); + } + + /** + * Constructs a new SuperCsvException. + * + * @param msg + * the exception message + * @param context + * the CSV context + */ + public SuperCsvException(final String msg, final CsvContext context) { + super(msg); + this.csvContext = context; + } + + /** + * Constructs a new SuperCsvException. + * + * @param msg + * the exception message + * @param context + * the CSV context + * @param t + * the nested exception + */ + public SuperCsvException(final String msg, final CsvContext context, final Throwable t) { + super(msg, t); + this.csvContext = context; + } + + /** + * Gets the current CSV context. + * + * @return the current CSV context, or null if none is available + */ + public CsvContext getCsvContext() { + return csvContext; + } + + /** + * Returns the String representation of this exception. + */ + @Override + public String toString() { + return String.format("%s: %s%ncontext=%s", getClass().getName(), getMessage(), csvContext); + } +} diff --git a/super-csv/src/main/java/org/supercsv/exception/SuperCsvReflectionException.java b/super-csv/src/main/java/org/supercsv/exception/SuperCsvReflectionException.java index b2aa75d4..edf5945b 100644 --- a/super-csv/src/main/java/org/supercsv/exception/SuperCsvReflectionException.java +++ b/super-csv/src/main/java/org/supercsv/exception/SuperCsvReflectionException.java @@ -1,55 +1,55 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -/** - * Wraps the following reflection related checked exceptions: - *

- * - * ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, - * NoSuchMethodException - *

- * - * @since 1.30 - * @author Kasper B. Graversen - */ -public class SuperCsvReflectionException extends SuperCsvException { - - private static final long serialVersionUID = 1L; - - /** - * Constructs a new SuperCsvReflectionException. - * - * @param msg - * the exception message - */ - public SuperCsvReflectionException(final String msg) { - super(msg); - } - - /** - * Constructs a new SuperCsvReflectionException. - * - * @param msg - * the exception message - * @param t - * the nested exception - */ - public SuperCsvReflectionException(final String msg, final Throwable t) { - super(msg, null, t); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +/** + * Wraps the following reflection related checked exceptions: + *

+ * + * ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, + * NoSuchMethodException + *

+ * + * @since 1.30 + * @author Kasper B. Graversen + */ +public class SuperCsvReflectionException extends SuperCsvException { + + private static final long serialVersionUID = 1L; + + /** + * Constructs a new SuperCsvReflectionException. + * + * @param msg + * the exception message + */ + public SuperCsvReflectionException(final String msg) { + super(msg); + } + + /** + * Constructs a new SuperCsvReflectionException. + * + * @param msg + * the exception message + * @param t + * the nested exception + */ + public SuperCsvReflectionException(final String msg, final Throwable t) { + super(msg, null, t); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/exception/package-info.java b/super-csv/src/main/java/org/supercsv/exception/package-info.java index 00dfbe18..88d745d3 100644 --- a/super-csv/src/main/java/org/supercsv/exception/package-info.java +++ b/super-csv/src/main/java/org/supercsv/exception/package-info.java @@ -1,19 +1,19 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides the exceptions that may be thrown by Super CSV. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides the exceptions that may be thrown by Super CSV. + */ package org.supercsv.exception; \ No newline at end of file diff --git a/super-csv/src/main/java/org/supercsv/io/AbstractCsvReader.java b/super-csv/src/main/java/org/supercsv/io/AbstractCsvReader.java index c5a53395..0b6af7bb 100644 --- a/super-csv/src/main/java/org/supercsv/io/AbstractCsvReader.java +++ b/super-csv/src/main/java/org/supercsv/io/AbstractCsvReader.java @@ -1,183 +1,183 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Reader; -import java.util.ArrayList; -import java.util.List; - -import org.supercsv.exception.SuperCsvException; -import org.supercsv.prefs.CsvPreference; - -/** - * Defines the standard behaviour of a CSV reader. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public abstract class AbstractCsvReader implements ICsvReader { - - private final ITokenizer tokenizer; - - private final CsvPreference preferences; - - // the current tokenized columns - private final List columns = new ArrayList(); - - // the number of CSV records read - private int rowNumber = 0; - - /** - * Constructs a new AbstractCsvReader, using the default {@link Tokenizer}. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if reader or preferences are null - */ - public AbstractCsvReader(final Reader reader, final CsvPreference preferences) { - if( reader == null ) { - throw new NullPointerException("reader should not be null"); - } else if( preferences == null ) { - throw new NullPointerException("preferences should not be null"); - } - - this.preferences = preferences; - this.tokenizer = new Tokenizer(reader, preferences); - } - - /** - * Constructs a new AbstractCsvReader, using a custom {@link Tokenizer} (which should have already been set - * up with the Reader, CsvPreference, and CsvContext). This constructor should only be used if the default Tokenizer - * doesn't provide the required functionality. - * - * @param tokenizer - * the tokenizer - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if tokenizer or preferences are null - */ - public AbstractCsvReader(final ITokenizer tokenizer, final CsvPreference preferences) { - if( tokenizer == null ) { - throw new NullPointerException("tokenizer should not be null"); - } else if( preferences == null ) { - throw new NullPointerException("preferences should not be null"); - } - - this.preferences = preferences; - this.tokenizer = tokenizer; - } - - /** - * Closes the Tokenizer and its associated Reader. - */ - public void close() throws IOException { - tokenizer.close(); - } - - /** - * {@inheritDoc} - */ - public String get(final int n) { - return columns.get(n - 1); // column numbers start at 1 - } - - /** - * {@inheritDoc} - */ - public String[] getHeader(final boolean firstLineCheck) throws IOException { - - if( firstLineCheck && tokenizer.getLineNumber() != 0 ) { - throw new SuperCsvException(String.format( - "CSV header must be fetched as the first read operation, but %d lines have already been read", - tokenizer.getLineNumber())); - } - - if( readRow() ) { - return columns.toArray(new String[columns.size()]); - } - - return null; - } - - /** - * {@inheritDoc} - */ - public int getLineNumber() { - return tokenizer.getLineNumber(); - } - - /** - * {@inheritDoc} - */ - public String getUntokenizedRow() { - return tokenizer.getUntokenizedRow(); - } - - /** - * {@inheritDoc} - */ - public int getRowNumber() { - return rowNumber; - } - - /** - * {@inheritDoc} - */ - public int length() { - return columns.size(); - } - - /** - * Gets the tokenized columns. - * - * @return the tokenized columns - */ - protected List getColumns() { - return columns; - } - - /** - * Gets the preferences. - * - * @return the preferences - */ - protected CsvPreference getPreferences() { - return preferences; - } - - /** - * Calls the tokenizer to read a CSV row. The columns can then be retrieved using {@link #getColumns()}. - * - * @return true if something was read, and false if EOF - * @throws IOException - * when an IOException occurs - * @throws SuperCsvException - * on errors in parsing the input - */ - protected boolean readRow() throws IOException { - if( tokenizer.readColumns(columns) ) { - rowNumber++; - return true; - } - return false; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; + +import org.supercsv.exception.SuperCsvException; +import org.supercsv.prefs.CsvPreference; + +/** + * Defines the standard behaviour of a CSV reader. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public abstract class AbstractCsvReader implements ICsvReader { + + private final ITokenizer tokenizer; + + private final CsvPreference preferences; + + // the current tokenized columns + private final List columns = new ArrayList(); + + // the number of CSV records read + private int rowNumber = 0; + + /** + * Constructs a new AbstractCsvReader, using the default {@link Tokenizer}. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if reader or preferences are null + */ + public AbstractCsvReader(final Reader reader, final CsvPreference preferences) { + if( reader == null ) { + throw new NullPointerException("reader should not be null"); + } else if( preferences == null ) { + throw new NullPointerException("preferences should not be null"); + } + + this.preferences = preferences; + this.tokenizer = new Tokenizer(reader, preferences); + } + + /** + * Constructs a new AbstractCsvReader, using a custom {@link Tokenizer} (which should have already been set + * up with the Reader, CsvPreference, and CsvContext). This constructor should only be used if the default Tokenizer + * doesn't provide the required functionality. + * + * @param tokenizer + * the tokenizer + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if tokenizer or preferences are null + */ + public AbstractCsvReader(final ITokenizer tokenizer, final CsvPreference preferences) { + if( tokenizer == null ) { + throw new NullPointerException("tokenizer should not be null"); + } else if( preferences == null ) { + throw new NullPointerException("preferences should not be null"); + } + + this.preferences = preferences; + this.tokenizer = tokenizer; + } + + /** + * Closes the Tokenizer and its associated Reader. + */ + public void close() throws IOException { + tokenizer.close(); + } + + /** + * {@inheritDoc} + */ + public String get(final int n) { + return columns.get(n - 1); // column numbers start at 1 + } + + /** + * {@inheritDoc} + */ + public String[] getHeader(final boolean firstLineCheck) throws IOException { + + if( firstLineCheck && tokenizer.getLineNumber() != 0 ) { + throw new SuperCsvException(String.format( + "CSV header must be fetched as the first read operation, but %d lines have already been read", + tokenizer.getLineNumber())); + } + + if( readRow() ) { + return columns.toArray(new String[columns.size()]); + } + + return null; + } + + /** + * {@inheritDoc} + */ + public int getLineNumber() { + return tokenizer.getLineNumber(); + } + + /** + * {@inheritDoc} + */ + public String getUntokenizedRow() { + return tokenizer.getUntokenizedRow(); + } + + /** + * {@inheritDoc} + */ + public int getRowNumber() { + return rowNumber; + } + + /** + * {@inheritDoc} + */ + public int length() { + return columns.size(); + } + + /** + * Gets the tokenized columns. + * + * @return the tokenized columns + */ + protected List getColumns() { + return columns; + } + + /** + * Gets the preferences. + * + * @return the preferences + */ + protected CsvPreference getPreferences() { + return preferences; + } + + /** + * Calls the tokenizer to read a CSV row. The columns can then be retrieved using {@link #getColumns()}. + * + * @return true if something was read, and false if EOF + * @throws IOException + * when an IOException occurs + * @throws SuperCsvException + * on errors in parsing the input + */ + protected boolean readRow() throws IOException { + if( tokenizer.readColumns(columns) ) { + rowNumber++; + return true; + } + return false; + } + +} diff --git a/super-csv/src/main/java/org/supercsv/io/AbstractCsvWriter.java b/super-csv/src/main/java/org/supercsv/io/AbstractCsvWriter.java index 6ce0e69b..6754a4d7 100644 --- a/super-csv/src/main/java/org/supercsv/io/AbstractCsvWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/AbstractCsvWriter.java @@ -1,242 +1,242 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.Writer; -import java.util.List; - -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * Defines the standard behaviour of a CSV writer. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public abstract class AbstractCsvWriter implements ICsvWriter { - - private final BufferedWriter writer; - - private final CsvPreference preference; - - // the line number being written / just written - private int lineNumber = 0; - - // the row being written / just written - private int rowNumber = 0; - - private final StringBuilder currentColumn = new StringBuilder(); - - /** - * Constructs a new AbstractCsvWriter with the supplied writer and preferences. - * - * @param writer - * the stream to write to - * @param preference - * the CSV preferences - * @throws NullPointerException - * if writer or preference are null - */ - public AbstractCsvWriter(final Writer writer, final CsvPreference preference) { - if( writer == null ) { - throw new NullPointerException("writer should not be null"); - } else if( preference == null ) { - throw new NullPointerException("preference should not be null"); - } - - this.writer = new BufferedWriter(writer); - this.preference = preference; - } - - /** - * Closes the underlying writer, flushing it first. - */ - public void close() throws IOException { - writer.close(); - } - - /** - * Flushes the underlying writer. - */ - public void flush() throws IOException { - writer.flush(); - } - - /** - * Make a string ready for writing by escaping various characters as specified by the CSV format. This method also - * updates the current lineNumber as newlines are encountered in the String to be escaped. - * - * @param csvElement - * an element of a CSV file - * @return an escaped version of the element ready for persisting - */ - protected String escapeString(final String csvElement) { - if( csvElement.length() == 0 ) { - return ""; - } - - currentColumn.delete(0, currentColumn.length()); // reusing builder object - - final int delimiter = preference.getDelimiterChar(); - final char quote = (char) preference.getQuoteChar(); - final char space = ' '; - final String eolSymbols = preference.getEndOfLineSymbols(); - final boolean surroundingSpacesNeedQuotes = preference.isSurroundingSpacesNeedQuotes(); - final int lastCharIndex = csvElement.length() - 1; - - // elements with leading/trailing spaces require surrounding quotes if surroundingSpacesNeedQuotes is enabled - boolean needForEscape = surroundingSpacesNeedQuotes - && (csvElement.charAt(0) == space || csvElement.charAt(lastCharIndex) == space); - - for( int i = 0; i <= lastCharIndex; i++ ) { - - final char c = csvElement.charAt(i); - - if( c == delimiter ) { - needForEscape = true; - currentColumn.append(c); - } else if( c == quote ) { - needForEscape = true; - currentColumn.append(quote); - currentColumn.append(quote); - } else if( c == '\n' ) { - needForEscape = true; - currentColumn.append(eolSymbols); - lineNumber++; - } else { - currentColumn.append(c); - } - } - - // if element contains special characters, escape the - // whole element with surrounding quotes - if( needForEscape ) { - currentColumn.insert(0, quote).append(quote); - } - - return currentColumn.toString(); - - } - - /** - * In order to maintain the current row and line numbers, this method must be called at the very - * beginning of every write method implemented in concrete CSV writers. This will allow the correct row/line numbers - * to be used in any exceptions thrown before writing occurs (e.g. during CellProcessor execution), and means that - * {@link #getLineNumber()} and {@link #getRowNumber()} can be called after writing to return the line/row just - * written. - */ - protected void incrementRowAndLineNo() { - lineNumber++; - rowNumber++; - } - - /** - * {@inheritDoc} - */ - public int getLineNumber() { - return lineNumber; - } - - /** - * {@inheritDoc} - */ - public int getRowNumber() { - return rowNumber; - } - - /** - * Writes a List of columns as a line to the CsvWriter. - * - * @param columns - * the columns to write - * @throws IllegalArgumentException - * if columns.size == 0 - * @throws IOException - * If an I/O error occurs - * @throws NullPointerException - * if columns is null - */ - protected void writeRow(final List columns) throws IOException { - writeRow(Util.objectListToStringArray(columns)); - } - - /** - * Writes one or more Object columns as a line to the CsvWriter. - * - * @param columns - * the columns to write - * @throws IllegalArgumentException - * if columns.length == 0 - * @throws IOException - * If an I/O error occurs - * @throws NullPointerException - * if columns is null - */ - protected void writeRow(final Object... columns) throws IOException { - writeRow(Util.objectArrayToStringArray(columns)); - } - - /** - * Writes one or more String columns as a line to the CsvWriter. - * - * @param columns - * the columns to write - * @throws IllegalArgumentException - * if columns.length == 0 - * @throws IOException - * If an I/O error occurs - * @throws NullPointerException - * if columns is null - */ - protected void writeRow(final String... columns) throws IOException { - - if( columns == null ) { - throw new NullPointerException(String.format("columns to write should not be null on line %d", lineNumber)); - } else if( columns.length == 0 ) { - throw new IllegalArgumentException(String.format("columns to write should not be empty on line %d", - lineNumber)); - } - - for( int i = 0; i < columns.length; i++ ) { - - if( i > 0 ) { - writer.write(preference.getDelimiterChar()); // delimiter - } - - if( columns[i] != null ) { - writer.write(escapeString(columns[i])); // escaped column (a null column implies "") - } - - } - - writer.write(preference.getEndOfLineSymbols()); // EOL - } - - /** - * {@inheritDoc} - */ - public void writeHeader(final String... header) throws IOException { - - // update the current row/line numbers - incrementRowAndLineNo(); - - writeRow(header); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.Writer; +import java.util.List; + +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * Defines the standard behaviour of a CSV writer. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public abstract class AbstractCsvWriter implements ICsvWriter { + + private final BufferedWriter writer; + + private final CsvPreference preference; + + // the line number being written / just written + private int lineNumber = 0; + + // the row being written / just written + private int rowNumber = 0; + + private final StringBuilder currentColumn = new StringBuilder(); + + /** + * Constructs a new AbstractCsvWriter with the supplied writer and preferences. + * + * @param writer + * the stream to write to + * @param preference + * the CSV preferences + * @throws NullPointerException + * if writer or preference are null + */ + public AbstractCsvWriter(final Writer writer, final CsvPreference preference) { + if( writer == null ) { + throw new NullPointerException("writer should not be null"); + } else if( preference == null ) { + throw new NullPointerException("preference should not be null"); + } + + this.writer = new BufferedWriter(writer); + this.preference = preference; + } + + /** + * Closes the underlying writer, flushing it first. + */ + public void close() throws IOException { + writer.close(); + } + + /** + * Flushes the underlying writer. + */ + public void flush() throws IOException { + writer.flush(); + } + + /** + * Make a string ready for writing by escaping various characters as specified by the CSV format. This method also + * updates the current lineNumber as newlines are encountered in the String to be escaped. + * + * @param csvElement + * an element of a CSV file + * @return an escaped version of the element ready for persisting + */ + protected String escapeString(final String csvElement) { + if( csvElement.length() == 0 ) { + return ""; + } + + currentColumn.delete(0, currentColumn.length()); // reusing builder object + + final int delimiter = preference.getDelimiterChar(); + final char quote = (char) preference.getQuoteChar(); + final char space = ' '; + final String eolSymbols = preference.getEndOfLineSymbols(); + final boolean surroundingSpacesNeedQuotes = preference.isSurroundingSpacesNeedQuotes(); + final int lastCharIndex = csvElement.length() - 1; + + // elements with leading/trailing spaces require surrounding quotes if surroundingSpacesNeedQuotes is enabled + boolean needForEscape = surroundingSpacesNeedQuotes + && (csvElement.charAt(0) == space || csvElement.charAt(lastCharIndex) == space); + + for( int i = 0; i <= lastCharIndex; i++ ) { + + final char c = csvElement.charAt(i); + + if( c == delimiter ) { + needForEscape = true; + currentColumn.append(c); + } else if( c == quote ) { + needForEscape = true; + currentColumn.append(quote); + currentColumn.append(quote); + } else if( c == '\n' ) { + needForEscape = true; + currentColumn.append(eolSymbols); + lineNumber++; + } else { + currentColumn.append(c); + } + } + + // if element contains special characters, escape the + // whole element with surrounding quotes + if( needForEscape ) { + currentColumn.insert(0, quote).append(quote); + } + + return currentColumn.toString(); + + } + + /** + * In order to maintain the current row and line numbers, this method must be called at the very + * beginning of every write method implemented in concrete CSV writers. This will allow the correct row/line numbers + * to be used in any exceptions thrown before writing occurs (e.g. during CellProcessor execution), and means that + * {@link #getLineNumber()} and {@link #getRowNumber()} can be called after writing to return the line/row just + * written. + */ + protected void incrementRowAndLineNo() { + lineNumber++; + rowNumber++; + } + + /** + * {@inheritDoc} + */ + public int getLineNumber() { + return lineNumber; + } + + /** + * {@inheritDoc} + */ + public int getRowNumber() { + return rowNumber; + } + + /** + * Writes a List of columns as a line to the CsvWriter. + * + * @param columns + * the columns to write + * @throws IllegalArgumentException + * if columns.size == 0 + * @throws IOException + * If an I/O error occurs + * @throws NullPointerException + * if columns is null + */ + protected void writeRow(final List columns) throws IOException { + writeRow(Util.objectListToStringArray(columns)); + } + + /** + * Writes one or more Object columns as a line to the CsvWriter. + * + * @param columns + * the columns to write + * @throws IllegalArgumentException + * if columns.length == 0 + * @throws IOException + * If an I/O error occurs + * @throws NullPointerException + * if columns is null + */ + protected void writeRow(final Object... columns) throws IOException { + writeRow(Util.objectArrayToStringArray(columns)); + } + + /** + * Writes one or more String columns as a line to the CsvWriter. + * + * @param columns + * the columns to write + * @throws IllegalArgumentException + * if columns.length == 0 + * @throws IOException + * If an I/O error occurs + * @throws NullPointerException + * if columns is null + */ + protected void writeRow(final String... columns) throws IOException { + + if( columns == null ) { + throw new NullPointerException(String.format("columns to write should not be null on line %d", lineNumber)); + } else if( columns.length == 0 ) { + throw new IllegalArgumentException(String.format("columns to write should not be empty on line %d", + lineNumber)); + } + + for( int i = 0; i < columns.length; i++ ) { + + if( i > 0 ) { + writer.write(preference.getDelimiterChar()); // delimiter + } + + if( columns[i] != null ) { + writer.write(escapeString(columns[i])); // escaped column (a null column implies "") + } + + } + + writer.write(preference.getEndOfLineSymbols()); // EOL + } + + /** + * {@inheritDoc} + */ + public void writeHeader(final String... header) throws IOException { + + // update the current row/line numbers + incrementRowAndLineNo(); + + writeRow(header); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/io/AbstractTokenizer.java b/super-csv/src/main/java/org/supercsv/io/AbstractTokenizer.java index 5c301098..dcf32331 100644 --- a/super-csv/src/main/java/org/supercsv/io/AbstractTokenizer.java +++ b/super-csv/src/main/java/org/supercsv/io/AbstractTokenizer.java @@ -1,94 +1,94 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.Reader; -import java.util.List; - -import org.supercsv.prefs.CsvPreference; - -/** - * Defines the standard behaviour of a Tokenizer. Extend this class if you want the line-reading functionality of the - * default {@link Tokenizer}, but want to define your own implementation of {@link #readColumns(List)}. - * - * @author James Bassett - * @since 2.0.0 - */ -public abstract class AbstractTokenizer implements ITokenizer { - - private final CsvPreference preferences; - - private final LineNumberReader lnr; - - /** - * Constructs a new AbstractTokenizer, which reads the CSV file, line by line. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if reader or preferences is null - */ - public AbstractTokenizer(final Reader reader, final CsvPreference preferences) { - if( reader == null ) { - throw new NullPointerException("reader should not be null"); - } - if( preferences == null ) { - throw new NullPointerException("preferences should not be null"); - } - this.preferences = preferences; - lnr = new LineNumberReader(reader); - } - - /** - * Closes the underlying reader. - */ - public void close() throws IOException { - lnr.close(); - } - - /** - * {@inheritDoc} - */ - public int getLineNumber() { - return lnr.getLineNumber(); - } - - /** - * Reads a line of text. Whenever a line terminator is read the current line number is incremented. - * - * @return A String containing the contents of the line, not including any line termination characters, or - * null if the end of the stream has been reached - * @throws IOException - * If an I/O error occurs - */ - protected String readLine() throws IOException { - return lnr.readLine(); - } - - /** - * Gets the CSV preferences. - * - * @return the preferences - */ - protected CsvPreference getPreferences() { - return preferences; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.Reader; +import java.util.List; + +import org.supercsv.prefs.CsvPreference; + +/** + * Defines the standard behaviour of a Tokenizer. Extend this class if you want the line-reading functionality of the + * default {@link Tokenizer}, but want to define your own implementation of {@link #readColumns(List)}. + * + * @author James Bassett + * @since 2.0.0 + */ +public abstract class AbstractTokenizer implements ITokenizer { + + private final CsvPreference preferences; + + private final LineNumberReader lnr; + + /** + * Constructs a new AbstractTokenizer, which reads the CSV file, line by line. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if reader or preferences is null + */ + public AbstractTokenizer(final Reader reader, final CsvPreference preferences) { + if( reader == null ) { + throw new NullPointerException("reader should not be null"); + } + if( preferences == null ) { + throw new NullPointerException("preferences should not be null"); + } + this.preferences = preferences; + lnr = new LineNumberReader(reader); + } + + /** + * Closes the underlying reader. + */ + public void close() throws IOException { + lnr.close(); + } + + /** + * {@inheritDoc} + */ + public int getLineNumber() { + return lnr.getLineNumber(); + } + + /** + * Reads a line of text. Whenever a line terminator is read the current line number is incremented. + * + * @return A String containing the contents of the line, not including any line termination characters, or + * null if the end of the stream has been reached + * @throws IOException + * If an I/O error occurs + */ + protected String readLine() throws IOException { + return lnr.readLine(); + } + + /** + * Gets the CSV preferences. + * + * @return the preferences + */ + protected CsvPreference getPreferences() { + return preferences; + } + +} diff --git a/super-csv/src/main/java/org/supercsv/io/CsvBeanReader.java b/super-csv/src/main/java/org/supercsv/io/CsvBeanReader.java index 3e653214..1842d179 100644 --- a/super-csv/src/main/java/org/supercsv/io/CsvBeanReader.java +++ b/super-csv/src/main/java/org/supercsv/io/CsvBeanReader.java @@ -1,214 +1,214 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Reader; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.exception.SuperCsvReflectionException; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.BeanInterfaceProxy; -import org.supercsv.util.MethodCache; -import org.supercsv.util.Util; - -/** - * CsvBeanReader reads a CSV file by instantiating a bean for every row and mapping each column to a field on the bean - * (using the supplied name mapping). The bean to populate can be either a class or interface. If a class is used, it - * must be a valid Javabean, i.e. it must have a default no-argument constructor and getter/setter methods. An interface - * may also be used if it defines getters/setters - a proxy object will be created that implements the interface. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class CsvBeanReader extends AbstractCsvReader implements ICsvBeanReader { - - // temporary storage of processed columns to be mapped to the bean - private final List processedColumns = new ArrayList(); - - // cache of methods for mapping from columns to fields - private final MethodCache cache = new MethodCache(); - - /** - * Constructs a new CsvBeanReader with the supplied Reader and CSV preferences. Note that the - * reader will be wrapped in a BufferedReader before accessed. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if reader or preferences are null - */ - public CsvBeanReader(final Reader reader, final CsvPreference preferences) { - super(reader, preferences); - } - - /** - * Constructs a new CsvBeanReader with the supplied (custom) Tokenizer and CSV preferences. The tokenizer - * should be set up with the Reader (CSV input) and CsvPreference beforehand. - * - * @param tokenizer - * the tokenizer - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if tokenizer or preferences are null - */ - public CsvBeanReader(final ITokenizer tokenizer, final CsvPreference preferences) { - super(tokenizer, preferences); - } - - /** - * Instantiates the bean (or creates a proxy if it's an interface). - * - * @param clazz - * the bean class to instantiate (a proxy will be created if an interface is supplied), using the default - * (no argument) constructor - * @return the instantiated bean - * @throws SuperCsvReflectionException - * if there was a reflection exception when instantiating the bean - */ - private static T instantiateBean(final Class clazz) { - final T bean; - if( clazz.isInterface() ) { - bean = BeanInterfaceProxy.createProxy(clazz); - } else { - try { - bean = clazz.newInstance(); - } - catch(InstantiationException e) { - throw new SuperCsvReflectionException(String.format( - "error instantiating bean, check that %s has a default no-args constructor", clazz.getName()), e); - } - catch(IllegalAccessException e) { - throw new SuperCsvReflectionException("error instantiating bean", e); - } - } - - return bean; - } - - /** - * Invokes the setter on the bean with the supplied value. - * - * @param bean - * the bean - * @param setMethod - * the setter method for the field - * @param fieldValue - * the field value to set - * @throws SuperCsvException - * if there was an exception invoking the setter - */ - private static void invokeSetter(final Object bean, final Method setMethod, final Object fieldValue) { - try { - setMethod.invoke(bean, fieldValue); - } - catch(final Exception e) { - throw new SuperCsvReflectionException(String.format("error invoking method %s()", setMethod.getName()), e); - } - } - - /** - * Instantiates the bean (or creates a proxy if it's an interface), and maps the processed columns to the fields of - * the bean. - * - * @param clazz - * the bean class to instantiate (a proxy will be created if an interface is supplied), using the default - * (no argument) constructor - * @param nameMapping - * the name mappings - * @return the populated bean - * @throws SuperCsvReflectionException - * if there was a reflection exception while populating the bean - */ - private T populateBean(final Class clazz, final String[] nameMapping) { - - // instantiate the bean or proxy - final T resultBean = instantiateBean(clazz); - - // map each column to its associated field on the bean - for( int i = 0; i < nameMapping.length; i++ ) { - - final Object fieldValue = processedColumns.get(i); - - // don't call a set-method in the bean if there is no name mapping for the column or no result to store - if( nameMapping[i] == null || fieldValue == null ) { - continue; - } - - // invoke the setter on the bean - Method setMethod = cache.getSetMethod(resultBean, nameMapping[i], fieldValue.getClass()); - invokeSetter(resultBean, setMethod, fieldValue); - - } - - return resultBean; - } - - /** - * {@inheritDoc} - */ - public T read(final Class clazz, final String... nameMapping) throws IOException { - - if( clazz == null ) { - throw new NullPointerException("clazz should not be null"); - } else if( nameMapping == null ) { - throw new NullPointerException("nameMapping should not be null"); - } - - if( readRow() ) { - if( nameMapping.length != length() ) { - throw new IllegalArgumentException(String.format("the nameMapping array and the number of columns read " - + "should be the same size (nameMapping length = %d, columns = %d)", nameMapping.length, length())); - } - processedColumns.clear(); - processedColumns.addAll(getColumns()); - return populateBean(clazz, nameMapping); - } - - return null; // EOF - } - - /** - * {@inheritDoc} - */ - public T read(final Class clazz, final String[] nameMapping, final CellProcessor... processors) - throws IOException { - - if( clazz == null ) { - throw new NullPointerException("clazz should not be null"); - } else if( nameMapping == null ) { - throw new NullPointerException("nameMapping should not be null"); - } else if( processors == null ) { - throw new NullPointerException("processors should not be null"); - } - - if( readRow() ) { - // execute the processors then populate the bean - Util.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber()); - return populateBean(clazz, nameMapping); - } - - return null; // EOF - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Reader; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.exception.SuperCsvReflectionException; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.BeanInterfaceProxy; +import org.supercsv.util.MethodCache; +import org.supercsv.util.Util; + +/** + * CsvBeanReader reads a CSV file by instantiating a bean for every row and mapping each column to a field on the bean + * (using the supplied name mapping). The bean to populate can be either a class or interface. If a class is used, it + * must be a valid Javabean, i.e. it must have a default no-argument constructor and getter/setter methods. An interface + * may also be used if it defines getters/setters - a proxy object will be created that implements the interface. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class CsvBeanReader extends AbstractCsvReader implements ICsvBeanReader { + + // temporary storage of processed columns to be mapped to the bean + private final List processedColumns = new ArrayList(); + + // cache of methods for mapping from columns to fields + private final MethodCache cache = new MethodCache(); + + /** + * Constructs a new CsvBeanReader with the supplied Reader and CSV preferences. Note that the + * reader will be wrapped in a BufferedReader before accessed. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if reader or preferences are null + */ + public CsvBeanReader(final Reader reader, final CsvPreference preferences) { + super(reader, preferences); + } + + /** + * Constructs a new CsvBeanReader with the supplied (custom) Tokenizer and CSV preferences. The tokenizer + * should be set up with the Reader (CSV input) and CsvPreference beforehand. + * + * @param tokenizer + * the tokenizer + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if tokenizer or preferences are null + */ + public CsvBeanReader(final ITokenizer tokenizer, final CsvPreference preferences) { + super(tokenizer, preferences); + } + + /** + * Instantiates the bean (or creates a proxy if it's an interface). + * + * @param clazz + * the bean class to instantiate (a proxy will be created if an interface is supplied), using the default + * (no argument) constructor + * @return the instantiated bean + * @throws SuperCsvReflectionException + * if there was a reflection exception when instantiating the bean + */ + private static T instantiateBean(final Class clazz) { + final T bean; + if( clazz.isInterface() ) { + bean = BeanInterfaceProxy.createProxy(clazz); + } else { + try { + bean = clazz.newInstance(); + } + catch(InstantiationException e) { + throw new SuperCsvReflectionException(String.format( + "error instantiating bean, check that %s has a default no-args constructor", clazz.getName()), e); + } + catch(IllegalAccessException e) { + throw new SuperCsvReflectionException("error instantiating bean", e); + } + } + + return bean; + } + + /** + * Invokes the setter on the bean with the supplied value. + * + * @param bean + * the bean + * @param setMethod + * the setter method for the field + * @param fieldValue + * the field value to set + * @throws SuperCsvException + * if there was an exception invoking the setter + */ + private static void invokeSetter(final Object bean, final Method setMethod, final Object fieldValue) { + try { + setMethod.invoke(bean, fieldValue); + } + catch(final Exception e) { + throw new SuperCsvReflectionException(String.format("error invoking method %s()", setMethod.getName()), e); + } + } + + /** + * Instantiates the bean (or creates a proxy if it's an interface), and maps the processed columns to the fields of + * the bean. + * + * @param clazz + * the bean class to instantiate (a proxy will be created if an interface is supplied), using the default + * (no argument) constructor + * @param nameMapping + * the name mappings + * @return the populated bean + * @throws SuperCsvReflectionException + * if there was a reflection exception while populating the bean + */ + private T populateBean(final Class clazz, final String[] nameMapping) { + + // instantiate the bean or proxy + final T resultBean = instantiateBean(clazz); + + // map each column to its associated field on the bean + for( int i = 0; i < nameMapping.length; i++ ) { + + final Object fieldValue = processedColumns.get(i); + + // don't call a set-method in the bean if there is no name mapping for the column or no result to store + if( nameMapping[i] == null || fieldValue == null ) { + continue; + } + + // invoke the setter on the bean + Method setMethod = cache.getSetMethod(resultBean, nameMapping[i], fieldValue.getClass()); + invokeSetter(resultBean, setMethod, fieldValue); + + } + + return resultBean; + } + + /** + * {@inheritDoc} + */ + public T read(final Class clazz, final String... nameMapping) throws IOException { + + if( clazz == null ) { + throw new NullPointerException("clazz should not be null"); + } else if( nameMapping == null ) { + throw new NullPointerException("nameMapping should not be null"); + } + + if( readRow() ) { + if( nameMapping.length != length() ) { + throw new IllegalArgumentException(String.format("the nameMapping array and the number of columns read " + + "should be the same size (nameMapping length = %d, columns = %d)", nameMapping.length, length())); + } + processedColumns.clear(); + processedColumns.addAll(getColumns()); + return populateBean(clazz, nameMapping); + } + + return null; // EOF + } + + /** + * {@inheritDoc} + */ + public T read(final Class clazz, final String[] nameMapping, final CellProcessor... processors) + throws IOException { + + if( clazz == null ) { + throw new NullPointerException("clazz should not be null"); + } else if( nameMapping == null ) { + throw new NullPointerException("nameMapping should not be null"); + } else if( processors == null ) { + throw new NullPointerException("processors should not be null"); + } + + if( readRow() ) { + // execute the processors then populate the bean + Util.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber()); + return populateBean(clazz, nameMapping); + } + + return null; // EOF + } + +} diff --git a/super-csv/src/main/java/org/supercsv/io/CsvBeanWriter.java b/super-csv/src/main/java/org/supercsv/io/CsvBeanWriter.java index 534bdb2c..146d9479 100644 --- a/super-csv/src/main/java/org/supercsv/io/CsvBeanWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/CsvBeanWriter.java @@ -1,141 +1,141 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Writer; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvReflectionException; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.MethodCache; -import org.supercsv.util.Util; - -/** - * CsvBeanWriter writes a CSV file by mapping each field on the bean to a column in the CSV file (using the supplied - * name mapping). - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class CsvBeanWriter extends AbstractCsvWriter implements ICsvBeanWriter { - - // temporary storage of bean values - private final List beanValues = new ArrayList(); - - // temporary storage of processed columns to be written - private final List processedColumns = new ArrayList(); - - // cache of methods for mapping from fields to columns - private final MethodCache cache = new MethodCache(); - - /** - * Constructs a new CsvBeanWriter with the supplied Writer and CSV preferences. Note that the - * writer will be wrapped in a BufferedWriter before accessed. - * - * @param writer - * the writer - * @param preference - * the CSV preferences - * @throws NullPointerException - * if writer or preference are null - */ - public CsvBeanWriter(final Writer writer, final CsvPreference preference) { - super(writer, preference); - } - - /** - * Extracts the bean values, using the supplied name mapping array. - * - * @param source - * the bean - * @param nameMapping - * the name mapping - * @throws NullPointerException - * if source or nameMapping are null - * @throws SuperCsvReflectionException - * if there was a reflection exception extracting the bean value - */ - private void extractBeanValues(final Object source, final String[] nameMapping) throws SuperCsvReflectionException { - - if( source == null ) { - throw new NullPointerException("the bean to write should not be null"); - } else if( nameMapping == null ) { - throw new NullPointerException( - "the nameMapping array can't be null as it's used to map from fields to columns"); - } - - beanValues.clear(); - - for( int i = 0; i < nameMapping.length; i++ ) { - - final String fieldName = nameMapping[i]; - - if( fieldName == null ) { - beanValues.add(null); // assume they always want a blank column - - } else { - Method getMethod = cache.getGetMethod(source, fieldName); - try { - beanValues.add(getMethod.invoke(source)); - } - catch(final Exception e) { - throw new SuperCsvReflectionException(String.format("error extracting bean value for field %s", - fieldName), e); - } - } - - } - - } - - /** - * {@inheritDoc} - */ - public void write(final Object source, final String... nameMapping) throws IOException { - - // update the current row/line numbers - super.incrementRowAndLineNo(); - - // extract the bean values - extractBeanValues(source, nameMapping); - - // write the list - super.writeRow(beanValues); - } - - /** - * {@inheritDoc} - */ - public void write(final Object source, final String[] nameMapping, final CellProcessor[] processors) - throws IOException { - - // update the current row/line numbers - super.incrementRowAndLineNo(); - - // extract the bean values - extractBeanValues(source, nameMapping); - - // execute the processors for each column - Util.executeCellProcessors(processedColumns, beanValues, processors, getLineNumber(), getRowNumber()); - - // write the list - super.writeRow(processedColumns); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Writer; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvReflectionException; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.MethodCache; +import org.supercsv.util.Util; + +/** + * CsvBeanWriter writes a CSV file by mapping each field on the bean to a column in the CSV file (using the supplied + * name mapping). + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class CsvBeanWriter extends AbstractCsvWriter implements ICsvBeanWriter { + + // temporary storage of bean values + private final List beanValues = new ArrayList(); + + // temporary storage of processed columns to be written + private final List processedColumns = new ArrayList(); + + // cache of methods for mapping from fields to columns + private final MethodCache cache = new MethodCache(); + + /** + * Constructs a new CsvBeanWriter with the supplied Writer and CSV preferences. Note that the + * writer will be wrapped in a BufferedWriter before accessed. + * + * @param writer + * the writer + * @param preference + * the CSV preferences + * @throws NullPointerException + * if writer or preference are null + */ + public CsvBeanWriter(final Writer writer, final CsvPreference preference) { + super(writer, preference); + } + + /** + * Extracts the bean values, using the supplied name mapping array. + * + * @param source + * the bean + * @param nameMapping + * the name mapping + * @throws NullPointerException + * if source or nameMapping are null + * @throws SuperCsvReflectionException + * if there was a reflection exception extracting the bean value + */ + private void extractBeanValues(final Object source, final String[] nameMapping) throws SuperCsvReflectionException { + + if( source == null ) { + throw new NullPointerException("the bean to write should not be null"); + } else if( nameMapping == null ) { + throw new NullPointerException( + "the nameMapping array can't be null as it's used to map from fields to columns"); + } + + beanValues.clear(); + + for( int i = 0; i < nameMapping.length; i++ ) { + + final String fieldName = nameMapping[i]; + + if( fieldName == null ) { + beanValues.add(null); // assume they always want a blank column + + } else { + Method getMethod = cache.getGetMethod(source, fieldName); + try { + beanValues.add(getMethod.invoke(source)); + } + catch(final Exception e) { + throw new SuperCsvReflectionException(String.format("error extracting bean value for field %s", + fieldName), e); + } + } + + } + + } + + /** + * {@inheritDoc} + */ + public void write(final Object source, final String... nameMapping) throws IOException { + + // update the current row/line numbers + super.incrementRowAndLineNo(); + + // extract the bean values + extractBeanValues(source, nameMapping); + + // write the list + super.writeRow(beanValues); + } + + /** + * {@inheritDoc} + */ + public void write(final Object source, final String[] nameMapping, final CellProcessor[] processors) + throws IOException { + + // update the current row/line numbers + super.incrementRowAndLineNo(); + + // extract the bean values + extractBeanValues(source, nameMapping); + + // execute the processors for each column + Util.executeCellProcessors(processedColumns, beanValues, processors, getLineNumber(), getRowNumber()); + + // write the list + super.writeRow(processedColumns); + } +} diff --git a/super-csv/src/main/java/org/supercsv/io/CsvListReader.java b/super-csv/src/main/java/org/supercsv/io/CsvListReader.java index 0ca7526b..1352c1e4 100644 --- a/super-csv/src/main/java/org/supercsv/io/CsvListReader.java +++ b/super-csv/src/main/java/org/supercsv/io/CsvListReader.java @@ -1,94 +1,94 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Reader; -import java.util.ArrayList; -import java.util.List; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * CsvListReader is a simple reader that reads a row from a CSV file into a List of Strings. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class CsvListReader extends AbstractCsvReader implements ICsvListReader { - - /** - * Constructs a new CsvListReader with the supplied Reader and CSV preferences. Note that the - * reader will be wrapped in a BufferedReader before accessed. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if reader or preferences are null - */ - public CsvListReader(final Reader reader, final CsvPreference preferences) { - super(reader, preferences); - } - - /** - * Constructs a new CsvListReader with the supplied (custom) Tokenizer and CSV preferences. The tokenizer - * should be set up with the Reader (CSV input) and CsvPreference beforehand. - * - * @param tokenizer - * the tokenizer - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if tokenizer or preferences are null - */ - public CsvListReader(final ITokenizer tokenizer, final CsvPreference preferences) { - super(tokenizer, preferences); - } - - /** - * {@inheritDoc} - */ - public List read() throws IOException { - - if( readRow() ) { - return new ArrayList(getColumns()); - } - - return null; // EOF - } - - /** - * {@inheritDoc} - */ - public List read(final CellProcessor... processors) throws IOException { - - if( processors == null ) { - throw new NullPointerException("processors should not be null"); - } - - if( readRow() ) { - final List processedColumns = new ArrayList(); - Util.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber()); - return processedColumns; - } - - return null; // EOF - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * CsvListReader is a simple reader that reads a row from a CSV file into a List of Strings. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class CsvListReader extends AbstractCsvReader implements ICsvListReader { + + /** + * Constructs a new CsvListReader with the supplied Reader and CSV preferences. Note that the + * reader will be wrapped in a BufferedReader before accessed. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if reader or preferences are null + */ + public CsvListReader(final Reader reader, final CsvPreference preferences) { + super(reader, preferences); + } + + /** + * Constructs a new CsvListReader with the supplied (custom) Tokenizer and CSV preferences. The tokenizer + * should be set up with the Reader (CSV input) and CsvPreference beforehand. + * + * @param tokenizer + * the tokenizer + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if tokenizer or preferences are null + */ + public CsvListReader(final ITokenizer tokenizer, final CsvPreference preferences) { + super(tokenizer, preferences); + } + + /** + * {@inheritDoc} + */ + public List read() throws IOException { + + if( readRow() ) { + return new ArrayList(getColumns()); + } + + return null; // EOF + } + + /** + * {@inheritDoc} + */ + public List read(final CellProcessor... processors) throws IOException { + + if( processors == null ) { + throw new NullPointerException("processors should not be null"); + } + + if( readRow() ) { + final List processedColumns = new ArrayList(); + Util.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber()); + return processedColumns; + } + + return null; // EOF + } +} diff --git a/super-csv/src/main/java/org/supercsv/io/CsvListWriter.java b/super-csv/src/main/java/org/supercsv/io/CsvListWriter.java index d455323a..90967d94 100644 --- a/super-csv/src/main/java/org/supercsv/io/CsvListWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/CsvListWriter.java @@ -1,89 +1,89 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * CsvListWriter is a simple writer capable of writing arrays and Lists to a CSV file. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class CsvListWriter extends AbstractCsvWriter implements ICsvListWriter { - - // temporary storage of processed columns to be written - private final List processedColumns = new ArrayList(); - - /** - * Constructs a new CsvListWriter with the supplied Writer and CSV preferences. Note that the - * reader will be wrapped in a BufferedReader before accessed. - * - * @param writer - * the writer - * @param preference - * the CSV preferences - * @throws NullPointerException - * if writer or preference are null - */ - public CsvListWriter(final Writer writer, final CsvPreference preference) { - super(writer, preference); - } - - /** - * {@inheritDoc} - */ - public void write(final List columns, final CellProcessor[] processors) throws IOException { - - super.incrementRowAndLineNo(); - - // execute the processors for each column - Util.executeCellProcessors(processedColumns, columns, processors, getLineNumber(), getRowNumber()); - - super.writeRow(processedColumns); - } - - /** - * {@inheritDoc} - */ - public void write(List columns) throws IOException { - super.incrementRowAndLineNo(); - super.writeRow(columns); - } - - /** - * {@inheritDoc} - */ - public void write(final Object... columns) throws IOException { - super.incrementRowAndLineNo(); - super.writeRow(columns); - } - - /** - * {@inheritDoc} - */ - public void write(final String... columns) throws IOException { - super.incrementRowAndLineNo(); - super.writeRow(columns); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * CsvListWriter is a simple writer capable of writing arrays and Lists to a CSV file. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class CsvListWriter extends AbstractCsvWriter implements ICsvListWriter { + + // temporary storage of processed columns to be written + private final List processedColumns = new ArrayList(); + + /** + * Constructs a new CsvListWriter with the supplied Writer and CSV preferences. Note that the + * reader will be wrapped in a BufferedReader before accessed. + * + * @param writer + * the writer + * @param preference + * the CSV preferences + * @throws NullPointerException + * if writer or preference are null + */ + public CsvListWriter(final Writer writer, final CsvPreference preference) { + super(writer, preference); + } + + /** + * {@inheritDoc} + */ + public void write(final List columns, final CellProcessor[] processors) throws IOException { + + super.incrementRowAndLineNo(); + + // execute the processors for each column + Util.executeCellProcessors(processedColumns, columns, processors, getLineNumber(), getRowNumber()); + + super.writeRow(processedColumns); + } + + /** + * {@inheritDoc} + */ + public void write(List columns) throws IOException { + super.incrementRowAndLineNo(); + super.writeRow(columns); + } + + /** + * {@inheritDoc} + */ + public void write(final Object... columns) throws IOException { + super.incrementRowAndLineNo(); + super.writeRow(columns); + } + + /** + * {@inheritDoc} + */ + public void write(final String... columns) throws IOException { + super.incrementRowAndLineNo(); + super.writeRow(columns); + } +} diff --git a/super-csv/src/main/java/org/supercsv/io/CsvMapReader.java b/super-csv/src/main/java/org/supercsv/io/CsvMapReader.java index fe7991a8..0f563b83 100644 --- a/super-csv/src/main/java/org/supercsv/io/CsvMapReader.java +++ b/super-csv/src/main/java/org/supercsv/io/CsvMapReader.java @@ -1,110 +1,110 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Reader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * CsvMapReader reads each CSV row into a Map with the column name as the map key, and the column value as the map - * value. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class CsvMapReader extends AbstractCsvReader implements ICsvMapReader { - - /** - * Constructs a new CsvMapReader with the supplied Reader and CSV preferences. Note that the - * reader will be wrapped in a BufferedReader before accessed. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if reader or preferences are null - */ - public CsvMapReader(final Reader reader, final CsvPreference preferences) { - super(reader, preferences); - } - - /** - * Constructs a new CsvMapReader with the supplied (custom) Tokenizer and CSV preferences. The tokenizer - * should be set up with the Reader (CSV input) and CsvPreference beforehand. - * - * @param tokenizer - * the tokenizer - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if tokenizer or preferences are null - */ - public CsvMapReader(final ITokenizer tokenizer, final CsvPreference preferences) { - super(tokenizer, preferences); - } - - /** - * {@inheritDoc} - */ - public Map read(final String... nameMapping) throws IOException { - - if( nameMapping == null ) { - throw new NullPointerException("nameMapping should not be null"); - } - - if( readRow() ) { - final Map destination = new HashMap(); - Util.filterListToMap(destination, nameMapping, getColumns()); - return destination; - } - - return null; // EOF - } - - /** - * {@inheritDoc} - */ - public Map read(final String[] nameMapping, final CellProcessor[] processors) throws IOException { - - if( nameMapping == null ) { - throw new NullPointerException("nameMapping should not be null"); - } else if( processors == null ) { - throw new NullPointerException("processors should not be null"); - } - - if( readRow() ) { - // process the columns - final List processedColumns = new ArrayList(getColumns().size()); - Util.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber()); - - // convert the List to a Map - final Map destination = new HashMap(processedColumns.size()); - Util.filterListToMap((Map) destination, nameMapping, (List) processedColumns); - return destination; - } - - return null; // EOF - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * CsvMapReader reads each CSV row into a Map with the column name as the map key, and the column value as the map + * value. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class CsvMapReader extends AbstractCsvReader implements ICsvMapReader { + + /** + * Constructs a new CsvMapReader with the supplied Reader and CSV preferences. Note that the + * reader will be wrapped in a BufferedReader before accessed. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if reader or preferences are null + */ + public CsvMapReader(final Reader reader, final CsvPreference preferences) { + super(reader, preferences); + } + + /** + * Constructs a new CsvMapReader with the supplied (custom) Tokenizer and CSV preferences. The tokenizer + * should be set up with the Reader (CSV input) and CsvPreference beforehand. + * + * @param tokenizer + * the tokenizer + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if tokenizer or preferences are null + */ + public CsvMapReader(final ITokenizer tokenizer, final CsvPreference preferences) { + super(tokenizer, preferences); + } + + /** + * {@inheritDoc} + */ + public Map read(final String... nameMapping) throws IOException { + + if( nameMapping == null ) { + throw new NullPointerException("nameMapping should not be null"); + } + + if( readRow() ) { + final Map destination = new HashMap(); + Util.filterListToMap(destination, nameMapping, getColumns()); + return destination; + } + + return null; // EOF + } + + /** + * {@inheritDoc} + */ + public Map read(final String[] nameMapping, final CellProcessor[] processors) throws IOException { + + if( nameMapping == null ) { + throw new NullPointerException("nameMapping should not be null"); + } else if( processors == null ) { + throw new NullPointerException("processors should not be null"); + } + + if( readRow() ) { + // process the columns + final List processedColumns = new ArrayList(getColumns().size()); + Util.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber()); + + // convert the List to a Map + final Map destination = new HashMap(processedColumns.size()); + Util.filterListToMap((Map) destination, nameMapping, (List) processedColumns); + return destination; + } + + return null; // EOF + } +} diff --git a/super-csv/src/main/java/org/supercsv/io/CsvMapWriter.java b/super-csv/src/main/java/org/supercsv/io/CsvMapWriter.java index 7cf9b6ae..014cb7fc 100644 --- a/super-csv/src/main/java/org/supercsv/io/CsvMapWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/CsvMapWriter.java @@ -1,77 +1,77 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * CsvMapWriter writes Maps of Objects to a CSV file. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class CsvMapWriter extends AbstractCsvWriter implements ICsvMapWriter { - - // temporary storage of processed columns to be written - private final List processedColumns = new ArrayList(); - - /** - * Constructs a new CsvMapWriter with the supplied Writer and CSV preferences. Note that the - * writer will be wrapped in a BufferedWriter before accessed. - * - * @param writer - * the writer - * @param preference - * the CSV preferences - * @throws NullPointerException - * if writer or preference are null - * @since 1.0 - */ - public CsvMapWriter(final Writer writer, final CsvPreference preference) { - super(writer, preference); - } - - /** - * {@inheritDoc} - */ - public void write(final Map values, final String... nameMapping) throws IOException { - super.incrementRowAndLineNo(); - super.writeRow(Util.filterMapToObjectArray(values, nameMapping)); - } - - /** - * {@inheritDoc} - */ - public void write(final Map values, final String[] nameMapping, final CellProcessor[] processors) - throws IOException { - - super.incrementRowAndLineNo(); - - // execute the processors for each column - Util.executeCellProcessors(processedColumns, Util.filterMapToList(values, nameMapping), processors, - getLineNumber(), getRowNumber()); - - super.writeRow(processedColumns); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * CsvMapWriter writes Maps of Objects to a CSV file. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class CsvMapWriter extends AbstractCsvWriter implements ICsvMapWriter { + + // temporary storage of processed columns to be written + private final List processedColumns = new ArrayList(); + + /** + * Constructs a new CsvMapWriter with the supplied Writer and CSV preferences. Note that the + * writer will be wrapped in a BufferedWriter before accessed. + * + * @param writer + * the writer + * @param preference + * the CSV preferences + * @throws NullPointerException + * if writer or preference are null + * @since 1.0 + */ + public CsvMapWriter(final Writer writer, final CsvPreference preference) { + super(writer, preference); + } + + /** + * {@inheritDoc} + */ + public void write(final Map values, final String... nameMapping) throws IOException { + super.incrementRowAndLineNo(); + super.writeRow(Util.filterMapToObjectArray(values, nameMapping)); + } + + /** + * {@inheritDoc} + */ + public void write(final Map values, final String[] nameMapping, final CellProcessor[] processors) + throws IOException { + + super.incrementRowAndLineNo(); + + // execute the processors for each column + Util.executeCellProcessors(processedColumns, Util.filterMapToList(values, nameMapping), processors, + getLineNumber(), getRowNumber()); + + super.writeRow(processedColumns); + } +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvBeanReader.java b/super-csv/src/main/java/org/supercsv/io/ICsvBeanReader.java index 5c4de7ec..23ca5f5f 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvBeanReader.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvBeanReader.java @@ -1,94 +1,94 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.exception.SuperCsvReflectionException; - -/** - * Interface for CSV readers reading into objects/beans. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ICsvBeanReader extends ICsvReader { - - /** - * Reads a row of a CSV file and populates an instance of the specified class, using the supplied name mapping to - * map column values to the appropriate fields. - * - * @param clazz - * the type to instantiate. If the type is a class then a new instance will be created using the default - * no-args constructor. If the type is an interface, a proxy object which implements the interface will - * be created instead. - * @param nameMapping - * an array of Strings linking the CSV columns to their corresponding field in the bean (the array length - * should match the number of columns). A null entry in the array indicates that the column - * should be ignored (the field in the bean will be null - or its default value). - * @return a populated bean or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws IllegalArgumentException - * if nameMapping.length != number of columns read - * @throws NullPointerException - * if clazz or nameMapping are null - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @throws SuperCsvReflectionException - * if there was an reflection exception while mapping the values to the bean - * @since 1.0 - */ - T read(Class clazz, String... nameMapping) throws IOException; - - /** - * Reads a row of a CSV file and populates an instance of the specified class, using the supplied name mapping to - * map column values to the appropriate fields. Before population the data can be further processed by cell - * processors (as with the nameMapping array, each element in the processors array corresponds with a CSV column). A - * null entry in the processors array indicates no further processing is required (the unprocessed String - * value will be set on the bean's field). - * - * @param clazz - * the type to instantiate. If the type is a class then a new instance will be created using the default - * no-args constructor. If the type is an interface, a proxy object which implements the interface will - * be created instead. - * @param nameMapping - * an array of Strings linking the CSV columns to their corresponding field in the bean (the array length - * should match the number of columns). A null entry in the array indicates that the column - * should be ignored (the field in the bean will be null - or its default value). - * @param processors - * an array of CellProcessors used to further process data before it is populated on the bean (each - * element in the processors array corresponds with a CSV column - the number of processors should match - * the number of columns). A null entry indicates no further processing is required (the - * unprocessed String value will be set on the bean's field). - * @return a populated bean or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if clazz, nameMapping, or processors are null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @throws SuperCsvReflectionException - * if there was an reflection exception while mapping the values to the bean - * @since 1.0 - */ - T read(Class clazz, String[] nameMapping, CellProcessor... processors) throws IOException; -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.exception.SuperCsvReflectionException; + +/** + * Interface for CSV readers reading into objects/beans. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ICsvBeanReader extends ICsvReader { + + /** + * Reads a row of a CSV file and populates an instance of the specified class, using the supplied name mapping to + * map column values to the appropriate fields. + * + * @param clazz + * the type to instantiate. If the type is a class then a new instance will be created using the default + * no-args constructor. If the type is an interface, a proxy object which implements the interface will + * be created instead. + * @param nameMapping + * an array of Strings linking the CSV columns to their corresponding field in the bean (the array length + * should match the number of columns). A null entry in the array indicates that the column + * should be ignored (the field in the bean will be null - or its default value). + * @return a populated bean or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws IllegalArgumentException + * if nameMapping.length != number of columns read + * @throws NullPointerException + * if clazz or nameMapping are null + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @throws SuperCsvReflectionException + * if there was an reflection exception while mapping the values to the bean + * @since 1.0 + */ + T read(Class clazz, String... nameMapping) throws IOException; + + /** + * Reads a row of a CSV file and populates an instance of the specified class, using the supplied name mapping to + * map column values to the appropriate fields. Before population the data can be further processed by cell + * processors (as with the nameMapping array, each element in the processors array corresponds with a CSV column). A + * null entry in the processors array indicates no further processing is required (the unprocessed String + * value will be set on the bean's field). + * + * @param clazz + * the type to instantiate. If the type is a class then a new instance will be created using the default + * no-args constructor. If the type is an interface, a proxy object which implements the interface will + * be created instead. + * @param nameMapping + * an array of Strings linking the CSV columns to their corresponding field in the bean (the array length + * should match the number of columns). A null entry in the array indicates that the column + * should be ignored (the field in the bean will be null - or its default value). + * @param processors + * an array of CellProcessors used to further process data before it is populated on the bean (each + * element in the processors array corresponds with a CSV column - the number of processors should match + * the number of columns). A null entry indicates no further processing is required (the + * unprocessed String value will be set on the bean's field). + * @return a populated bean or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if clazz, nameMapping, or processors are null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @throws SuperCsvReflectionException + * if there was an reflection exception while mapping the values to the bean + * @since 1.0 + */ + T read(Class clazz, String[] nameMapping, CellProcessor... processors) throws IOException; +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvBeanWriter.java b/super-csv/src/main/java/org/supercsv/io/ICsvBeanWriter.java index 3ff38471..60f29f7d 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvBeanWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvBeanWriter.java @@ -1,83 +1,83 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.exception.SuperCsvReflectionException; - -/** - * Interface for all CSV writers writing to beans. - * - * @author Kasper B. Graversen - */ -public interface ICsvBeanWriter extends ICsvWriter { - - /** - * Writes the fields of the object as columns of a CSV file, using the supplied name mapping to map fields to the - * appropriate columns. toString() will be called on each element prior to writing. - * - * @param source - * the object (bean instance) containing the values to write - * @param nameMapping - * an array of Strings linking the fields in the bean to their corresponding CSV columns (the array - * length should match the number of columns). A null entry in the array indicates that the - * column should be ignored (the column will be empty). - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if source or nameMapping are null - * @throws SuperCsvException - * if there was a general exception while writing - * @throws SuperCsvReflectionException - * if there was an reflection exception while mapping the values from the bean - * @since 1.0 - */ - void write(Object source, String... nameMapping) throws IOException; - - /** - * Writes the fields of the object as columns of a CSV file, using the supplied name mapping to map fields to the - * appropriate columns. toString() will be called on each (processed) element prior to writing. - * - * @param source - * the object (bean instance) containing the values to write - * @param nameMapping - * an array of Strings linking the fields in the bean to their corresponding CSV columns (the array - * length should match the number of columns). A null entry in the array indicates that the - * column should be ignored (the column will be empty). - * @param processors - * an array of CellProcessors used to further process data before it is written (each element in the - * processors array corresponds with a CSV column - the number of processors should match the number of - * columns). A null entry indicates no further processing is required (the value returned by - * toString() will be written as the column value). - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if source, nameMapping or processors are null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if there was a general exception while writing/processing - * @throws SuperCsvReflectionException - * if there was an reflection exception while mapping the values from the bean - * @since 1.29 - */ - void write(Object source, String[] nameMapping, CellProcessor[] processors) throws IOException; - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.exception.SuperCsvReflectionException; + +/** + * Interface for all CSV writers writing to beans. + * + * @author Kasper B. Graversen + */ +public interface ICsvBeanWriter extends ICsvWriter { + + /** + * Writes the fields of the object as columns of a CSV file, using the supplied name mapping to map fields to the + * appropriate columns. toString() will be called on each element prior to writing. + * + * @param source + * the object (bean instance) containing the values to write + * @param nameMapping + * an array of Strings linking the fields in the bean to their corresponding CSV columns (the array + * length should match the number of columns). A null entry in the array indicates that the + * column should be ignored (the column will be empty). + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if source or nameMapping are null + * @throws SuperCsvException + * if there was a general exception while writing + * @throws SuperCsvReflectionException + * if there was an reflection exception while mapping the values from the bean + * @since 1.0 + */ + void write(Object source, String... nameMapping) throws IOException; + + /** + * Writes the fields of the object as columns of a CSV file, using the supplied name mapping to map fields to the + * appropriate columns. toString() will be called on each (processed) element prior to writing. + * + * @param source + * the object (bean instance) containing the values to write + * @param nameMapping + * an array of Strings linking the fields in the bean to their corresponding CSV columns (the array + * length should match the number of columns). A null entry in the array indicates that the + * column should be ignored (the column will be empty). + * @param processors + * an array of CellProcessors used to further process data before it is written (each element in the + * processors array corresponds with a CSV column - the number of processors should match the number of + * columns). A null entry indicates no further processing is required (the value returned by + * toString() will be written as the column value). + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if source, nameMapping or processors are null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if there was a general exception while writing/processing + * @throws SuperCsvReflectionException + * if there was an reflection exception while mapping the values from the bean + * @since 1.29 + */ + void write(Object source, String[] nameMapping, CellProcessor[] processors) throws IOException; + +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvListReader.java b/super-csv/src/main/java/org/supercsv/io/ICsvListReader.java index 0651d944..738aceec 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvListReader.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvListReader.java @@ -1,68 +1,68 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.util.List; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; - -/** - * Interface for readers that read into Lists. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ICsvListReader extends ICsvReader { - - /** - * Reads a row of a CSV file and returns a List of Strings containing each column. - * - * @return the List of columns, or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @since 1.0 - */ - List read() throws IOException; - - /** - * Reads a row of a CSV file and returns a List of Objects containing each column. The data can be further processed - * by cell processors (each element in the processors array corresponds with a CSV column). A null entry in - * the processors array indicates no further processing is required (the unprocessed String value will be added to - * the List). Prior to version 2.0.0 this method returned a List of Strings. - * - * @param processors - * an array of CellProcessors used to further process data before it is added to the List (each element - * in the processors array corresponds with a CSV column - the number of processors should match the - * number of columns). A null entry indicates no further processing is required (the unprocessed - * String value will be added to the List). - * @return the List of columns, or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if processors is null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @since 1.0 - */ - List read(CellProcessor... processors) throws IOException; -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.util.List; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; + +/** + * Interface for readers that read into Lists. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ICsvListReader extends ICsvReader { + + /** + * Reads a row of a CSV file and returns a List of Strings containing each column. + * + * @return the List of columns, or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @since 1.0 + */ + List read() throws IOException; + + /** + * Reads a row of a CSV file and returns a List of Objects containing each column. The data can be further processed + * by cell processors (each element in the processors array corresponds with a CSV column). A null entry in + * the processors array indicates no further processing is required (the unprocessed String value will be added to + * the List). Prior to version 2.0.0 this method returned a List of Strings. + * + * @param processors + * an array of CellProcessors used to further process data before it is added to the List (each element + * in the processors array corresponds with a CSV column - the number of processors should match the + * number of columns). A null entry indicates no further processing is required (the unprocessed + * String value will be added to the List). + * @return the List of columns, or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if processors is null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @since 1.0 + */ + List read(CellProcessor... processors) throws IOException; +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvListWriter.java b/super-csv/src/main/java/org/supercsv/io/ICsvListWriter.java index a2b44fb3..e687ef8a 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvListWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvListWriter.java @@ -1,111 +1,111 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.util.List; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; - -/** - * Interface for writers that write to a List. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ICsvListWriter extends ICsvWriter { - - /** - * Writes a List of Objects as columns of a CSV file. toString() will be called on each element prior to - * writing. - * - * @param columns - * the columns to write - * @throws IllegalArgumentException - * if columns.size == 0 - * @throws IOException - * If an I/O error occurs - * @throws NullPointerException - * if columns is null - * @throws SuperCsvException - * if there was a general exception while writing - * @since 1.0 - */ - void write(List columns) throws IOException; - - /** - * Writes a List of Objects as columns of a CSV file, performing any necessary processing beforehand. - * toString() will be called on each (processed) element prior to writing. - * - * @param columns - * the columns to write - * @param processors - * an array of CellProcessors used to further process data before it is written (each element in the - * processors array corresponds with a CSV column - the number of processors should match the number of - * columns). A null entry indicates no further processing is required (the value returned by - * toString() will be written as the column value). - * @throws IllegalArgumentException - * if columns.size == 0 - * @throws IOException - * If an I/O error occurs - * @throws NullPointerException - * if columns or processors is null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if there was a general exception while writing/processing - * @since 1.0 - */ - void write(List columns, CellProcessor[] processors) throws IOException; - - /** - * Writes a array of Objects as columns of a CSV file. toString() will be called on each element prior to - * writing. - * - * @param columns - * the columns to write - * @throws IllegalArgumentException - * if columns.length == 0 - * @throws IOException - * If an I/O error occurs - * @throws NullPointerException - * if columns is null - * @throws SuperCsvException - * if there was a general exception while writing - * @since 1.0 - */ - void write(Object... columns) throws IOException; - - /** - * Writes an array of strings as columns of a CSV file. - * - * @param columns - * the columns to write - * @throws IllegalArgumentException - * if columns.length == 0 - * @throws IOException - * If an I/O error occurs - * @throws NullPointerException - * if columns is null - * @throws SuperCsvException - * if there was a general exception while writing - * @since 1.0 - */ - void write(String... columns) throws IOException; - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.util.List; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; + +/** + * Interface for writers that write to a List. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ICsvListWriter extends ICsvWriter { + + /** + * Writes a List of Objects as columns of a CSV file. toString() will be called on each element prior to + * writing. + * + * @param columns + * the columns to write + * @throws IllegalArgumentException + * if columns.size == 0 + * @throws IOException + * If an I/O error occurs + * @throws NullPointerException + * if columns is null + * @throws SuperCsvException + * if there was a general exception while writing + * @since 1.0 + */ + void write(List columns) throws IOException; + + /** + * Writes a List of Objects as columns of a CSV file, performing any necessary processing beforehand. + * toString() will be called on each (processed) element prior to writing. + * + * @param columns + * the columns to write + * @param processors + * an array of CellProcessors used to further process data before it is written (each element in the + * processors array corresponds with a CSV column - the number of processors should match the number of + * columns). A null entry indicates no further processing is required (the value returned by + * toString() will be written as the column value). + * @throws IllegalArgumentException + * if columns.size == 0 + * @throws IOException + * If an I/O error occurs + * @throws NullPointerException + * if columns or processors is null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if there was a general exception while writing/processing + * @since 1.0 + */ + void write(List columns, CellProcessor[] processors) throws IOException; + + /** + * Writes a array of Objects as columns of a CSV file. toString() will be called on each element prior to + * writing. + * + * @param columns + * the columns to write + * @throws IllegalArgumentException + * if columns.length == 0 + * @throws IOException + * If an I/O error occurs + * @throws NullPointerException + * if columns is null + * @throws SuperCsvException + * if there was a general exception while writing + * @since 1.0 + */ + void write(Object... columns) throws IOException; + + /** + * Writes an array of strings as columns of a CSV file. + * + * @param columns + * the columns to write + * @throws IllegalArgumentException + * if columns.length == 0 + * @throws IOException + * If an I/O error occurs + * @throws NullPointerException + * if columns is null + * @throws SuperCsvException + * if there was a general exception while writing + * @since 1.0 + */ + void write(String... columns) throws IOException; + +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvMapReader.java b/super-csv/src/main/java/org/supercsv/io/ICsvMapReader.java index f110b003..16b7d871 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvMapReader.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvMapReader.java @@ -1,78 +1,78 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.util.Map; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; - -/** - * The interface for MapReaders, which read each CSV row into a Map. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ICsvMapReader extends ICsvReader { - - /** - * Reads a row of a CSV file into a Map, using the supplied name mapping to map column values to the appropriate map - * entries. - * - * @param nameMapping - * an array of Strings linking the CSV columns to their corresponding entry in the Map (the array length - * should match the number of columns). A null entry in the array indicates that the column - * should be ignored (e.g. not added to the Map). - * @return a Map of column names to column values (Strings, as no processing is performed), or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if nameMapping is null - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @since 1.0 - */ - Map read(String... nameMapping) throws IOException; - - /** - * Reads a row of a CSV file into a Map, using the supplied name mapping to map column values to the appropriate map - * entries, and the supplied processors to process the values before adding them to the Map. - * - * @param nameMapping - * an array of Strings linking the CSV columns to their corresponding entry in the Map (the array length - * should match the number of columns). A null entry in the array indicates that the column - * should be ignored (e.g. not added to the Map). - * @param processors - * an array of CellProcessors used to further process data before it is added to the Map (each element in - * the processors array corresponds with a CSV column - the number of processors should match the number - * of columns). A null entry indicates no further processing is required (the unprocessed String - * value will added to the Map). - * @return a Map of column names to column values, or null if EOF - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if nameMapping or processors are null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if there was a general exception while reading/processing - * @since 1.0 - */ - Map read(String[] nameMapping, CellProcessor[] processors) throws IOException; - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.util.Map; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; + +/** + * The interface for MapReaders, which read each CSV row into a Map. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ICsvMapReader extends ICsvReader { + + /** + * Reads a row of a CSV file into a Map, using the supplied name mapping to map column values to the appropriate map + * entries. + * + * @param nameMapping + * an array of Strings linking the CSV columns to their corresponding entry in the Map (the array length + * should match the number of columns). A null entry in the array indicates that the column + * should be ignored (e.g. not added to the Map). + * @return a Map of column names to column values (Strings, as no processing is performed), or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if nameMapping is null + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @since 1.0 + */ + Map read(String... nameMapping) throws IOException; + + /** + * Reads a row of a CSV file into a Map, using the supplied name mapping to map column values to the appropriate map + * entries, and the supplied processors to process the values before adding them to the Map. + * + * @param nameMapping + * an array of Strings linking the CSV columns to their corresponding entry in the Map (the array length + * should match the number of columns). A null entry in the array indicates that the column + * should be ignored (e.g. not added to the Map). + * @param processors + * an array of CellProcessors used to further process data before it is added to the Map (each element in + * the processors array corresponds with a CSV column - the number of processors should match the number + * of columns). A null entry indicates no further processing is required (the unprocessed String + * value will added to the Map). + * @return a Map of column names to column values, or null if EOF + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if nameMapping or processors are null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if there was a general exception while reading/processing + * @since 1.0 + */ + Map read(String[] nameMapping, CellProcessor[] processors) throws IOException; + +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvMapWriter.java b/super-csv/src/main/java/org/supercsv/io/ICsvMapWriter.java index 9798c747..29ed977b 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvMapWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvMapWriter.java @@ -1,80 +1,80 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.util.Map; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; - -/** - * The interface for writers that write from Maps. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ICsvMapWriter extends ICsvWriter { - - /** - * Writes the values of the Map as columns of a CSV file, using the supplied name mapping to map values to the - * appropriate columns. toString() will be called on each element prior to writing. - * - * @param values - * the Map containing the values to write - * @param nameMapping - * an array of Strings linking the Map keys to their corresponding CSV columns (the array length should - * match the number of columns). A null entry in the array indicates that the column should be - * ignored (the column will be empty). - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if values or nameMapping are null - * @throws SuperCsvException - * if there was a general exception while writing - * @since 1.0 - */ - void write(Map values, String... nameMapping) throws IOException; - - /** - * Writes the values of the Map as columns of a CSV file, using the supplied name mapping to map values to the - * appropriate columns. toString() will be called on each element prior to writing. - * - * @param values - * the Map containing the values to write - * @param nameMapping - * an array of Strings linking the Map keys to their corresponding CSV columns (the array length should - * match the number of columns). A null entry in the array indicates that the column should be - * ignored (the column will be empty). - * @param processors - * an array of CellProcessors used to further process data before it is written (each element in the - * processors array corresponds with a CSV column - the number of processors should match the number of - * columns). A null entry indicates no further processing is required (the value returned by - * toString() will be written as the column value). - * @throws IOException - * if an I/O error occurred - * @throws NullPointerException - * if values or nameMapping are null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if there was a general exception while writing - * @since 1.20 - */ - void write(Map values, String[] nameMapping, CellProcessor[] processors) throws IOException; - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.util.Map; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; + +/** + * The interface for writers that write from Maps. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ICsvMapWriter extends ICsvWriter { + + /** + * Writes the values of the Map as columns of a CSV file, using the supplied name mapping to map values to the + * appropriate columns. toString() will be called on each element prior to writing. + * + * @param values + * the Map containing the values to write + * @param nameMapping + * an array of Strings linking the Map keys to their corresponding CSV columns (the array length should + * match the number of columns). A null entry in the array indicates that the column should be + * ignored (the column will be empty). + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if values or nameMapping are null + * @throws SuperCsvException + * if there was a general exception while writing + * @since 1.0 + */ + void write(Map values, String... nameMapping) throws IOException; + + /** + * Writes the values of the Map as columns of a CSV file, using the supplied name mapping to map values to the + * appropriate columns. toString() will be called on each element prior to writing. + * + * @param values + * the Map containing the values to write + * @param nameMapping + * an array of Strings linking the Map keys to their corresponding CSV columns (the array length should + * match the number of columns). A null entry in the array indicates that the column should be + * ignored (the column will be empty). + * @param processors + * an array of CellProcessors used to further process data before it is written (each element in the + * processors array corresponds with a CSV column - the number of processors should match the number of + * columns). A null entry indicates no further processing is required (the value returned by + * toString() will be written as the column value). + * @throws IOException + * if an I/O error occurred + * @throws NullPointerException + * if values or nameMapping are null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if there was a general exception while writing + * @since 1.20 + */ + void write(Map values, String[] nameMapping, CellProcessor[] processors) throws IOException; + +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvReader.java b/super-csv/src/main/java/org/supercsv/io/ICsvReader.java index 39ad684a..cf73f62b 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvReader.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvReader.java @@ -1,91 +1,91 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.Closeable; -import java.io.IOException; - -import org.supercsv.exception.SuperCsvException; - -/** - * The interface for CSV readers. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ICsvReader extends Closeable { - - /** - * Get column N of the current line (column indexes begin at 1). - * - * @param n - * the index of the column to get - * @return the n'th column - * @throws IndexOutOfBoundsException - * if the supplied index is not a valid column index - * @since 1.0 - */ - String get(int n); - - /** - * This method is used to get an optional header of the CSV file and move the file cursor to the first row - * containing data (the second row from the top). The header can subsequently be used as the - * nameMapping array for read operations. - * - * @param firstLineCheck - * if true, ensures that this method is only called when reading the first line (as that's where the - * header is meant to be) - * @return the array of header fields, or null if EOF is encountered - * @throws IOException - * if an I/O exception occurs - * @throws SuperCsvException - * if firstLineCheck == true and it's not the first line being read - * @since 1.0 - */ - String[] getHeader(boolean firstLineCheck) throws IOException; - - /** - * Gets the current position in the file. The first line of the file is line number 1. - * - * @since 1.0 - */ - int getLineNumber(); - - /** - * Returns the untokenized CSV row that was just read (which can potentially span multiple lines in the file). - * - * @return the untokenized CSV row that was just read - * @since 2.0.0 - */ - String getUntokenizedRow(); - - /** - * Gets the current row number (i.e. the number of CSV records - including the header - that have been read). This - * differs from the lineNumber, which is the number of real lines that have been read in the file. The first row is - * row 1 (which is typically the header row). - * - * @since 2.0.0 - */ - int getRowNumber(); - - /** - * Returns the length (i.e. number of columns) of the current row. - * - * @since 1.0 - */ - int length(); - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.Closeable; +import java.io.IOException; + +import org.supercsv.exception.SuperCsvException; + +/** + * The interface for CSV readers. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ICsvReader extends Closeable { + + /** + * Get column N of the current line (column indexes begin at 1). + * + * @param n + * the index of the column to get + * @return the n'th column + * @throws IndexOutOfBoundsException + * if the supplied index is not a valid column index + * @since 1.0 + */ + String get(int n); + + /** + * This method is used to get an optional header of the CSV file and move the file cursor to the first row + * containing data (the second row from the top). The header can subsequently be used as the + * nameMapping array for read operations. + * + * @param firstLineCheck + * if true, ensures that this method is only called when reading the first line (as that's where the + * header is meant to be) + * @return the array of header fields, or null if EOF is encountered + * @throws IOException + * if an I/O exception occurs + * @throws SuperCsvException + * if firstLineCheck == true and it's not the first line being read + * @since 1.0 + */ + String[] getHeader(boolean firstLineCheck) throws IOException; + + /** + * Gets the current position in the file. The first line of the file is line number 1. + * + * @since 1.0 + */ + int getLineNumber(); + + /** + * Returns the untokenized CSV row that was just read (which can potentially span multiple lines in the file). + * + * @return the untokenized CSV row that was just read + * @since 2.0.0 + */ + String getUntokenizedRow(); + + /** + * Gets the current row number (i.e. the number of CSV records - including the header - that have been read). This + * differs from the lineNumber, which is the number of real lines that have been read in the file. The first row is + * row 1 (which is typically the header row). + * + * @since 2.0.0 + */ + int getRowNumber(); + + /** + * Returns the length (i.e. number of columns) of the current row. + * + * @since 1.0 + */ + int length(); + +} diff --git a/super-csv/src/main/java/org/supercsv/io/ICsvWriter.java b/super-csv/src/main/java/org/supercsv/io/ICsvWriter.java index 3358db5a..bf397aac 100644 --- a/super-csv/src/main/java/org/supercsv/io/ICsvWriter.java +++ b/super-csv/src/main/java/org/supercsv/io/ICsvWriter.java @@ -1,59 +1,59 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.Closeable; -import java.io.Flushable; -import java.io.IOException; - -/** - * The interface for CSV writers. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ICsvWriter extends Closeable, Flushable { - - /** - * Gets the current position in the file. The first line of the file is line number 1. - * - * @since 1.0 - */ - int getLineNumber(); - - /** - * Gets the current row number (i.e. the number of CSV records - including the header - that have been written). - * This differs from the lineNumber, which is the number of real lines that have been written to the file. The first - * row is row 1 (which is typically the header row). - * - * @since 2.0.0 - */ - int getRowNumber(); - - /** - * Writes the header of the CSV file. - * - * @param header - * one or more header Strings - * @throws NullPointerException - * if header is null - * @throws IOException - * if an I/O error occurs - * @since 1.0 - */ - void writeHeader(String... header) throws IOException; - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.Closeable; +import java.io.Flushable; +import java.io.IOException; + +/** + * The interface for CSV writers. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ICsvWriter extends Closeable, Flushable { + + /** + * Gets the current position in the file. The first line of the file is line number 1. + * + * @since 1.0 + */ + int getLineNumber(); + + /** + * Gets the current row number (i.e. the number of CSV records - including the header - that have been written). + * This differs from the lineNumber, which is the number of real lines that have been written to the file. The first + * row is row 1 (which is typically the header row). + * + * @since 2.0.0 + */ + int getRowNumber(); + + /** + * Writes the header of the CSV file. + * + * @param header + * one or more header Strings + * @throws NullPointerException + * if header is null + * @throws IOException + * if an I/O error occurs + * @since 1.0 + */ + void writeHeader(String... header) throws IOException; + +} diff --git a/super-csv/src/main/java/org/supercsv/io/ITokenizer.java b/super-csv/src/main/java/org/supercsv/io/ITokenizer.java index 34cf50ef..ae652d1b 100644 --- a/super-csv/src/main/java/org/supercsv/io/ITokenizer.java +++ b/super-csv/src/main/java/org/supercsv/io/ITokenizer.java @@ -1,70 +1,70 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.Closeable; -import java.io.IOException; -import java.util.List; - -import org.supercsv.exception.SuperCsvException; - -/** - * The interface for tokenizers, which are responsible for reading the CSV file, line by line. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public interface ITokenizer extends Closeable { - - /** - * Gets the line number currently being tokenized (the first line is line 1). This number increments at every line - * terminator as the data is read, i.e. it will be - *
    - *
  • 0, if {@link #readColumns(List)} hasn't been called yet
  • - *
  • 1, when the first line is being read/tokenized
  • - *
  • 2, when the second line is being read/tokenized
  • - *
- * - * @return the line number currently being tokenized - */ - int getLineNumber(); - - /** - * Returns the raw (untokenized) CSV row that was just read (which can potentially span multiple lines in the file). - * - * @return the raw (untokenized) CSV row that was just read - * @since 2.0.0 - */ - String getUntokenizedRow(); - - /** - * Reads a CSV row into the supplied List of columns (which can potentially span multiple lines in the file). The - * columns list is cleared as the first operation in the method. Any empty columns ("") will be added to the list as - * null. - * - * @param columns - * the List of columns to read into - * @return true if something was read, or false if EOF - * @throws IOException - * when an IOException occurs - * @throws NullPointerException - * if columns is null - * @throws SuperCsvException - * on errors in parsing the input - * @since 2.0.0 (was previously called readStringList) - */ - boolean readColumns(List columns) throws IOException; -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.Closeable; +import java.io.IOException; +import java.util.List; + +import org.supercsv.exception.SuperCsvException; + +/** + * The interface for tokenizers, which are responsible for reading the CSV file, line by line. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public interface ITokenizer extends Closeable { + + /** + * Gets the line number currently being tokenized (the first line is line 1). This number increments at every line + * terminator as the data is read, i.e. it will be + *
    + *
  • 0, if {@link #readColumns(List)} hasn't been called yet
  • + *
  • 1, when the first line is being read/tokenized
  • + *
  • 2, when the second line is being read/tokenized
  • + *
+ * + * @return the line number currently being tokenized + */ + int getLineNumber(); + + /** + * Returns the raw (untokenized) CSV row that was just read (which can potentially span multiple lines in the file). + * + * @return the raw (untokenized) CSV row that was just read + * @since 2.0.0 + */ + String getUntokenizedRow(); + + /** + * Reads a CSV row into the supplied List of columns (which can potentially span multiple lines in the file). The + * columns list is cleared as the first operation in the method. Any empty columns ("") will be added to the list as + * null. + * + * @param columns + * the List of columns to read into + * @return true if something was read, or false if EOF + * @throws IOException + * when an IOException occurs + * @throws NullPointerException + * if columns is null + * @throws SuperCsvException + * on errors in parsing the input + * @since 2.0.0 (was previously called readStringList) + */ + boolean readColumns(List columns) throws IOException; +} diff --git a/super-csv/src/main/java/org/supercsv/io/Tokenizer.java b/super-csv/src/main/java/org/supercsv/io/Tokenizer.java index 316cc6d7..a1c96160 100644 --- a/super-csv/src/main/java/org/supercsv/io/Tokenizer.java +++ b/super-csv/src/main/java/org/supercsv/io/Tokenizer.java @@ -1,254 +1,254 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import java.io.IOException; -import java.io.Reader; -import java.util.List; - -import org.supercsv.exception.SuperCsvException; -import org.supercsv.prefs.CsvPreference; - -/** - * Reads the CSV file, line by line. If you want the line-reading functionality of this class, but want to define your - * own implementation of {@link #readColumns(List)}, then consider writing your own Tokenizer by extending - * AbstractTokenizer. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class Tokenizer extends AbstractTokenizer { - - private static final char NEWLINE = '\n'; - - private static final char SPACE = ' '; - - private final StringBuilder currentColumn = new StringBuilder(); - - /* the raw, untokenized CSV row (may span multiple lines) */ - private final StringBuilder currentRow = new StringBuilder(); - - private final int quoteChar; - - private final int delimeterChar; - - private final boolean surroundingSpacesNeedQuotes; - - /** - * Enumeration of tokenizer states. QUOTE_MODE is activated between quotes. - */ - private enum TokenizerState { - NORMAL, QUOTE_MODE; - } - - /** - * Constructs a new Tokenizer, which reads the CSV file, line by line. - * - * @param reader - * the reader - * @param preferences - * the CSV preferences - * @throws NullPointerException - * if reader or preferences is null - */ - public Tokenizer(final Reader reader, final CsvPreference preferences) { - super(reader, preferences); - this.quoteChar = preferences.getQuoteChar(); - this.delimeterChar = preferences.getDelimiterChar(); - this.surroundingSpacesNeedQuotes = preferences.isSurroundingSpacesNeedQuotes(); - } - - /** - * {@inheritDoc} - */ - public boolean readColumns(final List columns) throws IOException { - - if( columns == null ) { - throw new NullPointerException("columns should not be null"); - } - - // clear the reusable List and StringBuilders - columns.clear(); - currentColumn.setLength(0); - currentRow.setLength(0); - - // keep reading lines until data is found - String line; - do { - line = readLine(); - if( line == null ) { - return false; // EOF - } - } - while( line.length() == 0 ); - - // update the untokenized CSV row - currentRow.append(line); - - // add a newline to determine end of line (making parsing easier) - line += NEWLINE; - - // process each character in the line, catering for surrounding quotes (QUOTE_MODE) - TokenizerState state = TokenizerState.NORMAL; - int quoteScopeStartingLine = -1; // the line number where a potential multi-line cell starts - int potentialSpaces = 0; // keep track of spaces (so leading/trailing space can be removed if required) - int charIndex = 0; - while( true ) { - - final char c = line.charAt(charIndex); - - if( TokenizerState.NORMAL.equals(state) ) { - - /* - * NORMAL mode (not within quotes). - */ - - if( c == delimeterChar ) { - /* - * Delimiter. Save the column (trim trailing space if required) then continue to next character. - */ - if( !surroundingSpacesNeedQuotes ) { - appendSpaces(currentColumn, potentialSpaces); - } - columns.add(currentColumn.length() > 0 ? currentColumn.toString() : null); // "" -> null - potentialSpaces = 0; - currentColumn.setLength(0); - - } else if( c == SPACE ) { - /* - * Space. Remember it, then continue to next character. - */ - potentialSpaces++; - - } else if( c == NEWLINE ) { - /* - * Newline. Add any required spaces (if surrounding spaces don't need quotes) and return (we've read - * a line!). - */ - if( !surroundingSpacesNeedQuotes ) { - appendSpaces(currentColumn, potentialSpaces); - } - columns.add(currentColumn.length() > 0 ? currentColumn.toString() : null); // "" -> null - return true; - - } else if( c == quoteChar ) { - /* - * A single quote ("). Update to QUOTESCOPE (but don't save quote), then continue to next character. - */ - state = TokenizerState.QUOTE_MODE; - quoteScopeStartingLine = getLineNumber(); - - // cater for spaces before a quoted section (be lenient!) - if( !surroundingSpacesNeedQuotes || currentColumn.length() > 0 ) { - appendSpaces(currentColumn, potentialSpaces); - } - potentialSpaces = 0; - - } else { - /* - * Just a normal character. Add any required spaces (but trim any leading spaces if surrounding - * spaces need quotes), add the character, then continue to next character. - */ - if( !surroundingSpacesNeedQuotes || currentColumn.length() > 0 ) { - appendSpaces(currentColumn, potentialSpaces); - } - - potentialSpaces = 0; - currentColumn.append(c); - } - - } else { - - /* - * QUOTE_MODE (within quotes). - */ - - if( c == NEWLINE ) { - - /* - * Newline. Doesn't count as newline while in QUOTESCOPE. Add the newline char, reset the charIndex - * (will update to 0 for next iteration), read in the next line, then then continue to next - * character. For a large file with an unterminated quoted section (no trailing quote), this could - * cause memory issues as it will keep reading lines looking for the trailing quote. Maybe there - * should be a configurable limit on max lines to read in quoted mode? - */ - currentColumn.append(NEWLINE); - currentRow.append(NEWLINE); // specific line terminator lost, \n will have to suffice - - charIndex = -1; - line = readLine(); - if( line == null ) { - throw new SuperCsvException( - String - .format( - "unexpected end of file while reading quoted column beginning on line %d and ending on line %d", - quoteScopeStartingLine, getLineNumber())); - } - - currentRow.append(line); // update untokenized CSV row - line += NEWLINE; // add newline to simplify parsing - - } else if( c == quoteChar ) { - - if( line.charAt(charIndex + 1) == quoteChar ) { - /* - * An escaped quote (""). Add a single quote, then move the cursor so the next iteration of the - * loop will read the character following the escaped quote. - */ - currentColumn.append(c); - charIndex++; - - } else { - /* - * A single quote ("). Update to NORMAL (but don't save quote), then continue to next character. - */ - state = TokenizerState.NORMAL; - quoteScopeStartingLine = -1; // reset ready for next multi-line cell - } - } else { - /* - * Just a normal character, delimiter (they don't count in QUOTESCOPE) or space. Add the character, - * then continue to next character. - */ - currentColumn.append(c); - } - } - - charIndex++; // read next char of the line - } - } - - /** - * Appends the required number of spaces to the StringBuilder. - * - * @param sb - * the StringBuilder - * @param spaces - * the required number of spaces to append - */ - private static void appendSpaces(final StringBuilder sb, final int spaces) { - for( int i = 0; i < spaces; i++ ) { - sb.append(SPACE); - } - } - - /** - * {@inheritDoc} - */ - public String getUntokenizedRow() { - return currentRow.toString(); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import java.io.IOException; +import java.io.Reader; +import java.util.List; + +import org.supercsv.exception.SuperCsvException; +import org.supercsv.prefs.CsvPreference; + +/** + * Reads the CSV file, line by line. If you want the line-reading functionality of this class, but want to define your + * own implementation of {@link #readColumns(List)}, then consider writing your own Tokenizer by extending + * AbstractTokenizer. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class Tokenizer extends AbstractTokenizer { + + private static final char NEWLINE = '\n'; + + private static final char SPACE = ' '; + + private final StringBuilder currentColumn = new StringBuilder(); + + /* the raw, untokenized CSV row (may span multiple lines) */ + private final StringBuilder currentRow = new StringBuilder(); + + private final int quoteChar; + + private final int delimeterChar; + + private final boolean surroundingSpacesNeedQuotes; + + /** + * Enumeration of tokenizer states. QUOTE_MODE is activated between quotes. + */ + private enum TokenizerState { + NORMAL, QUOTE_MODE; + } + + /** + * Constructs a new Tokenizer, which reads the CSV file, line by line. + * + * @param reader + * the reader + * @param preferences + * the CSV preferences + * @throws NullPointerException + * if reader or preferences is null + */ + public Tokenizer(final Reader reader, final CsvPreference preferences) { + super(reader, preferences); + this.quoteChar = preferences.getQuoteChar(); + this.delimeterChar = preferences.getDelimiterChar(); + this.surroundingSpacesNeedQuotes = preferences.isSurroundingSpacesNeedQuotes(); + } + + /** + * {@inheritDoc} + */ + public boolean readColumns(final List columns) throws IOException { + + if( columns == null ) { + throw new NullPointerException("columns should not be null"); + } + + // clear the reusable List and StringBuilders + columns.clear(); + currentColumn.setLength(0); + currentRow.setLength(0); + + // keep reading lines until data is found + String line; + do { + line = readLine(); + if( line == null ) { + return false; // EOF + } + } + while( line.length() == 0 ); + + // update the untokenized CSV row + currentRow.append(line); + + // add a newline to determine end of line (making parsing easier) + line += NEWLINE; + + // process each character in the line, catering for surrounding quotes (QUOTE_MODE) + TokenizerState state = TokenizerState.NORMAL; + int quoteScopeStartingLine = -1; // the line number where a potential multi-line cell starts + int potentialSpaces = 0; // keep track of spaces (so leading/trailing space can be removed if required) + int charIndex = 0; + while( true ) { + + final char c = line.charAt(charIndex); + + if( TokenizerState.NORMAL.equals(state) ) { + + /* + * NORMAL mode (not within quotes). + */ + + if( c == delimeterChar ) { + /* + * Delimiter. Save the column (trim trailing space if required) then continue to next character. + */ + if( !surroundingSpacesNeedQuotes ) { + appendSpaces(currentColumn, potentialSpaces); + } + columns.add(currentColumn.length() > 0 ? currentColumn.toString() : null); // "" -> null + potentialSpaces = 0; + currentColumn.setLength(0); + + } else if( c == SPACE ) { + /* + * Space. Remember it, then continue to next character. + */ + potentialSpaces++; + + } else if( c == NEWLINE ) { + /* + * Newline. Add any required spaces (if surrounding spaces don't need quotes) and return (we've read + * a line!). + */ + if( !surroundingSpacesNeedQuotes ) { + appendSpaces(currentColumn, potentialSpaces); + } + columns.add(currentColumn.length() > 0 ? currentColumn.toString() : null); // "" -> null + return true; + + } else if( c == quoteChar ) { + /* + * A single quote ("). Update to QUOTESCOPE (but don't save quote), then continue to next character. + */ + state = TokenizerState.QUOTE_MODE; + quoteScopeStartingLine = getLineNumber(); + + // cater for spaces before a quoted section (be lenient!) + if( !surroundingSpacesNeedQuotes || currentColumn.length() > 0 ) { + appendSpaces(currentColumn, potentialSpaces); + } + potentialSpaces = 0; + + } else { + /* + * Just a normal character. Add any required spaces (but trim any leading spaces if surrounding + * spaces need quotes), add the character, then continue to next character. + */ + if( !surroundingSpacesNeedQuotes || currentColumn.length() > 0 ) { + appendSpaces(currentColumn, potentialSpaces); + } + + potentialSpaces = 0; + currentColumn.append(c); + } + + } else { + + /* + * QUOTE_MODE (within quotes). + */ + + if( c == NEWLINE ) { + + /* + * Newline. Doesn't count as newline while in QUOTESCOPE. Add the newline char, reset the charIndex + * (will update to 0 for next iteration), read in the next line, then then continue to next + * character. For a large file with an unterminated quoted section (no trailing quote), this could + * cause memory issues as it will keep reading lines looking for the trailing quote. Maybe there + * should be a configurable limit on max lines to read in quoted mode? + */ + currentColumn.append(NEWLINE); + currentRow.append(NEWLINE); // specific line terminator lost, \n will have to suffice + + charIndex = -1; + line = readLine(); + if( line == null ) { + throw new SuperCsvException( + String + .format( + "unexpected end of file while reading quoted column beginning on line %d and ending on line %d", + quoteScopeStartingLine, getLineNumber())); + } + + currentRow.append(line); // update untokenized CSV row + line += NEWLINE; // add newline to simplify parsing + + } else if( c == quoteChar ) { + + if( line.charAt(charIndex + 1) == quoteChar ) { + /* + * An escaped quote (""). Add a single quote, then move the cursor so the next iteration of the + * loop will read the character following the escaped quote. + */ + currentColumn.append(c); + charIndex++; + + } else { + /* + * A single quote ("). Update to NORMAL (but don't save quote), then continue to next character. + */ + state = TokenizerState.NORMAL; + quoteScopeStartingLine = -1; // reset ready for next multi-line cell + } + } else { + /* + * Just a normal character, delimiter (they don't count in QUOTESCOPE) or space. Add the character, + * then continue to next character. + */ + currentColumn.append(c); + } + } + + charIndex++; // read next char of the line + } + } + + /** + * Appends the required number of spaces to the StringBuilder. + * + * @param sb + * the StringBuilder + * @param spaces + * the required number of spaces to append + */ + private static void appendSpaces(final StringBuilder sb, final int spaces) { + for( int i = 0; i < spaces; i++ ) { + sb.append(SPACE); + } + } + + /** + * {@inheritDoc} + */ + public String getUntokenizedRow() { + return currentRow.toString(); + } +} diff --git a/super-csv/src/main/java/org/supercsv/io/package-info.java b/super-csv/src/main/java/org/supercsv/io/package-info.java index d2d8bf75..aa15b3d9 100644 --- a/super-csv/src/main/java/org/supercsv/io/package-info.java +++ b/super-csv/src/main/java/org/supercsv/io/package-info.java @@ -1,20 +1,20 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides the various readers and writers used to read/write Strings, Maps, or Objects. In order to - * use a reader/writer it should be configured with CellProcessors and a CSVPreference. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides the various readers and writers used to read/write Strings, Maps, or Objects. In order to + * use a reader/writer it should be configured with CellProcessors and a CSVPreference. + */ package org.supercsv.io; \ No newline at end of file diff --git a/super-csv/src/main/java/org/supercsv/prefs/CsvPreference.java b/super-csv/src/main/java/org/supercsv/prefs/CsvPreference.java index 1e7ee66c..5c109568 100644 --- a/super-csv/src/main/java/org/supercsv/prefs/CsvPreference.java +++ b/super-csv/src/main/java/org/supercsv/prefs/CsvPreference.java @@ -1,233 +1,233 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.prefs; - -/** - * Before reading or writing CSV files, you must supply the reader/writer with some preferences. - *

- * Please note: the end of line symbols are only used for writing. - *

- * The following predefined configurations are available: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
ConstantQuote characterDelimiter characterEnd of line symbols
STANDARD_PREFERENCE",\r\n
EXCEL_PREFERENCE",\n
EXCEL_NORTH_EUROPE_PREFERENCE";\n
TAB_PREFERENCE"\t\n
- *

- * By default, spaces surrounding an unquoted cell are treated as part of the data. In versions of Super CSV prior to - * 2.0.0 this wasn't the case, and any surrounding spaces that weren't within quotes were ignored when reading (and - * quotes were automatically added to Strings containing surrounding spaces when writing). - *

- * If you wish enable this functionality again, then you can create a CsvPreference with the - * surroundingSpacesNeedQuotes flag set to true (the default is false). This means that surrounding spaces without - * quotes will be trimmed when reading, and quotes will automatically be added for Strings containing surrounding spaces - * when writing. - *

- * You can apply the surroundingSpacesNeedQuotes property to an existing preference as follows:
- * {@code private static final CsvPreference STANDARD_SURROUNDING_SPACES_NEED_QUOTES = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build();} - *

- * You can also create your own preferences. For example if your file was pipe-delimited, you could use the following:
- * {@code private static final CsvPreference PIPE_DELIMITED = new CsvPreference.Builder('"', '|', "\n").build();} - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public final class CsvPreference { - - /** - * Ready to use configuration that should cover 99% of all usages. - */ - public static final CsvPreference STANDARD_PREFERENCE = new CsvPreference.Builder('"', ',', "\r\n").build(); - - /** - * Ready to use configuration for Windows Excel exported CSV files. - */ - public static final CsvPreference EXCEL_PREFERENCE = new CsvPreference.Builder('"', ',', "\n").build(); - - /** - * Ready to use configuration for north European excel CSV files (columns are separated by ";" instead of ",") - */ - public static final CsvPreference EXCEL_NORTH_EUROPE_PREFERENCE = new CsvPreference.Builder('"', ';', "\n").build(); - - /** - * Ready to use configuration for tab-delimited files. - */ - public static final CsvPreference TAB_PREFERENCE = new CsvPreference.Builder('"', '\t', "\n").build(); - - private final char quoteChar; - - private final int delimiterChar; - - private final String endOfLineSymbols; - - private final boolean surroundingSpacesNeedQuotes; - - /** - * Constructs a new CsvPreference from a Builder. - */ - private CsvPreference(Builder builder) { - this.quoteChar = builder.quoteChar; - this.delimiterChar = builder.delimiterChar; - this.endOfLineSymbols = builder.endOfLineSymbols; - this.surroundingSpacesNeedQuotes = builder.surroundingSpacesNeedQuotes; - } - - /** - * Returns the delimiter character - * - * @return the delimiter character - */ - public int getDelimiterChar() { - return delimiterChar; - } - - /** - * Returns the end of line symbols - * - * @return the end of line symbols - */ - public String getEndOfLineSymbols() { - return endOfLineSymbols; - } - - /** - * Returns the quote character - * - * @return the quote character - */ - public int getQuoteChar() { - return quoteChar; - } - - /** - * Returns the surroundingSpacesNeedQuotes flag. - * - * @return the surroundingSpacesNeedQuotes flag - */ - public boolean isSurroundingSpacesNeedQuotes() { - return surroundingSpacesNeedQuotes; - } - - /** - * Builds immutable CsvPreference instances. The builder pattern allows for additional preferences to be - * added in the future. - */ - public static class Builder { - - private final char quoteChar; - - private final int delimiterChar; - - private final String endOfLineSymbols; - - private boolean surroundingSpacesNeedQuotes = false; - - /** - * Constructs a Builder with all of the values from an existing CsvPreference instance. Useful if you - * want to base your preferences off one of the existing CsvPreference constants. - * - * @param preference - * the existing preference - */ - public Builder(final CsvPreference preference) { - this.quoteChar = preference.quoteChar; - this.delimiterChar = preference.delimiterChar; - this.endOfLineSymbols = preference.endOfLineSymbols; - this.surroundingSpacesNeedQuotes = preference.surroundingSpacesNeedQuotes; - } - - /** - * Constructs a Builder with the mandatory preference values. - * - * @param quoteChar - * matching pairs of this character are used to escape columns containing the delimiter - * @param delimiterChar - * the character separating each column - * @param endOfLineSymbols - * one or more symbols terminating the line, e.g. "\n". Only used for writing. - * @throws IllegalArgumentException - * if quoteChar and delimiterChar are the same character - * @throws NullPointerException - * if endOfLineSymbols is null - */ - public Builder(final char quoteChar, final int delimiterChar, final String endOfLineSymbols) { - if( quoteChar == delimiterChar ) { - throw new IllegalArgumentException(String.format( - "quoteChar and delimiterChar should not be the same character: %c", quoteChar)); - } else if( endOfLineSymbols == null ) { - throw new NullPointerException("endOfLineSymbols should not be null"); - } - this.quoteChar = quoteChar; - this.delimiterChar = delimiterChar; - this.endOfLineSymbols = endOfLineSymbols; - } - - /** - * Flag indicating whether spaces at the beginning or end of a cell should be ignored if they're not surrounded - * by quotes (applicable to both reading and writing CSV). The default is false, as spaces - * "are considered part of a field and should not be ignored" according to RFC 4180. - * - * @param surroundingSpacesNeedQuotes - * flag indicating whether spaces at the beginning or end of a cell should be ignored if they're not - * surrounded by quotes - * @return the updated Builder - */ - public Builder surroundingSpacesNeedQuotes(final boolean surroundingSpacesNeedQuotes) { - this.surroundingSpacesNeedQuotes = surroundingSpacesNeedQuotes; - return this; - } - - /** - * Builds the CsvPreference instance. - * - * @return the immutable CsvPreference instance - */ - public CsvPreference build() { - return new CsvPreference(this); - } - - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.prefs; + +/** + * Before reading or writing CSV files, you must supply the reader/writer with some preferences. + *

+ * Please note: the end of line symbols are only used for writing. + *

+ * The following predefined configurations are available: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ConstantQuote characterDelimiter characterEnd of line symbols
STANDARD_PREFERENCE",\r\n
EXCEL_PREFERENCE",\n
EXCEL_NORTH_EUROPE_PREFERENCE";\n
TAB_PREFERENCE"\t\n
+ *

+ * By default, spaces surrounding an unquoted cell are treated as part of the data. In versions of Super CSV prior to + * 2.0.0 this wasn't the case, and any surrounding spaces that weren't within quotes were ignored when reading (and + * quotes were automatically added to Strings containing surrounding spaces when writing). + *

+ * If you wish enable this functionality again, then you can create a CsvPreference with the + * surroundingSpacesNeedQuotes flag set to true (the default is false). This means that surrounding spaces without + * quotes will be trimmed when reading, and quotes will automatically be added for Strings containing surrounding spaces + * when writing. + *

+ * You can apply the surroundingSpacesNeedQuotes property to an existing preference as follows:
+ * {@code private static final CsvPreference STANDARD_SURROUNDING_SPACES_NEED_QUOTES = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build();} + *

+ * You can also create your own preferences. For example if your file was pipe-delimited, you could use the following:
+ * {@code private static final CsvPreference PIPE_DELIMITED = new CsvPreference.Builder('"', '|', "\n").build();} + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public final class CsvPreference { + + /** + * Ready to use configuration that should cover 99% of all usages. + */ + public static final CsvPreference STANDARD_PREFERENCE = new CsvPreference.Builder('"', ',', "\r\n").build(); + + /** + * Ready to use configuration for Windows Excel exported CSV files. + */ + public static final CsvPreference EXCEL_PREFERENCE = new CsvPreference.Builder('"', ',', "\n").build(); + + /** + * Ready to use configuration for north European excel CSV files (columns are separated by ";" instead of ",") + */ + public static final CsvPreference EXCEL_NORTH_EUROPE_PREFERENCE = new CsvPreference.Builder('"', ';', "\n").build(); + + /** + * Ready to use configuration for tab-delimited files. + */ + public static final CsvPreference TAB_PREFERENCE = new CsvPreference.Builder('"', '\t', "\n").build(); + + private final char quoteChar; + + private final int delimiterChar; + + private final String endOfLineSymbols; + + private final boolean surroundingSpacesNeedQuotes; + + /** + * Constructs a new CsvPreference from a Builder. + */ + private CsvPreference(Builder builder) { + this.quoteChar = builder.quoteChar; + this.delimiterChar = builder.delimiterChar; + this.endOfLineSymbols = builder.endOfLineSymbols; + this.surroundingSpacesNeedQuotes = builder.surroundingSpacesNeedQuotes; + } + + /** + * Returns the delimiter character + * + * @return the delimiter character + */ + public int getDelimiterChar() { + return delimiterChar; + } + + /** + * Returns the end of line symbols + * + * @return the end of line symbols + */ + public String getEndOfLineSymbols() { + return endOfLineSymbols; + } + + /** + * Returns the quote character + * + * @return the quote character + */ + public int getQuoteChar() { + return quoteChar; + } + + /** + * Returns the surroundingSpacesNeedQuotes flag. + * + * @return the surroundingSpacesNeedQuotes flag + */ + public boolean isSurroundingSpacesNeedQuotes() { + return surroundingSpacesNeedQuotes; + } + + /** + * Builds immutable CsvPreference instances. The builder pattern allows for additional preferences to be + * added in the future. + */ + public static class Builder { + + private final char quoteChar; + + private final int delimiterChar; + + private final String endOfLineSymbols; + + private boolean surroundingSpacesNeedQuotes = false; + + /** + * Constructs a Builder with all of the values from an existing CsvPreference instance. Useful if you + * want to base your preferences off one of the existing CsvPreference constants. + * + * @param preference + * the existing preference + */ + public Builder(final CsvPreference preference) { + this.quoteChar = preference.quoteChar; + this.delimiterChar = preference.delimiterChar; + this.endOfLineSymbols = preference.endOfLineSymbols; + this.surroundingSpacesNeedQuotes = preference.surroundingSpacesNeedQuotes; + } + + /** + * Constructs a Builder with the mandatory preference values. + * + * @param quoteChar + * matching pairs of this character are used to escape columns containing the delimiter + * @param delimiterChar + * the character separating each column + * @param endOfLineSymbols + * one or more symbols terminating the line, e.g. "\n". Only used for writing. + * @throws IllegalArgumentException + * if quoteChar and delimiterChar are the same character + * @throws NullPointerException + * if endOfLineSymbols is null + */ + public Builder(final char quoteChar, final int delimiterChar, final String endOfLineSymbols) { + if( quoteChar == delimiterChar ) { + throw new IllegalArgumentException(String.format( + "quoteChar and delimiterChar should not be the same character: %c", quoteChar)); + } else if( endOfLineSymbols == null ) { + throw new NullPointerException("endOfLineSymbols should not be null"); + } + this.quoteChar = quoteChar; + this.delimiterChar = delimiterChar; + this.endOfLineSymbols = endOfLineSymbols; + } + + /** + * Flag indicating whether spaces at the beginning or end of a cell should be ignored if they're not surrounded + * by quotes (applicable to both reading and writing CSV). The default is false, as spaces + * "are considered part of a field and should not be ignored" according to RFC 4180. + * + * @param surroundingSpacesNeedQuotes + * flag indicating whether spaces at the beginning or end of a cell should be ignored if they're not + * surrounded by quotes + * @return the updated Builder + */ + public Builder surroundingSpacesNeedQuotes(final boolean surroundingSpacesNeedQuotes) { + this.surroundingSpacesNeedQuotes = surroundingSpacesNeedQuotes; + return this; + } + + /** + * Builds the CsvPreference instance. + * + * @return the immutable CsvPreference instance + */ + public CsvPreference build() { + return new CsvPreference(this); + } + + } + +} diff --git a/super-csv/src/main/java/org/supercsv/prefs/package-info.java b/super-csv/src/main/java/org/supercsv/prefs/package-info.java index aff72185..a90e4351 100644 --- a/super-csv/src/main/java/org/supercsv/prefs/package-info.java +++ b/super-csv/src/main/java/org/supercsv/prefs/package-info.java @@ -1,19 +1,19 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides the configuration classes used when instantiating readers and writers. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides the configuration classes used when instantiating readers and writers. + */ package org.supercsv.prefs; \ No newline at end of file diff --git a/super-csv/src/main/java/org/supercsv/util/BeanInterfaceProxy.java b/super-csv/src/main/java/org/supercsv/util/BeanInterfaceProxy.java index 3036e92f..971ca6ea 100644 --- a/super-csv/src/main/java/org/supercsv/util/BeanInterfaceProxy.java +++ b/super-csv/src/main/java/org/supercsv/util/BeanInterfaceProxy.java @@ -1,108 +1,108 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.supercsv.util.ReflectionUtils.GET_PREFIX; -import static org.supercsv.util.ReflectionUtils.SET_PREFIX; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.HashMap; -import java.util.Map; - -/** - * This is part of the internal implementation of Super CSV. - *

- * This class creates bean instances based on an interface. This allows you, given an interface for a bean (but no - * implementation), to generate a bean implementation on-the-fly. This instance can then be used for fetching and - * storing state. It assumes all get methods starts with "get" and all set methods start with "set" and takes only 1 - * argument. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public final class BeanInterfaceProxy implements InvocationHandler { - - private final Map beanState = new HashMap(); - - // no instantiation - private BeanInterfaceProxy() { - } - - /** - * Creates a proxy object which implements a given bean interface. - * - * @param proxyInterface - * the interface the the proxy will implement - * @return the proxy implementation - * @throws NullPointerException - * if proxyInterface is null - */ - public static T createProxy(final Class proxyInterface) { - if( proxyInterface == null ) { - throw new NullPointerException("proxyInterface should not be null"); - } - return proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(), - new Class[] { proxyInterface }, new BeanInterfaceProxy())); - } - - /** - * {@inheritDoc} - *

- * If a getter method is encountered then this method returns the stored value from the bean state (or null if the - * field has not been set). - *

- * If a setter method is encountered then the bean state is updated with the value of the first argument and the - * value is returned (to allow for method chaining) - * - * @throws IllegalArgumentException - * if the method is not a valid getter/setter - */ - public Object invoke(final Object proxy, final Method method, final Object[] args) { - - final String methodName = method.getName(); - - if( methodName.startsWith(GET_PREFIX) ) { - - if( method.getParameterTypes().length > 0 ) { - throw new IllegalArgumentException(String.format( - "method %s.%s() should have no parameters to be a valid getter", method.getDeclaringClass() - .getName(), methodName)); - } - - // simulate getter by retrieving value from bean state - return beanState.get(methodName.substring(GET_PREFIX.length())); - - } else if( methodName.startsWith(SET_PREFIX) ) { - - if( args == null || args.length != 1 ) { - throw new IllegalArgumentException(String.format( - "method %s.%s() should have exactly one parameter to be a valid setter", method - .getDeclaringClass().getName(), methodName)); - } - - // simulate setter by storing value in bean state - beanState.put(methodName.substring(SET_PREFIX.length()), args[0]); - return proxy; - - } else { - throw new IllegalArgumentException(String.format("method %s.%s() is not a valid getter/setter", method - .getDeclaringClass().getName(), methodName)); - } - - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.supercsv.util.ReflectionUtils.GET_PREFIX; +import static org.supercsv.util.ReflectionUtils.SET_PREFIX; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +/** + * This is part of the internal implementation of Super CSV. + *

+ * This class creates bean instances based on an interface. This allows you, given an interface for a bean (but no + * implementation), to generate a bean implementation on-the-fly. This instance can then be used for fetching and + * storing state. It assumes all get methods starts with "get" and all set methods start with "set" and takes only 1 + * argument. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public final class BeanInterfaceProxy implements InvocationHandler { + + private final Map beanState = new HashMap(); + + // no instantiation + private BeanInterfaceProxy() { + } + + /** + * Creates a proxy object which implements a given bean interface. + * + * @param proxyInterface + * the interface the the proxy will implement + * @return the proxy implementation + * @throws NullPointerException + * if proxyInterface is null + */ + public static T createProxy(final Class proxyInterface) { + if( proxyInterface == null ) { + throw new NullPointerException("proxyInterface should not be null"); + } + return proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(), + new Class[] { proxyInterface }, new BeanInterfaceProxy())); + } + + /** + * {@inheritDoc} + *

+ * If a getter method is encountered then this method returns the stored value from the bean state (or null if the + * field has not been set). + *

+ * If a setter method is encountered then the bean state is updated with the value of the first argument and the + * value is returned (to allow for method chaining) + * + * @throws IllegalArgumentException + * if the method is not a valid getter/setter + */ + public Object invoke(final Object proxy, final Method method, final Object[] args) { + + final String methodName = method.getName(); + + if( methodName.startsWith(GET_PREFIX) ) { + + if( method.getParameterTypes().length > 0 ) { + throw new IllegalArgumentException(String.format( + "method %s.%s() should have no parameters to be a valid getter", method.getDeclaringClass() + .getName(), methodName)); + } + + // simulate getter by retrieving value from bean state + return beanState.get(methodName.substring(GET_PREFIX.length())); + + } else if( methodName.startsWith(SET_PREFIX) ) { + + if( args == null || args.length != 1 ) { + throw new IllegalArgumentException(String.format( + "method %s.%s() should have exactly one parameter to be a valid setter", method + .getDeclaringClass().getName(), methodName)); + } + + // simulate setter by storing value in bean state + beanState.put(methodName.substring(SET_PREFIX.length()), args[0]); + return proxy; + + } else { + throw new IllegalArgumentException(String.format("method %s.%s() is not a valid getter/setter", method + .getDeclaringClass().getName(), methodName)); + } + + } +} diff --git a/super-csv/src/main/java/org/supercsv/util/CsvContext.java b/super-csv/src/main/java/org/supercsv/util/CsvContext.java index 43a0dbd5..ba9b5a0d 100644 --- a/super-csv/src/main/java/org/supercsv/util/CsvContext.java +++ b/super-csv/src/main/java/org/supercsv/util/CsvContext.java @@ -1,179 +1,179 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import java.io.Serializable; -import java.util.List; - -/** - * This object represents the current context of a given CSV file being either read or written to. The lineNumber is the - * actual line number (beginning at 1) of the file being read or written to. The rowNumber (beginning at 1) is the - * number of the CSV row (which will be identical to lineNumber if no rows span multiple lines) - the last rowNumber - * will correspond with the number of CSV records. The columnNumber (beginning at 1) is the number of the CSV column. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class CsvContext implements Serializable { - - private static final long serialVersionUID = 1L; - - /** the line number of the file being read/written */ - private int lineNumber; - - /** the CSV row number (CSV rows can span multiple lines) */ - private int rowNumber; - - /** the CSV column number */ - private int columnNumber; - - /** the row just read in, or to be written */ - private List rowSource; - - /** - * Constructs a new CsvContext. - * - * @param lineNumber - * the current line number - * @param rowNumber - * the current CSV row number - * @param columnNumber - * the current CSV column number - */ - public CsvContext(final int lineNumber, final int rowNumber, final int columnNumber) { - this.lineNumber = lineNumber; - this.rowNumber = rowNumber; - this.columnNumber = columnNumber; - } - - /** - * @return the lineNumber - */ - public int getLineNumber() { - return lineNumber; - } - - /** - * @param lineNumber - * the lineNumber to set - */ - public void setLineNumber(int lineNumber) { - this.lineNumber = lineNumber; - } - - /** - * @return the rowNumber - */ - public int getRowNumber() { - return rowNumber; - } - - /** - * @param rowNumber - * the rowNumber to set - */ - public void setRowNumber(int rowNumber) { - this.rowNumber = rowNumber; - } - - /** - * @return the columnNumber - */ - public int getColumnNumber() { - return columnNumber; - } - - /** - * @param columnNumber - * the columnNumber to set - */ - public void setColumnNumber(int columnNumber) { - this.columnNumber = columnNumber; - } - - /** - * @return the rowSource - */ - public List getRowSource() { - return rowSource; - } - - /** - * @param rowSource - * the rowSource to set - */ - public void setRowSource(List rowSource) { - this.rowSource = rowSource; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return String.format("{lineNo=%d, rowNo=%d, columnNo=%d, rowSource=%s}", lineNumber, rowNumber, columnNumber, - rowSource); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + columnNumber; - result = prime * result + rowNumber; - result = prime * result + lineNumber; - result = prime * result + ((rowSource == null) ? 0 : rowSource.hashCode()); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if( this == obj ) { - return true; - } - if( obj == null ) { - return false; - } - if( getClass() != obj.getClass() ) { - return false; - } - final CsvContext other = (CsvContext) obj; - if( columnNumber != other.columnNumber ) { - return false; - } - if( rowNumber != other.rowNumber ) { - return false; - } - if( lineNumber != other.lineNumber ) { - return false; - } - if( rowSource == null ) { - if( other.rowSource != null ) { - return false; - } - } else if( !rowSource.equals(other.rowSource) ) { - return false; - } - return true; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import java.io.Serializable; +import java.util.List; + +/** + * This object represents the current context of a given CSV file being either read or written to. The lineNumber is the + * actual line number (beginning at 1) of the file being read or written to. The rowNumber (beginning at 1) is the + * number of the CSV row (which will be identical to lineNumber if no rows span multiple lines) - the last rowNumber + * will correspond with the number of CSV records. The columnNumber (beginning at 1) is the number of the CSV column. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class CsvContext implements Serializable { + + private static final long serialVersionUID = 1L; + + /** the line number of the file being read/written */ + private int lineNumber; + + /** the CSV row number (CSV rows can span multiple lines) */ + private int rowNumber; + + /** the CSV column number */ + private int columnNumber; + + /** the row just read in, or to be written */ + private List rowSource; + + /** + * Constructs a new CsvContext. + * + * @param lineNumber + * the current line number + * @param rowNumber + * the current CSV row number + * @param columnNumber + * the current CSV column number + */ + public CsvContext(final int lineNumber, final int rowNumber, final int columnNumber) { + this.lineNumber = lineNumber; + this.rowNumber = rowNumber; + this.columnNumber = columnNumber; + } + + /** + * @return the lineNumber + */ + public int getLineNumber() { + return lineNumber; + } + + /** + * @param lineNumber + * the lineNumber to set + */ + public void setLineNumber(int lineNumber) { + this.lineNumber = lineNumber; + } + + /** + * @return the rowNumber + */ + public int getRowNumber() { + return rowNumber; + } + + /** + * @param rowNumber + * the rowNumber to set + */ + public void setRowNumber(int rowNumber) { + this.rowNumber = rowNumber; + } + + /** + * @return the columnNumber + */ + public int getColumnNumber() { + return columnNumber; + } + + /** + * @param columnNumber + * the columnNumber to set + */ + public void setColumnNumber(int columnNumber) { + this.columnNumber = columnNumber; + } + + /** + * @return the rowSource + */ + public List getRowSource() { + return rowSource; + } + + /** + * @param rowSource + * the rowSource to set + */ + public void setRowSource(List rowSource) { + this.rowSource = rowSource; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("{lineNo=%d, rowNo=%d, columnNo=%d, rowSource=%s}", lineNumber, rowNumber, columnNumber, + rowSource); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + columnNumber; + result = prime * result + rowNumber; + result = prime * result + lineNumber; + result = prime * result + ((rowSource == null) ? 0 : rowSource.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if( this == obj ) { + return true; + } + if( obj == null ) { + return false; + } + if( getClass() != obj.getClass() ) { + return false; + } + final CsvContext other = (CsvContext) obj; + if( columnNumber != other.columnNumber ) { + return false; + } + if( rowNumber != other.rowNumber ) { + return false; + } + if( lineNumber != other.lineNumber ) { + return false; + } + if( rowSource == null ) { + if( other.rowSource != null ) { + return false; + } + } else if( !rowSource.equals(other.rowSource) ) { + return false; + } + return true; + } + +} diff --git a/super-csv/src/main/java/org/supercsv/util/MethodCache.java b/super-csv/src/main/java/org/supercsv/util/MethodCache.java index 18af0eac..7d97f0e6 100644 --- a/super-csv/src/main/java/org/supercsv/util/MethodCache.java +++ b/super-csv/src/main/java/org/supercsv/util/MethodCache.java @@ -1,101 +1,101 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import java.lang.reflect.Method; - -import org.supercsv.exception.SuperCsvReflectionException; - -/** - * This class cache's method lookups. Hence first time it introspects the instance's class, while subsequent method - * lookups are super fast. - */ -public class MethodCache { - - /** - * A cache of setter methods. The three keys are the class the setter is being invoked on, the parameter type of the - * setter, and the variable name. The value is the setter method. - */ - private final ThreeDHashMap, Class, String, Method> setMethodsCache = new ThreeDHashMap, Class, String, Method>(); - - /** - * A cache of getter methods. The two keys are the name of the class the getter is being invoked on, and the - * variable name. The value is the getter method. - */ - private final TwoDHashMap getCache = new TwoDHashMap(); - - /** - * Returns the getter method for field on an object. - * - * @param object - * the object - * @param fieldName - * the field name - * @return the getter associated with the field on the object - * @throws NullPointerException - * if object or fieldName is null - * @throws SuperCsvReflectionException - * if the getter doesn't exist or is not visible - */ - public Method getGetMethod(final Object object, final String fieldName) { - if( object == null ) { - throw new NullPointerException("object should not be null"); - } else if( fieldName == null ) { - throw new NullPointerException("fieldName should not be null"); - } - - Method method = getCache.get(object.getClass().getName(), fieldName); - if( method == null ) { - method = ReflectionUtils.findGetter(object, fieldName); - getCache.set(object.getClass().getName(), fieldName, method); - } - return method; - } - - /** - * Returns the setter method for the field on an object. - * - * @param - * @param object - * the object - * @param fieldName - * the field name - * @param argumentType - * the type to be passed to the setter - * @return the setter method associated with the field on the object - * @throws NullPointerException - * if object, fieldName or fieldType is null - * @throws SuperCsvReflectionException - * if the setter doesn't exist or is not visible - */ - public Method getSetMethod(final Object object, final String fieldName, final Class argumentType) { - if( object == null ) { - throw new NullPointerException("object should not be null"); - } else if( fieldName == null ) { - throw new NullPointerException("fieldName should not be null"); - } else if( argumentType == null ) { - throw new NullPointerException("argumentType should not be null"); - } - - Method method = setMethodsCache.get(object.getClass(), argumentType, fieldName); - if( method == null ) { - method = ReflectionUtils.findSetter(object, fieldName, argumentType); - setMethodsCache.set(object.getClass(), argumentType, fieldName, method); - } - return method; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import java.lang.reflect.Method; + +import org.supercsv.exception.SuperCsvReflectionException; + +/** + * This class cache's method lookups. Hence first time it introspects the instance's class, while subsequent method + * lookups are super fast. + */ +public class MethodCache { + + /** + * A cache of setter methods. The three keys are the class the setter is being invoked on, the parameter type of the + * setter, and the variable name. The value is the setter method. + */ + private final ThreeDHashMap, Class, String, Method> setMethodsCache = new ThreeDHashMap, Class, String, Method>(); + + /** + * A cache of getter methods. The two keys are the name of the class the getter is being invoked on, and the + * variable name. The value is the getter method. + */ + private final TwoDHashMap getCache = new TwoDHashMap(); + + /** + * Returns the getter method for field on an object. + * + * @param object + * the object + * @param fieldName + * the field name + * @return the getter associated with the field on the object + * @throws NullPointerException + * if object or fieldName is null + * @throws SuperCsvReflectionException + * if the getter doesn't exist or is not visible + */ + public Method getGetMethod(final Object object, final String fieldName) { + if( object == null ) { + throw new NullPointerException("object should not be null"); + } else if( fieldName == null ) { + throw new NullPointerException("fieldName should not be null"); + } + + Method method = getCache.get(object.getClass().getName(), fieldName); + if( method == null ) { + method = ReflectionUtils.findGetter(object, fieldName); + getCache.set(object.getClass().getName(), fieldName, method); + } + return method; + } + + /** + * Returns the setter method for the field on an object. + * + * @param + * @param object + * the object + * @param fieldName + * the field name + * @param argumentType + * the type to be passed to the setter + * @return the setter method associated with the field on the object + * @throws NullPointerException + * if object, fieldName or fieldType is null + * @throws SuperCsvReflectionException + * if the setter doesn't exist or is not visible + */ + public Method getSetMethod(final Object object, final String fieldName, final Class argumentType) { + if( object == null ) { + throw new NullPointerException("object should not be null"); + } else if( fieldName == null ) { + throw new NullPointerException("fieldName should not be null"); + } else if( argumentType == null ) { + throw new NullPointerException("argumentType should not be null"); + } + + Method method = setMethodsCache.get(object.getClass(), argumentType, fieldName); + if( method == null ) { + method = ReflectionUtils.findSetter(object, fieldName, argumentType); + setMethodsCache.set(object.getClass(), argumentType, fieldName, method); + } + return method; + } + +} diff --git a/super-csv/src/main/java/org/supercsv/util/ReflectionUtils.java b/super-csv/src/main/java/org/supercsv/util/ReflectionUtils.java index 7de2f06f..5443b67d 100644 --- a/super-csv/src/main/java/org/supercsv/util/ReflectionUtils.java +++ b/super-csv/src/main/java/org/supercsv/util/ReflectionUtils.java @@ -1,200 +1,200 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -import org.supercsv.exception.SuperCsvReflectionException; - -/** - * Provides useful utility methods for reflection. - * - * @author James Bassett - * @since 2.0.0 - */ -public final class ReflectionUtils { - - public static final String SET_PREFIX = "set"; - public static final String GET_PREFIX = "get"; - - /** - * A map of primitives and their associated wrapper classes, to cater for autoboxing. - */ - private static final Map, Class> AUTOBOXING_CONVERTER = new HashMap, Class>(); - static { - AUTOBOXING_CONVERTER.put(long.class, Long.class); - AUTOBOXING_CONVERTER.put(Long.class, long.class); - AUTOBOXING_CONVERTER.put(int.class, Integer.class); - AUTOBOXING_CONVERTER.put(Integer.class, int.class); - AUTOBOXING_CONVERTER.put(char.class, Character.class); - AUTOBOXING_CONVERTER.put(Character.class, char.class); - AUTOBOXING_CONVERTER.put(byte.class, Byte.class); - AUTOBOXING_CONVERTER.put(Byte.class, byte.class); - AUTOBOXING_CONVERTER.put(short.class, Short.class); - AUTOBOXING_CONVERTER.put(Short.class, short.class); - AUTOBOXING_CONVERTER.put(boolean.class, Boolean.class); - AUTOBOXING_CONVERTER.put(Boolean.class, boolean.class); - AUTOBOXING_CONVERTER.put(double.class, Double.class); - AUTOBOXING_CONVERTER.put(Double.class, double.class); - AUTOBOXING_CONVERTER.put(float.class, Float.class); - AUTOBOXING_CONVERTER.put(Float.class, float.class); - } - - // no instantiation - private ReflectionUtils() { - } - - /** - * Returns the getter method associated with the object's field. - * - * @param object - * the object - * @param fieldName - * the name of the field - * @return the getter method - * @throws NullPointerException - * if object or fieldName is null - * @throws SuperCsvReflectionException - * if the getter doesn't exist or is not visible - */ - public static Method findGetter(final Object object, final String fieldName) { - if( object == null ) { - throw new NullPointerException("object should not be null"); - } else if( fieldName == null ) { - throw new NullPointerException("fieldName should not be null"); - } - - String getterName = getMethodNameForField(GET_PREFIX, fieldName); - Class clazz = object.getClass(); - try { - return clazz.getMethod(getterName); - } - catch(final Exception e) { - throw new SuperCsvReflectionException( - String.format( - "unable to find method %s() in class %s - check that the corresponding nameMapping element matches the field name in the bean", - getterName, clazz.getName()), e); - } - - } - - /** - * Returns the setter method associated with the object's field. - *

- * This method handles any autoboxing/unboxing of the argument passed to the setter (e.g. if the setter type is a - * primitive {@code int} but the argument passed to the setter is an {@code Integer}) by looking for a setter with - * the same type, and failing that checking for a setter with the corresponding primitive/wrapper type. - *

- * It also allows for an argument type that is a subclass or implementation of the setter type (when the setter type - * is an {@code Object} or {@code interface} respectively). - * - * @param object - * the object - * @param fieldName - * the name of the field - * @param argumentType - * the type to be passed to the setter - * @return the setter method - * @throws NullPointerException - * if object, fieldName or fieldType is null - * @throws SuperCsvReflectionException - * if the setter doesn't exist or is not visible - */ - public static Method findSetter(final Object object, final String fieldName, final Class argumentType) { - if( object == null ) { - throw new NullPointerException("object should not be null"); - } else if( fieldName == null ) { - throw new NullPointerException("fieldName should not be null"); - } else if( argumentType == null ) { - throw new NullPointerException("argumentType should not be null"); - } - - final String setterName = getMethodNameForField(SET_PREFIX, fieldName); - final Class clazz = object.getClass(); - - // find a setter compatible with the supplied argument type - Method setter = findSetterWithCompatibleParamType(clazz, setterName, argumentType); - - // if that failed, try the corresponding primitive/wrapper if it's a type that can be autoboxed/unboxed - if( setter == null && AUTOBOXING_CONVERTER.containsKey(argumentType) ) { - setter = findSetterWithCompatibleParamType(clazz, setterName, AUTOBOXING_CONVERTER.get(argumentType)); - } - - if( setter == null ) { - throw new SuperCsvReflectionException( - String - .format( - "unable to find method %s(%s) in class %s - check that the corresponding nameMapping element matches the field name in the bean, " - + "and the cell processor returns a type compatible with the field", setterName, - argumentType.getName(), clazz.getName())); - } - - return setter; - } - - /** - * Helper method for findSetter() that returns the setter method of the supplied name, whose parameter type is - * compatible with the supplied argument type (will allow an object of that type to be used when invoking the - * setter), or returns null if no match is found. Preference is given to setters whose parameter type is an - * exact match, but if there is none, then the first compatible method found is returned. - * - * @param clazz - * the class containing the setter - * @param setterName - * the name of the setter - * @param argumentType - * the type to be passed to the setter - * @return the setter method, or null if none is found - */ - private static Method findSetterWithCompatibleParamType(final Class clazz, final String setterName, - final Class argumentType) { - - Method compatibleSetter = null; - for( final Method method : clazz.getMethods() ) { - - if( !setterName.equals(method.getName()) || method.getParameterTypes().length != 1 ) { - continue; // setter must have correct name and only 1 parameter - } - - final Class parameterType = method.getParameterTypes()[0]; - if( parameterType.equals(argumentType) ) { - compatibleSetter = method; - break; // exact match - - } else if( parameterType.isAssignableFrom(argumentType) ) { - compatibleSetter = method; // potential match, but keep looking for exact match - } - - } - - return compatibleSetter; - } - - /** - * Gets the camelcase getter/setter method name for a field. - * - * @param prefix - * the method prefix - * @param fieldName - * the field name - * @return the method name - */ - private static String getMethodNameForField(final String prefix, final String fieldName) { - return prefix + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.supercsv.exception.SuperCsvReflectionException; + +/** + * Provides useful utility methods for reflection. + * + * @author James Bassett + * @since 2.0.0 + */ +public final class ReflectionUtils { + + public static final String SET_PREFIX = "set"; + public static final String GET_PREFIX = "get"; + + /** + * A map of primitives and their associated wrapper classes, to cater for autoboxing. + */ + private static final Map, Class> AUTOBOXING_CONVERTER = new HashMap, Class>(); + static { + AUTOBOXING_CONVERTER.put(long.class, Long.class); + AUTOBOXING_CONVERTER.put(Long.class, long.class); + AUTOBOXING_CONVERTER.put(int.class, Integer.class); + AUTOBOXING_CONVERTER.put(Integer.class, int.class); + AUTOBOXING_CONVERTER.put(char.class, Character.class); + AUTOBOXING_CONVERTER.put(Character.class, char.class); + AUTOBOXING_CONVERTER.put(byte.class, Byte.class); + AUTOBOXING_CONVERTER.put(Byte.class, byte.class); + AUTOBOXING_CONVERTER.put(short.class, Short.class); + AUTOBOXING_CONVERTER.put(Short.class, short.class); + AUTOBOXING_CONVERTER.put(boolean.class, Boolean.class); + AUTOBOXING_CONVERTER.put(Boolean.class, boolean.class); + AUTOBOXING_CONVERTER.put(double.class, Double.class); + AUTOBOXING_CONVERTER.put(Double.class, double.class); + AUTOBOXING_CONVERTER.put(float.class, Float.class); + AUTOBOXING_CONVERTER.put(Float.class, float.class); + } + + // no instantiation + private ReflectionUtils() { + } + + /** + * Returns the getter method associated with the object's field. + * + * @param object + * the object + * @param fieldName + * the name of the field + * @return the getter method + * @throws NullPointerException + * if object or fieldName is null + * @throws SuperCsvReflectionException + * if the getter doesn't exist or is not visible + */ + public static Method findGetter(final Object object, final String fieldName) { + if( object == null ) { + throw new NullPointerException("object should not be null"); + } else if( fieldName == null ) { + throw new NullPointerException("fieldName should not be null"); + } + + String getterName = getMethodNameForField(GET_PREFIX, fieldName); + Class clazz = object.getClass(); + try { + return clazz.getMethod(getterName); + } + catch(final Exception e) { + throw new SuperCsvReflectionException( + String.format( + "unable to find method %s() in class %s - check that the corresponding nameMapping element matches the field name in the bean", + getterName, clazz.getName()), e); + } + + } + + /** + * Returns the setter method associated with the object's field. + *

+ * This method handles any autoboxing/unboxing of the argument passed to the setter (e.g. if the setter type is a + * primitive {@code int} but the argument passed to the setter is an {@code Integer}) by looking for a setter with + * the same type, and failing that checking for a setter with the corresponding primitive/wrapper type. + *

+ * It also allows for an argument type that is a subclass or implementation of the setter type (when the setter type + * is an {@code Object} or {@code interface} respectively). + * + * @param object + * the object + * @param fieldName + * the name of the field + * @param argumentType + * the type to be passed to the setter + * @return the setter method + * @throws NullPointerException + * if object, fieldName or fieldType is null + * @throws SuperCsvReflectionException + * if the setter doesn't exist or is not visible + */ + public static Method findSetter(final Object object, final String fieldName, final Class argumentType) { + if( object == null ) { + throw new NullPointerException("object should not be null"); + } else if( fieldName == null ) { + throw new NullPointerException("fieldName should not be null"); + } else if( argumentType == null ) { + throw new NullPointerException("argumentType should not be null"); + } + + final String setterName = getMethodNameForField(SET_PREFIX, fieldName); + final Class clazz = object.getClass(); + + // find a setter compatible with the supplied argument type + Method setter = findSetterWithCompatibleParamType(clazz, setterName, argumentType); + + // if that failed, try the corresponding primitive/wrapper if it's a type that can be autoboxed/unboxed + if( setter == null && AUTOBOXING_CONVERTER.containsKey(argumentType) ) { + setter = findSetterWithCompatibleParamType(clazz, setterName, AUTOBOXING_CONVERTER.get(argumentType)); + } + + if( setter == null ) { + throw new SuperCsvReflectionException( + String + .format( + "unable to find method %s(%s) in class %s - check that the corresponding nameMapping element matches the field name in the bean, " + + "and the cell processor returns a type compatible with the field", setterName, + argumentType.getName(), clazz.getName())); + } + + return setter; + } + + /** + * Helper method for findSetter() that returns the setter method of the supplied name, whose parameter type is + * compatible with the supplied argument type (will allow an object of that type to be used when invoking the + * setter), or returns null if no match is found. Preference is given to setters whose parameter type is an + * exact match, but if there is none, then the first compatible method found is returned. + * + * @param clazz + * the class containing the setter + * @param setterName + * the name of the setter + * @param argumentType + * the type to be passed to the setter + * @return the setter method, or null if none is found + */ + private static Method findSetterWithCompatibleParamType(final Class clazz, final String setterName, + final Class argumentType) { + + Method compatibleSetter = null; + for( final Method method : clazz.getMethods() ) { + + if( !setterName.equals(method.getName()) || method.getParameterTypes().length != 1 ) { + continue; // setter must have correct name and only 1 parameter + } + + final Class parameterType = method.getParameterTypes()[0]; + if( parameterType.equals(argumentType) ) { + compatibleSetter = method; + break; // exact match + + } else if( parameterType.isAssignableFrom(argumentType) ) { + compatibleSetter = method; // potential match, but keep looking for exact match + } + + } + + return compatibleSetter; + } + + /** + * Gets the camelcase getter/setter method name for a field. + * + * @param prefix + * the method prefix + * @param fieldName + * the field name + * @return the method name + */ + private static String getMethodNameForField(final String prefix, final String fieldName) { + return prefix + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); + } +} diff --git a/super-csv/src/main/java/org/supercsv/util/ThreeDHashMap.java b/super-csv/src/main/java/org/supercsv/util/ThreeDHashMap.java index 4e6d40e1..bd1b8ae9 100644 --- a/super-csv/src/main/java/org/supercsv/util/ThreeDHashMap.java +++ b/super-csv/src/main/java/org/supercsv/util/ThreeDHashMap.java @@ -1,234 +1,234 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import java.util.HashMap; -import java.util.Set; - -/** - * A 3-dimensional HashMap is a HashMap that enables you to refer to values via three keys rather than one. The - * underlying implementation is simply a HashMap containing HashMap containing a HashMap, each of which maps to values. - * - * @author Kasper B. Graversen - * @since 2.0.0 (migrated from Spiffy 0.5) - */ -public class ThreeDHashMap { - - private final HashMap>> map = new HashMap>>(); - - /** - * Existence check of a value (or null) mapped to the keys. - * - * @param firstKey - * first key - * @param secondKey - * second key - * @return true when an element (or null) has been stored with the keys - */ - public boolean containsKey(final K1 firstKey, final K2 secondKey) { - // existence check on inner map - final HashMap> innerMap1 = map.get(firstKey); - if( innerMap1 == null ) { - return false; - } - - return innerMap1.containsKey(secondKey); - } - - /** - * Existence check of a value (or null) mapped to the keys. - * - * @param firstKey - * first key - * @param secondKey - * second key - * @param thirdKey - * third key - * @return true when an element (or null) has been stored with the keys - */ - public boolean containsKey(final K1 firstKey, final K2 secondKey, final K3 thirdKey) { - // existence check on inner map - final HashMap> innerMap1 = map.get(firstKey); - if( innerMap1 == null ) { - return false; - } - - // existence check on inner map1 - final HashMap innerMap2 = innerMap1.get(secondKey); - if( innerMap2 == null ) { - return false; - } - return innerMap2.containsKey(thirdKey); - } - - /** - * Fetch the outermost Hashmap. - * - * @param firstKey - * first key - * @return the the innermost hashmap - */ - public HashMap> get(final K1 firstKey) { - return map.get(firstKey); - } - - /** - * Fetch the outermost Hashmap as a TwoDHashMap. - * - * @param firstKey - * first key - * @return the the innermost hashmap - */ - public TwoDHashMap getAs2d(final K1 firstKey) { - final HashMap> innerMap1 = map.get(firstKey); - if( innerMap1 != null ) { - return new TwoDHashMap(innerMap1); - } else { - return new TwoDHashMap(); - } - - } - - /** - * Fetch the innermost Hashmap. - * - * @param firstKey - * first key - * @param secondKey - * second key - * @return the the innermost hashmap - */ - public HashMap get(final K1 firstKey, final K2 secondKey) { - // existence check on inner map - final HashMap> innerMap1 = map.get(firstKey); - if( innerMap1 == null ) { - return null; - } - - return innerMap1.get(secondKey); - } - - /** - * Fetch a value from the Hashmap. - * - * @param firstKey - * first key - * @param secondKey - * second key - * @param thirdKey - * third key - * @return the element or null. - */ - public V get(final K1 firstKey, final K2 secondKey, final K3 thirdKey) { - // existence check on inner map - final HashMap> innerMap1 = map.get(firstKey); - if( innerMap1 == null ) { - return null; - } - - // existence check on inner map1 - final HashMap innerMap2 = innerMap1.get(secondKey); - if( innerMap2 == null ) { - return null; - } - return innerMap2.get(thirdKey); - } - - /** - * Insert a value - * - * @param firstKey - * first key - * @param secondKey - * second key - * @param thirdKey - * third key - * @param value - * the value to be inserted. null may be inserted as well. - * @return null or the value the insert is replacing. - */ - public Object set(final K1 firstKey, final K2 secondKey, final K3 thirdKey, final V value) { - // existence check on inner map1 - HashMap> innerMap1 = map.get(firstKey); - - if( innerMap1 == null ) { - // no inner map, create it - innerMap1 = new HashMap>(); - map.put(firstKey, innerMap1); - } - - // existence check on inner map1 - HashMap innerMap2 = innerMap1.get(secondKey); - if( innerMap2 == null ) { - // no inner map, create it - innerMap2 = new HashMap(); - innerMap1.put(secondKey, innerMap2); - } - - return innerMap2.put(thirdKey, value); - } - - /** - * Returns the number of key-value mappings in this map for the first key. - * - * @return Returns the number of key-value mappings in this map for the first key. - */ - public int size() { - return map.size(); - } - - /** - * Returns the number of key-value mappings in this map for the second key. - * - * @return Returns the number of key-value mappings in this map for the second key. - */ - public int size(final K1 firstKey) { - // existence check on inner map - final HashMap> innerMap = map.get(firstKey); - if( innerMap == null ) { - return 0; - } - return innerMap.size(); - } - - /** - * Returns the number of key-value mappings in this map for the third key. - * - * @return Returns the number of key-value mappings in this map for the third key. - */ - public int size(final K1 firstKey, final K2 secondKey) { - // existence check on inner map - final HashMap> innerMap1 = map.get(firstKey); - if( innerMap1 == null ) { - return 0; - } - - // existence check on inner map1 - final HashMap innerMap2 = innerMap1.get(secondKey); - if( innerMap2 == null ) { - return 0; - } - return innerMap2.size(); - } - - /** - * Returns a set of the keys of the outermost map. - */ - public Set keySet() { - return map.keySet(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import java.util.HashMap; +import java.util.Set; + +/** + * A 3-dimensional HashMap is a HashMap that enables you to refer to values via three keys rather than one. The + * underlying implementation is simply a HashMap containing HashMap containing a HashMap, each of which maps to values. + * + * @author Kasper B. Graversen + * @since 2.0.0 (migrated from Spiffy 0.5) + */ +public class ThreeDHashMap { + + private final HashMap>> map = new HashMap>>(); + + /** + * Existence check of a value (or null) mapped to the keys. + * + * @param firstKey + * first key + * @param secondKey + * second key + * @return true when an element (or null) has been stored with the keys + */ + public boolean containsKey(final K1 firstKey, final K2 secondKey) { + // existence check on inner map + final HashMap> innerMap1 = map.get(firstKey); + if( innerMap1 == null ) { + return false; + } + + return innerMap1.containsKey(secondKey); + } + + /** + * Existence check of a value (or null) mapped to the keys. + * + * @param firstKey + * first key + * @param secondKey + * second key + * @param thirdKey + * third key + * @return true when an element (or null) has been stored with the keys + */ + public boolean containsKey(final K1 firstKey, final K2 secondKey, final K3 thirdKey) { + // existence check on inner map + final HashMap> innerMap1 = map.get(firstKey); + if( innerMap1 == null ) { + return false; + } + + // existence check on inner map1 + final HashMap innerMap2 = innerMap1.get(secondKey); + if( innerMap2 == null ) { + return false; + } + return innerMap2.containsKey(thirdKey); + } + + /** + * Fetch the outermost Hashmap. + * + * @param firstKey + * first key + * @return the the innermost hashmap + */ + public HashMap> get(final K1 firstKey) { + return map.get(firstKey); + } + + /** + * Fetch the outermost Hashmap as a TwoDHashMap. + * + * @param firstKey + * first key + * @return the the innermost hashmap + */ + public TwoDHashMap getAs2d(final K1 firstKey) { + final HashMap> innerMap1 = map.get(firstKey); + if( innerMap1 != null ) { + return new TwoDHashMap(innerMap1); + } else { + return new TwoDHashMap(); + } + + } + + /** + * Fetch the innermost Hashmap. + * + * @param firstKey + * first key + * @param secondKey + * second key + * @return the the innermost hashmap + */ + public HashMap get(final K1 firstKey, final K2 secondKey) { + // existence check on inner map + final HashMap> innerMap1 = map.get(firstKey); + if( innerMap1 == null ) { + return null; + } + + return innerMap1.get(secondKey); + } + + /** + * Fetch a value from the Hashmap. + * + * @param firstKey + * first key + * @param secondKey + * second key + * @param thirdKey + * third key + * @return the element or null. + */ + public V get(final K1 firstKey, final K2 secondKey, final K3 thirdKey) { + // existence check on inner map + final HashMap> innerMap1 = map.get(firstKey); + if( innerMap1 == null ) { + return null; + } + + // existence check on inner map1 + final HashMap innerMap2 = innerMap1.get(secondKey); + if( innerMap2 == null ) { + return null; + } + return innerMap2.get(thirdKey); + } + + /** + * Insert a value + * + * @param firstKey + * first key + * @param secondKey + * second key + * @param thirdKey + * third key + * @param value + * the value to be inserted. null may be inserted as well. + * @return null or the value the insert is replacing. + */ + public Object set(final K1 firstKey, final K2 secondKey, final K3 thirdKey, final V value) { + // existence check on inner map1 + HashMap> innerMap1 = map.get(firstKey); + + if( innerMap1 == null ) { + // no inner map, create it + innerMap1 = new HashMap>(); + map.put(firstKey, innerMap1); + } + + // existence check on inner map1 + HashMap innerMap2 = innerMap1.get(secondKey); + if( innerMap2 == null ) { + // no inner map, create it + innerMap2 = new HashMap(); + innerMap1.put(secondKey, innerMap2); + } + + return innerMap2.put(thirdKey, value); + } + + /** + * Returns the number of key-value mappings in this map for the first key. + * + * @return Returns the number of key-value mappings in this map for the first key. + */ + public int size() { + return map.size(); + } + + /** + * Returns the number of key-value mappings in this map for the second key. + * + * @return Returns the number of key-value mappings in this map for the second key. + */ + public int size(final K1 firstKey) { + // existence check on inner map + final HashMap> innerMap = map.get(firstKey); + if( innerMap == null ) { + return 0; + } + return innerMap.size(); + } + + /** + * Returns the number of key-value mappings in this map for the third key. + * + * @return Returns the number of key-value mappings in this map for the third key. + */ + public int size(final K1 firstKey, final K2 secondKey) { + // existence check on inner map + final HashMap> innerMap1 = map.get(firstKey); + if( innerMap1 == null ) { + return 0; + } + + // existence check on inner map1 + final HashMap innerMap2 = innerMap1.get(secondKey); + if( innerMap2 == null ) { + return 0; + } + return innerMap2.size(); + } + + /** + * Returns a set of the keys of the outermost map. + */ + public Set keySet() { + return map.keySet(); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/util/TwoDHashMap.java b/super-csv/src/main/java/org/supercsv/util/TwoDHashMap.java index 5b45932e..a83a771c 100644 --- a/super-csv/src/main/java/org/supercsv/util/TwoDHashMap.java +++ b/super-csv/src/main/java/org/supercsv/util/TwoDHashMap.java @@ -1,145 +1,145 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import java.util.HashMap; -import java.util.Set; - -/** - * A two-dimensional hashmap, is a HashMap that enables you to refer to values via two keys rather than one. The - * underlying implementation is simply a HashMap containing HashMap, each of which maps to values. - * - * @see java.util.HashMap - * @author Kasper B. Graversen - * @since 2.0.0 (migrated from Spiffy 0.5) - */ -public class TwoDHashMap { - - private final HashMap> map; - - /** - * Constructs a new TwoDHashMap. - */ - public TwoDHashMap() { - map = new HashMap>(); - } - - /** - * Constructs a new TwoDHashMap using the supplied map. - * - * @param map - * the map - * @throws NullPointerException - * if map is null - */ - public TwoDHashMap(final HashMap> map) { - if( map == null ) { - throw new NullPointerException("map should not be null"); - } - this.map = map; - } - - /** - * Existence check of a value (or null) mapped to the keys. - * - * @param firstKey - * first key - * @param secondKey - * second key - * @return true when an element (or null) has been stored with the keys - */ - public boolean containsKey(final K1 firstKey, final K2 secondKey) { - // existence check on inner map - final HashMap innerMap = map.get(firstKey); - if( innerMap == null ) { - return false; - } - return innerMap.containsKey(secondKey); - } - - /** - * Fetch a value from the Hashmap . - * - * @param firstKey - * first key - * @param secondKey - * second key - * @return the element or null. - */ - public V get(final K1 firstKey, final K2 secondKey) { - // existence check on inner map - final HashMap innerMap = map.get(firstKey); - if( innerMap == null ) { - return null; - } - return innerMap.get(secondKey); - } - - /** - * Insert a value - * - * @param firstKey - * first key - * @param secondKey - * second key - * @param value - * the value to be inserted. null may be inserted as well. - * @return null or the value the insert is replacing. - */ - public Object set(final K1 firstKey, final K2 secondKey, final V value) { - // existence check on inner map - HashMap innerMap = map.get(firstKey); - - if( innerMap == null ) { - // no inner map, create it - innerMap = new HashMap(); - map.put(firstKey, innerMap); - } - - return innerMap.put(secondKey, value); - } - - /** - * Returns the number of key-value mappings in this map for the first key. - * - * @return Returns the number of key-value mappings in this map for the first key. - */ - public int size() { - return map.size(); - } - - /** - * Returns the number of key-value mappings in this map for the second key. - * - * @return Returns the number of key-value mappings in this map for the second key. - */ - public int size(final K1 firstKey) { - // existence check on inner map - final HashMap innerMap = map.get(firstKey); - if( innerMap == null ) { - return 0; - } - return innerMap.size(); - } - - /** - * Returns a set of the keys of the outermost map. - */ - public Set keySet() { - return map.keySet(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import java.util.HashMap; +import java.util.Set; + +/** + * A two-dimensional hashmap, is a HashMap that enables you to refer to values via two keys rather than one. The + * underlying implementation is simply a HashMap containing HashMap, each of which maps to values. + * + * @see java.util.HashMap + * @author Kasper B. Graversen + * @since 2.0.0 (migrated from Spiffy 0.5) + */ +public class TwoDHashMap { + + private final HashMap> map; + + /** + * Constructs a new TwoDHashMap. + */ + public TwoDHashMap() { + map = new HashMap>(); + } + + /** + * Constructs a new TwoDHashMap using the supplied map. + * + * @param map + * the map + * @throws NullPointerException + * if map is null + */ + public TwoDHashMap(final HashMap> map) { + if( map == null ) { + throw new NullPointerException("map should not be null"); + } + this.map = map; + } + + /** + * Existence check of a value (or null) mapped to the keys. + * + * @param firstKey + * first key + * @param secondKey + * second key + * @return true when an element (or null) has been stored with the keys + */ + public boolean containsKey(final K1 firstKey, final K2 secondKey) { + // existence check on inner map + final HashMap innerMap = map.get(firstKey); + if( innerMap == null ) { + return false; + } + return innerMap.containsKey(secondKey); + } + + /** + * Fetch a value from the Hashmap . + * + * @param firstKey + * first key + * @param secondKey + * second key + * @return the element or null. + */ + public V get(final K1 firstKey, final K2 secondKey) { + // existence check on inner map + final HashMap innerMap = map.get(firstKey); + if( innerMap == null ) { + return null; + } + return innerMap.get(secondKey); + } + + /** + * Insert a value + * + * @param firstKey + * first key + * @param secondKey + * second key + * @param value + * the value to be inserted. null may be inserted as well. + * @return null or the value the insert is replacing. + */ + public Object set(final K1 firstKey, final K2 secondKey, final V value) { + // existence check on inner map + HashMap innerMap = map.get(firstKey); + + if( innerMap == null ) { + // no inner map, create it + innerMap = new HashMap(); + map.put(firstKey, innerMap); + } + + return innerMap.put(secondKey, value); + } + + /** + * Returns the number of key-value mappings in this map for the first key. + * + * @return Returns the number of key-value mappings in this map for the first key. + */ + public int size() { + return map.size(); + } + + /** + * Returns the number of key-value mappings in this map for the second key. + * + * @return Returns the number of key-value mappings in this map for the second key. + */ + public int size(final K1 firstKey) { + // existence check on inner map + final HashMap innerMap = map.get(firstKey); + if( innerMap == null ) { + return 0; + } + return innerMap.size(); + } + + /** + * Returns a set of the keys of the outermost map. + */ + public Set keySet() { + return map.keySet(); + } + +} diff --git a/super-csv/src/main/java/org/supercsv/util/Util.java b/super-csv/src/main/java/org/supercsv/util/Util.java index 772bd5af..b1d74f1f 100644 --- a/super-csv/src/main/java/org/supercsv/util/Util.java +++ b/super-csv/src/main/java/org/supercsv/util/Util.java @@ -1,238 +1,238 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.exception.SuperCsvException; - -/** - * Useful utility methods. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public final class Util { - - // no instantiation - private Util() { - } - - /** - * Processes each element in the source List (using the corresponding processor chain in the processors array) and - * adds it to the destination List. A null CellProcessor in the array indicates that no processing is - * required and the element should be added as-is. - * - * @param destination - * the List to add the processed elements to (which is cleared before it's populated) - * @param source - * the List of source elements to be processed - * @param processors - * the array of CellProcessors used to process each element. The number of elements in this array must - * match the size of the source List. A null CellProcessor in this array indicates that no - * processing is required and the element should be added as-is. - * @param lineNo - * the current line number - * @param rowNo - * the current row number - * @throws NullPointerException - * if destination, source or processors is null - * @throws SuperCsvConstraintViolationException - * if a CellProcessor constraint failed - * @throws SuperCsvException - * if source.size() != processors.length, or CellProcessor execution failed - */ - public static void executeCellProcessors(final List destination, final List source, - final CellProcessor[] processors, final int lineNo, final int rowNo) { - - if( destination == null ) { - throw new NullPointerException("destination should not be null"); - } else if( source == null ) { - throw new NullPointerException("source should not be null"); - } else if( processors == null ) { - throw new NullPointerException("processors should not be null"); - } - - // the context used when cell processors report exceptions - final CsvContext context = new CsvContext(lineNo, rowNo, 1); - context.setRowSource(new ArrayList(source)); - - if( source.size() != processors.length ) { - throw new SuperCsvException(String.format( - "The number of columns to be processed (%d) must match the number of CellProcessors (%d): check that the number" - + " of CellProcessors you have defined matches the expected number of columns being read/written", - source.size(), processors.length), context); - } - - destination.clear(); - - for( int i = 0; i < source.size(); i++ ) { - - context.setColumnNumber(i + 1); // update context (columns start at 1) - - if( processors[i] == null ) { - destination.add(source.get(i)); // no processing required - } else { - destination.add(processors[i].execute(source.get(i), context)); // execute the processor chain - } - } - } - - /** - * Converts a List to a Map using the elements of the nameMapping array as the keys of the Map. - * - * @param destinationMap - * the destination Map (which is cleared before it's populated) - * @param nameMapping - * the keys of the Map (corresponding with the elements in the sourceList). Cannot contain duplicates. - * @param sourceList - * the List to convert - * @throws NullPointerException - * if destinationMap, nameMapping or sourceList are null - * @throws SuperCsvException - * if nameMapping and sourceList are not the same size - */ - public static void filterListToMap(final Map destinationMap, final String[] nameMapping, - final List sourceList) { - if( destinationMap == null ) { - throw new NullPointerException("destinationMap should not be null"); - } else if( nameMapping == null ) { - throw new NullPointerException("nameMapping should not be null"); - } else if( sourceList == null ) { - throw new NullPointerException("sourceList should not be null"); - } else if( nameMapping.length != sourceList.size() ) { - throw new SuperCsvException( - String - .format( - "the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)", - nameMapping.length, sourceList.size())); - } - - destinationMap.clear(); - - for( int i = 0; i < nameMapping.length; i++ ) { - final String key = nameMapping[i]; - - if( key == null ) { - continue; // null's in the name mapping means skip column - } - - // no duplicates allowed - if( destinationMap.containsKey(key) ) { - throw new SuperCsvException(String.format("duplicate nameMapping '%s' at index %d", key, i)); - } - - destinationMap.put(key, sourceList.get(i)); - } - } - - /** - * Returns a List of all of the values in the Map whose key matches an entry in the nameMapping array. - * - * @param map - * the map - * @param nameMapping - * the keys of the Map values to add to the List - * @return a List of all of the values in the Map whose key matches an entry in the nameMapping array - * @throws NullPointerException - * if map or nameMapping is null - */ - public static List filterMapToList(final Map map, final String[] nameMapping) { - if( map == null ) { - throw new NullPointerException("map should not be null"); - } else if( nameMapping == null ) { - throw new NullPointerException("nameMapping should not be null"); - } - - final List result = new ArrayList(nameMapping.length); - for( final String key : nameMapping ) { - result.add(map.get(key)); - } - return result; - } - - /** - * Converts a Map to an array of objects, adding only those entries whose key is in the nameMapping array. - * - * @param values - * the Map of values to convert - * @param nameMapping - * the keys to extract from the Map (elements in the target array will be added in this order) - * @return the array of Objects - * @throws NullPointerException - * if values or nameMapping is null - */ - public static Object[] filterMapToObjectArray(final Map values, final String[] nameMapping) { - - if( values == null ) { - throw new NullPointerException("values should not be null"); - } else if( nameMapping == null ) { - throw new NullPointerException("nameMapping should not be null"); - } - - final Object[] targetArray = new Object[nameMapping.length]; - int i = 0; - for( final String name : nameMapping ) { - targetArray[i++] = values.get(name); - } - return targetArray; - } - - /** - * Converts an Object array to a String array (null-safe), by calling toString() on each element. - * - * @param objectArray - * the Object array - * @return the String array, or null if objectArray is null - */ - public static String[] objectArrayToStringArray(final Object[] objectArray) { - if( objectArray == null ) { - return null; - } - - final String[] stringArray = new String[objectArray.length]; - for( int i = 0; i < objectArray.length; i++ ) { - stringArray[i] = objectArray[i] != null ? objectArray[i].toString() : null; - } - - return stringArray; - } - - /** - * Converts an List objectList) { - if( objectList == null ) { - return null; - } - - final String[] stringArray = new String[objectList.size()]; - for( int i = 0; i < objectList.size(); i++ ) { - stringArray[i] = objectList.get(i) != null ? objectList.get(i).toString() : null; - } - - return stringArray; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.exception.SuperCsvException; + +/** + * Useful utility methods. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public final class Util { + + // no instantiation + private Util() { + } + + /** + * Processes each element in the source List (using the corresponding processor chain in the processors array) and + * adds it to the destination List. A null CellProcessor in the array indicates that no processing is + * required and the element should be added as-is. + * + * @param destination + * the List to add the processed elements to (which is cleared before it's populated) + * @param source + * the List of source elements to be processed + * @param processors + * the array of CellProcessors used to process each element. The number of elements in this array must + * match the size of the source List. A null CellProcessor in this array indicates that no + * processing is required and the element should be added as-is. + * @param lineNo + * the current line number + * @param rowNo + * the current row number + * @throws NullPointerException + * if destination, source or processors is null + * @throws SuperCsvConstraintViolationException + * if a CellProcessor constraint failed + * @throws SuperCsvException + * if source.size() != processors.length, or CellProcessor execution failed + */ + public static void executeCellProcessors(final List destination, final List source, + final CellProcessor[] processors, final int lineNo, final int rowNo) { + + if( destination == null ) { + throw new NullPointerException("destination should not be null"); + } else if( source == null ) { + throw new NullPointerException("source should not be null"); + } else if( processors == null ) { + throw new NullPointerException("processors should not be null"); + } + + // the context used when cell processors report exceptions + final CsvContext context = new CsvContext(lineNo, rowNo, 1); + context.setRowSource(new ArrayList(source)); + + if( source.size() != processors.length ) { + throw new SuperCsvException(String.format( + "The number of columns to be processed (%d) must match the number of CellProcessors (%d): check that the number" + + " of CellProcessors you have defined matches the expected number of columns being read/written", + source.size(), processors.length), context); + } + + destination.clear(); + + for( int i = 0; i < source.size(); i++ ) { + + context.setColumnNumber(i + 1); // update context (columns start at 1) + + if( processors[i] == null ) { + destination.add(source.get(i)); // no processing required + } else { + destination.add(processors[i].execute(source.get(i), context)); // execute the processor chain + } + } + } + + /** + * Converts a List to a Map using the elements of the nameMapping array as the keys of the Map. + * + * @param destinationMap + * the destination Map (which is cleared before it's populated) + * @param nameMapping + * the keys of the Map (corresponding with the elements in the sourceList). Cannot contain duplicates. + * @param sourceList + * the List to convert + * @throws NullPointerException + * if destinationMap, nameMapping or sourceList are null + * @throws SuperCsvException + * if nameMapping and sourceList are not the same size + */ + public static void filterListToMap(final Map destinationMap, final String[] nameMapping, + final List sourceList) { + if( destinationMap == null ) { + throw new NullPointerException("destinationMap should not be null"); + } else if( nameMapping == null ) { + throw new NullPointerException("nameMapping should not be null"); + } else if( sourceList == null ) { + throw new NullPointerException("sourceList should not be null"); + } else if( nameMapping.length != sourceList.size() ) { + throw new SuperCsvException( + String + .format( + "the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)", + nameMapping.length, sourceList.size())); + } + + destinationMap.clear(); + + for( int i = 0; i < nameMapping.length; i++ ) { + final String key = nameMapping[i]; + + if( key == null ) { + continue; // null's in the name mapping means skip column + } + + // no duplicates allowed + if( destinationMap.containsKey(key) ) { + throw new SuperCsvException(String.format("duplicate nameMapping '%s' at index %d", key, i)); + } + + destinationMap.put(key, sourceList.get(i)); + } + } + + /** + * Returns a List of all of the values in the Map whose key matches an entry in the nameMapping array. + * + * @param map + * the map + * @param nameMapping + * the keys of the Map values to add to the List + * @return a List of all of the values in the Map whose key matches an entry in the nameMapping array + * @throws NullPointerException + * if map or nameMapping is null + */ + public static List filterMapToList(final Map map, final String[] nameMapping) { + if( map == null ) { + throw new NullPointerException("map should not be null"); + } else if( nameMapping == null ) { + throw new NullPointerException("nameMapping should not be null"); + } + + final List result = new ArrayList(nameMapping.length); + for( final String key : nameMapping ) { + result.add(map.get(key)); + } + return result; + } + + /** + * Converts a Map to an array of objects, adding only those entries whose key is in the nameMapping array. + * + * @param values + * the Map of values to convert + * @param nameMapping + * the keys to extract from the Map (elements in the target array will be added in this order) + * @return the array of Objects + * @throws NullPointerException + * if values or nameMapping is null + */ + public static Object[] filterMapToObjectArray(final Map values, final String[] nameMapping) { + + if( values == null ) { + throw new NullPointerException("values should not be null"); + } else if( nameMapping == null ) { + throw new NullPointerException("nameMapping should not be null"); + } + + final Object[] targetArray = new Object[nameMapping.length]; + int i = 0; + for( final String name : nameMapping ) { + targetArray[i++] = values.get(name); + } + return targetArray; + } + + /** + * Converts an Object array to a String array (null-safe), by calling toString() on each element. + * + * @param objectArray + * the Object array + * @return the String array, or null if objectArray is null + */ + public static String[] objectArrayToStringArray(final Object[] objectArray) { + if( objectArray == null ) { + return null; + } + + final String[] stringArray = new String[objectArray.length]; + for( int i = 0; i < objectArray.length; i++ ) { + stringArray[i] = objectArray[i] != null ? objectArray[i].toString() : null; + } + + return stringArray; + } + + /** + * Converts an List objectList) { + if( objectList == null ) { + return null; + } + + final String[] stringArray = new String[objectList.size()]; + for( int i = 0; i < objectList.size(); i++ ) { + stringArray[i] = objectList.get(i) != null ? objectList.get(i).toString() : null; + } + + return stringArray; + } + +} diff --git a/super-csv/src/main/java/org/supercsv/util/package-info.java b/super-csv/src/main/java/org/supercsv/util/package-info.java index ecac2797..db6099d6 100644 --- a/super-csv/src/main/java/org/supercsv/util/package-info.java +++ b/super-csv/src/main/java/org/supercsv/util/package-info.java @@ -1,19 +1,19 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * 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. - */ -/** - * Provides the utility classes used by Super CSV. - */ +/* + * Copyright 2007 Kasper B. Graversen + * + * 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. + */ +/** + * Provides the utility classes used by Super CSV. + */ package org.supercsv.util; \ No newline at end of file diff --git a/super-csv/src/site/site.xml b/super-csv/src/site/site.xml index 04f38b05..a91ff6bf 100644 --- a/super-csv/src/site/site.xml +++ b/super-csv/src/site/site.xml @@ -1,25 +1,25 @@ - - - - - - - - - - + + + + + + + + + + \ No newline at end of file diff --git a/super-csv/src/test/java/org/supercsv/SuperCsvTestUtils.java b/super-csv/src/test/java/org/supercsv/SuperCsvTestUtils.java index 3bb9f445..f1cf2620 100644 --- a/super-csv/src/test/java/org/supercsv/SuperCsvTestUtils.java +++ b/super-csv/src/test/java/org/supercsv/SuperCsvTestUtils.java @@ -1,198 +1,198 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv; - -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.supercsv.cellprocessor.FmtBool; -import org.supercsv.cellprocessor.FmtDate; -import org.supercsv.cellprocessor.Optional; -import org.supercsv.cellprocessor.ParseBool; -import org.supercsv.cellprocessor.ParseDate; -import org.supercsv.cellprocessor.ParseInt; -import org.supercsv.cellprocessor.ParseLong; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.mock.CustomerBean; -import org.supercsv.mock.CustomerStringBean; -import org.supercsv.util.CsvContext; - -/** - * Utility methods and constants for tests. - * - * @author James Bassett - */ -public class SuperCsvTestUtils { - - public static final CsvContext ANONYMOUS_CSVCONTEXT = new CsvContext(1, 2, 3); - - /** the complete header for testing */ - public static final String[] HEADER = new String[] { "customerNo", "firstName", "lastName", "birthDate", - "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; - public static final String HEADER_CSV = "customerNo,firstName,lastName,birthDate,mailingAddress,married," - + "numberOfKids,favouriteQuote,email,loyaltyPoints"; - - /** partial header for testing partial reading (only a few columns are mapped) */ - public static final String[] PARTIAL_HEADER = new String[] { null, "firstName", "lastName", null, null, null, null, - null, "email", null }; - - /** the processors to use for CSV reading tests */ - public static final CellProcessor[] READ_PROCESSORS = new CellProcessor[] { null, null, null, - new ParseDate("dd/MM/yyyy"), null, new Optional(new ParseBool()), new Optional(new ParseInt()), null, null, - new ParseLong() }; - - /** the processors to use for CSV writing tests */ - public static final CellProcessor[] WRITE_PROCESSORS = new CellProcessor[] { null, null, null, - new FmtDate("dd/MM/yyyy"), null, new Optional(new FmtBool("Y", "N")), null, null, null, null }; - - // each line in the CSV file and it's corresponding CustomerBean/CustomerStringBeans for testing - public static final String JOHN_CSV = "1,John,Dunbar,13/06/1945,\"1600 Amphitheatre Parkway\r\nMountain View, CA 94043\r\nUnited States\"," - + ",,\"\"\"May the Force be with you.\"\" - Star Wars\",jdunbar@gmail.com,0"; - public static final CustomerBean JOHN = new CustomerBean("1", "John", "Dunbar", date(1945, 6, 13), - "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, - "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); - public static final CustomerStringBean JOHN_STRING = new CustomerStringBean(JOHN); - - public static final String BOB_CSV = "2,Bob,Down,25/02/1919,\"1601 Willow Rd.\r\nMenlo Park, CA 94025\r\nUnited States\"," - + "Y,0,\"\"\"Frankly, my dear, I don't give a damn.\"\" - Gone With The Wind\",bobdown@hotmail.com,123456"; - public static final CustomerBean BOB = new CustomerBean("2", "Bob", "Down", date(1919, 2, 25), - "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, - "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); - public static final CustomerStringBean BOB_STRING = new CustomerStringBean(BOB); - - public static final String ALICE_CSV = "3,Alice,Wunderland,08/08/1985,\"One Microsoft Way\r\nRedmond, WA 98052-6399\r\nUnited States\"," - + "Y,0,\"\"\"Play it, Sam. Play \"\"As Time Goes By.\"\"\"\" - Casablanca\",throughthelookingglass@yahoo.com,2255887799"; - public static final CustomerBean ALICE = new CustomerBean("3", "Alice", "Wunderland", date(1985, 8, 8), - "One Microsoft Way\nRedmond, WA 98052-6399\nUnited States", true, 0, - "\"Play it, Sam. Play \"As Time Goes By.\"\" - Casablanca", "throughthelookingglass@yahoo.com", 2255887799L); - public static final CustomerStringBean ALICE_STRING = new CustomerStringBean(ALICE); - - public static final String BILL_CSV = "4,Bill,Jobs,10/07/1973,\"2701 San Tomas Expressway\r\nSanta Clara, CA 95050\r\nUnited States\"," - + "Y,3,\"\"\"You've got to ask yourself one question: \"\"Do I feel lucky?\"\" Well, do ya, punk?\"\" - Dirty Harry\",billy34@hotmail.com,36"; - public static final CustomerBean BILL = new CustomerBean("4", "Bill", "Jobs", date(1973, 7, 10), - "2701 San Tomas Expressway\nSanta Clara, CA 95050\nUnited States", true, 3, - "\"You've got to ask yourself one question: \"Do I feel lucky?\" Well, do ya, punk?\" - Dirty Harry", - "billy34@hotmail.com", 36L); - public static final CustomerStringBean BILL_STRING = new CustomerStringBean(BILL); - - public static final String MIRANDA_CSV = "5,Miranda,Feist,03/01/1999,\"2-4 Rue du Sablon\r\nMorges, 1110\r\nSwitzerland\"," - + ",,\"\"\"You had me at \"\"hello.\"\"\"\" - Jerry Maguire\",miranda_feist@gmail.com,54623"; - public static final CustomerBean MIRANDA = new CustomerBean("5", "Miranda", "Feist", date(1999, 1, 3), - "2-4 Rue du Sablon\nMorges, 1110\nSwitzerland", null, null, "\"You had me at \"hello.\"\" - Jerry Maguire", - "miranda_feist@gmail.com", 54623L); - public static final CustomerStringBean MIRANDA_STRING = new CustomerStringBean(MIRANDA); - - public static final String STEVE_CSV = "6,Steve,Gates,31/12/2000,\"701 First Avenue\r\nSunnyvale, CA 94089\r\nUnited States\"," - + "N,0,\"\"\"Gentlemen, you can't fight in here! This is the War Room!\"\" - Dr Strangelove\",stevengates@yahoo.com,1341512"; - public static final CustomerBean STEVE = new CustomerBean("6", "Steve", "Gates", date(2000, 12, 31), - "701 First Avenue\nSunnyvale, CA 94089\nUnited States", false, 0, - "\"Gentlemen, you can't fight in here! This is the War Room!\" - Dr Strangelove", "stevengates@yahoo.com", - 1341512L); - public static final CustomerStringBean STEVE_STRING = new CustomerStringBean(STEVE); - - public static final String ADA_CSV = "7,Ada,Von Trappe,18/11/1956,\"One Dell Way\r\nRound Rock, TX 78682\r\nUnited States\"," - + ",2,\"\"\"Hasta la vista, baby.\"\" - Terminator 2: Judgement Day\",vonada@gmail.com,0"; - public static final CustomerBean ADA = new CustomerBean("7", "Ada", "Von Trappe", date(1956, 11, 18), - "One Dell Way\nRound Rock, TX 78682\nUnited States", null, 2, - "\"Hasta la vista, baby.\" - Terminator 2: Judgement Day", "vonada@gmail.com", 0L); - public static final CustomerStringBean ADA_STRING = new CustomerStringBean(ADA); - - public static final String SERGEI_CSV = "8,Sergei,Denisovich,22/06/1944,\"1 Infinite Loop\r\nCupertino, CA 95014\r\nUnited States\"," - + "Y,,\"\"\"Open the pod bay doors, HAL.\"\" - 2001: A Space Odyssey\",sergei@denisovich.com,229431"; - public static final CustomerBean SERGEI = new CustomerBean("8", "Sergei", "Denisovich", date(1944, 6, 22), - "1 Infinite Loop\nCupertino, CA 95014\nUnited States", true, null, - "\"Open the pod bay doors, HAL.\" - 2001: A Space Odyssey", "sergei@denisovich.com", 229431L); - public static final CustomerStringBean SERGEI_STRING = new CustomerStringBean(SERGEI); - - public static final String LARRY_CSV = "9,Larry,Ballmer,01/01/1901,\"1-7-1 Konan\r\nMinato-ku\r\nTokyo, 108-0075\r\nJapan\"," - + "N,0,\"\"\"A martini. Shaken, not stirred.\"\" - Goldfinger\",lazza99@gmail.com,164"; - public static final CustomerBean LARRY = new CustomerBean("9", "Larry", "Ballmer", date(1901, 1, 1), - "1-7-1 Konan\nMinato-ku\nTokyo, 108-0075\nJapan", false, 0, "\"A martini. Shaken, not stirred.\" - Goldfinger", - "lazza99@gmail.com", 164L); - public static final CustomerStringBean LARRY_STRING = new CustomerStringBean(LARRY); - - public static final String GRACE_CSV = "10,Grace,Fowler,28/11/2003,\"11-1, Kamitoba Hokotate-cho\r\nMinami-ku\r\nKyoto, 601-8501\r\nJapan\"," - + "N,0,\"\"\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"\" - Dead Poets Society\",gracie@hotmail.com,168841"; - public static final CustomerBean GRACE = new CustomerBean("10", "Grace", "Fowler", date(2003, 11, 28), - "11-1, Kamitoba Hokotate-cho\nMinami-ku\nKyoto, 601-8501\nJapan", false, 0, - "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\" - Dead Poets Society", - "gracie@hotmail.com", 168841L); - public static final CustomerStringBean GRACE_STRING = new CustomerStringBean(GRACE); - - /** - * The CSV file to use for testing. - */ - public static final String CSV_FILE = new StringBuilder(HEADER_CSV).append("\r\n").append(JOHN_CSV).append("\r\n") - .append(BOB_CSV).append("\r\n").append(ALICE_CSV).append("\r\n").append(BILL_CSV).append("\r\n") - .append(MIRANDA_CSV).append("\r\n").append(STEVE_CSV).append("\r\n").append(ADA_CSV).append("\r\n") - .append(SERGEI_CSV).append("\r\n").append(LARRY_CSV).append("\r\n").append(GRACE_CSV).append("\r\n").toString(); - - /** List of populated customer beans to use for testing */ - public static final List CUSTOMERS = Arrays.asList(JOHN, BOB, ALICE, BILL, MIRANDA, STEVE, ADA, - SERGEI, LARRY, GRACE); - - /** List of populated customer string beans to use for testing */ - public static final List STRING_CUSTOMERS = Arrays.asList(JOHN_STRING, BOB_STRING, - ALICE_STRING, BILL_STRING, MIRANDA_STRING, STEVE_STRING, ADA_STRING, SERGEI_STRING, LARRY_STRING, GRACE_STRING); - - /** - * An easy and non-deprecated non-lenient way of creating Date objects. - * - * @param year - * the year, e.g. 2007 is year 2007 - * @param month - * the month, where 1 == January - * @param dayOfMonth - * the day of the month, where 1 == first day of the month - * @return a Date object with time set to midnight, ie. hour = 00, minutes = 00, seconds = 00 and milliseconds = 000 - */ - public static Date date(final int year, final int month, final int dayOfMonth) { - final Calendar cal = Calendar.getInstance(); - cal.setLenient(false); - cal.set(year, month - 1, dayOfMonth, 0, 0, 0); - cal.set(Calendar.MILLISECOND, 0); - return cal.getTime(); - } - - /** - * An easy and non-deprecated non-lenient way of creating Date objects. - * - * @param year - * the year, e.g. 2007 is year 2007 - * @param month - * the month, where 1 == January - * @param dayOfMonth - * the day of the month, where 1 == first day of the month - * @param hour - * the hour in 24 hour format where 0 == midnight - * @param minute - * is the minute 0-59 - * @param second - * is the seconds 0-59 - * @return a Date object with time set to midnight, ie. hour = 00, minutes = 00, seconds = 00 and milliseconds = 000 - */ - public static Date date(final int year, final int month, final int dayOfMonth, final int hour, final int minute, - final int second) { - final Calendar cal = Calendar.getInstance(); - cal.setLenient(false); - cal.set(year, month - 1, dayOfMonth, hour, minute, second); - cal.set(Calendar.MILLISECOND, 0); - return cal.getTime(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv; + +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import org.supercsv.cellprocessor.FmtBool; +import org.supercsv.cellprocessor.FmtDate; +import org.supercsv.cellprocessor.Optional; +import org.supercsv.cellprocessor.ParseBool; +import org.supercsv.cellprocessor.ParseDate; +import org.supercsv.cellprocessor.ParseInt; +import org.supercsv.cellprocessor.ParseLong; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.mock.CustomerBean; +import org.supercsv.mock.CustomerStringBean; +import org.supercsv.util.CsvContext; + +/** + * Utility methods and constants for tests. + * + * @author James Bassett + */ +public class SuperCsvTestUtils { + + public static final CsvContext ANONYMOUS_CSVCONTEXT = new CsvContext(1, 2, 3); + + /** the complete header for testing */ + public static final String[] HEADER = new String[] { "customerNo", "firstName", "lastName", "birthDate", + "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; + public static final String HEADER_CSV = "customerNo,firstName,lastName,birthDate,mailingAddress,married," + + "numberOfKids,favouriteQuote,email,loyaltyPoints"; + + /** partial header for testing partial reading (only a few columns are mapped) */ + public static final String[] PARTIAL_HEADER = new String[] { null, "firstName", "lastName", null, null, null, null, + null, "email", null }; + + /** the processors to use for CSV reading tests */ + public static final CellProcessor[] READ_PROCESSORS = new CellProcessor[] { null, null, null, + new ParseDate("dd/MM/yyyy"), null, new Optional(new ParseBool()), new Optional(new ParseInt()), null, null, + new ParseLong() }; + + /** the processors to use for CSV writing tests */ + public static final CellProcessor[] WRITE_PROCESSORS = new CellProcessor[] { null, null, null, + new FmtDate("dd/MM/yyyy"), null, new Optional(new FmtBool("Y", "N")), null, null, null, null }; + + // each line in the CSV file and it's corresponding CustomerBean/CustomerStringBeans for testing + public static final String JOHN_CSV = "1,John,Dunbar,13/06/1945,\"1600 Amphitheatre Parkway\r\nMountain View, CA 94043\r\nUnited States\"," + + ",,\"\"\"May the Force be with you.\"\" - Star Wars\",jdunbar@gmail.com,0"; + public static final CustomerBean JOHN = new CustomerBean("1", "John", "Dunbar", date(1945, 6, 13), + "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, + "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); + public static final CustomerStringBean JOHN_STRING = new CustomerStringBean(JOHN); + + public static final String BOB_CSV = "2,Bob,Down,25/02/1919,\"1601 Willow Rd.\r\nMenlo Park, CA 94025\r\nUnited States\"," + + "Y,0,\"\"\"Frankly, my dear, I don't give a damn.\"\" - Gone With The Wind\",bobdown@hotmail.com,123456"; + public static final CustomerBean BOB = new CustomerBean("2", "Bob", "Down", date(1919, 2, 25), + "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, + "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); + public static final CustomerStringBean BOB_STRING = new CustomerStringBean(BOB); + + public static final String ALICE_CSV = "3,Alice,Wunderland,08/08/1985,\"One Microsoft Way\r\nRedmond, WA 98052-6399\r\nUnited States\"," + + "Y,0,\"\"\"Play it, Sam. Play \"\"As Time Goes By.\"\"\"\" - Casablanca\",throughthelookingglass@yahoo.com,2255887799"; + public static final CustomerBean ALICE = new CustomerBean("3", "Alice", "Wunderland", date(1985, 8, 8), + "One Microsoft Way\nRedmond, WA 98052-6399\nUnited States", true, 0, + "\"Play it, Sam. Play \"As Time Goes By.\"\" - Casablanca", "throughthelookingglass@yahoo.com", 2255887799L); + public static final CustomerStringBean ALICE_STRING = new CustomerStringBean(ALICE); + + public static final String BILL_CSV = "4,Bill,Jobs,10/07/1973,\"2701 San Tomas Expressway\r\nSanta Clara, CA 95050\r\nUnited States\"," + + "Y,3,\"\"\"You've got to ask yourself one question: \"\"Do I feel lucky?\"\" Well, do ya, punk?\"\" - Dirty Harry\",billy34@hotmail.com,36"; + public static final CustomerBean BILL = new CustomerBean("4", "Bill", "Jobs", date(1973, 7, 10), + "2701 San Tomas Expressway\nSanta Clara, CA 95050\nUnited States", true, 3, + "\"You've got to ask yourself one question: \"Do I feel lucky?\" Well, do ya, punk?\" - Dirty Harry", + "billy34@hotmail.com", 36L); + public static final CustomerStringBean BILL_STRING = new CustomerStringBean(BILL); + + public static final String MIRANDA_CSV = "5,Miranda,Feist,03/01/1999,\"2-4 Rue du Sablon\r\nMorges, 1110\r\nSwitzerland\"," + + ",,\"\"\"You had me at \"\"hello.\"\"\"\" - Jerry Maguire\",miranda_feist@gmail.com,54623"; + public static final CustomerBean MIRANDA = new CustomerBean("5", "Miranda", "Feist", date(1999, 1, 3), + "2-4 Rue du Sablon\nMorges, 1110\nSwitzerland", null, null, "\"You had me at \"hello.\"\" - Jerry Maguire", + "miranda_feist@gmail.com", 54623L); + public static final CustomerStringBean MIRANDA_STRING = new CustomerStringBean(MIRANDA); + + public static final String STEVE_CSV = "6,Steve,Gates,31/12/2000,\"701 First Avenue\r\nSunnyvale, CA 94089\r\nUnited States\"," + + "N,0,\"\"\"Gentlemen, you can't fight in here! This is the War Room!\"\" - Dr Strangelove\",stevengates@yahoo.com,1341512"; + public static final CustomerBean STEVE = new CustomerBean("6", "Steve", "Gates", date(2000, 12, 31), + "701 First Avenue\nSunnyvale, CA 94089\nUnited States", false, 0, + "\"Gentlemen, you can't fight in here! This is the War Room!\" - Dr Strangelove", "stevengates@yahoo.com", + 1341512L); + public static final CustomerStringBean STEVE_STRING = new CustomerStringBean(STEVE); + + public static final String ADA_CSV = "7,Ada,Von Trappe,18/11/1956,\"One Dell Way\r\nRound Rock, TX 78682\r\nUnited States\"," + + ",2,\"\"\"Hasta la vista, baby.\"\" - Terminator 2: Judgement Day\",vonada@gmail.com,0"; + public static final CustomerBean ADA = new CustomerBean("7", "Ada", "Von Trappe", date(1956, 11, 18), + "One Dell Way\nRound Rock, TX 78682\nUnited States", null, 2, + "\"Hasta la vista, baby.\" - Terminator 2: Judgement Day", "vonada@gmail.com", 0L); + public static final CustomerStringBean ADA_STRING = new CustomerStringBean(ADA); + + public static final String SERGEI_CSV = "8,Sergei,Denisovich,22/06/1944,\"1 Infinite Loop\r\nCupertino, CA 95014\r\nUnited States\"," + + "Y,,\"\"\"Open the pod bay doors, HAL.\"\" - 2001: A Space Odyssey\",sergei@denisovich.com,229431"; + public static final CustomerBean SERGEI = new CustomerBean("8", "Sergei", "Denisovich", date(1944, 6, 22), + "1 Infinite Loop\nCupertino, CA 95014\nUnited States", true, null, + "\"Open the pod bay doors, HAL.\" - 2001: A Space Odyssey", "sergei@denisovich.com", 229431L); + public static final CustomerStringBean SERGEI_STRING = new CustomerStringBean(SERGEI); + + public static final String LARRY_CSV = "9,Larry,Ballmer,01/01/1901,\"1-7-1 Konan\r\nMinato-ku\r\nTokyo, 108-0075\r\nJapan\"," + + "N,0,\"\"\"A martini. Shaken, not stirred.\"\" - Goldfinger\",lazza99@gmail.com,164"; + public static final CustomerBean LARRY = new CustomerBean("9", "Larry", "Ballmer", date(1901, 1, 1), + "1-7-1 Konan\nMinato-ku\nTokyo, 108-0075\nJapan", false, 0, "\"A martini. Shaken, not stirred.\" - Goldfinger", + "lazza99@gmail.com", 164L); + public static final CustomerStringBean LARRY_STRING = new CustomerStringBean(LARRY); + + public static final String GRACE_CSV = "10,Grace,Fowler,28/11/2003,\"11-1, Kamitoba Hokotate-cho\r\nMinami-ku\r\nKyoto, 601-8501\r\nJapan\"," + + "N,0,\"\"\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\"\" - Dead Poets Society\",gracie@hotmail.com,168841"; + public static final CustomerBean GRACE = new CustomerBean("10", "Grace", "Fowler", date(2003, 11, 28), + "11-1, Kamitoba Hokotate-cho\nMinami-ku\nKyoto, 601-8501\nJapan", false, 0, + "\"Carpe diem. Seize the day, boys. Make your lives extraordinary.\" - Dead Poets Society", + "gracie@hotmail.com", 168841L); + public static final CustomerStringBean GRACE_STRING = new CustomerStringBean(GRACE); + + /** + * The CSV file to use for testing. + */ + public static final String CSV_FILE = new StringBuilder(HEADER_CSV).append("\r\n").append(JOHN_CSV).append("\r\n") + .append(BOB_CSV).append("\r\n").append(ALICE_CSV).append("\r\n").append(BILL_CSV).append("\r\n") + .append(MIRANDA_CSV).append("\r\n").append(STEVE_CSV).append("\r\n").append(ADA_CSV).append("\r\n") + .append(SERGEI_CSV).append("\r\n").append(LARRY_CSV).append("\r\n").append(GRACE_CSV).append("\r\n").toString(); + + /** List of populated customer beans to use for testing */ + public static final List CUSTOMERS = Arrays.asList(JOHN, BOB, ALICE, BILL, MIRANDA, STEVE, ADA, + SERGEI, LARRY, GRACE); + + /** List of populated customer string beans to use for testing */ + public static final List STRING_CUSTOMERS = Arrays.asList(JOHN_STRING, BOB_STRING, + ALICE_STRING, BILL_STRING, MIRANDA_STRING, STEVE_STRING, ADA_STRING, SERGEI_STRING, LARRY_STRING, GRACE_STRING); + + /** + * An easy and non-deprecated non-lenient way of creating Date objects. + * + * @param year + * the year, e.g. 2007 is year 2007 + * @param month + * the month, where 1 == January + * @param dayOfMonth + * the day of the month, where 1 == first day of the month + * @return a Date object with time set to midnight, ie. hour = 00, minutes = 00, seconds = 00 and milliseconds = 000 + */ + public static Date date(final int year, final int month, final int dayOfMonth) { + final Calendar cal = Calendar.getInstance(); + cal.setLenient(false); + cal.set(year, month - 1, dayOfMonth, 0, 0, 0); + cal.set(Calendar.MILLISECOND, 0); + return cal.getTime(); + } + + /** + * An easy and non-deprecated non-lenient way of creating Date objects. + * + * @param year + * the year, e.g. 2007 is year 2007 + * @param month + * the month, where 1 == January + * @param dayOfMonth + * the day of the month, where 1 == first day of the month + * @param hour + * the hour in 24 hour format where 0 == midnight + * @param minute + * is the minute 0-59 + * @param second + * is the seconds 0-59 + * @return a Date object with time set to midnight, ie. hour = 00, minutes = 00, seconds = 00 and milliseconds = 000 + */ + public static Date date(final int year, final int month, final int dayOfMonth, final int hour, final int minute, + final int second) { + final Calendar cal = Calendar.getInstance(); + cal.setLenient(false); + cal.set(year, month - 1, dayOfMonth, hour, minute, second); + cal.set(Calendar.MILLISECOND, 0); + return cal.getTime(); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/CellProcessorAdaptorTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/CellProcessorAdaptorTest.java index 9a0ee62b..66d8dcb4 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/CellProcessorAdaptorTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/CellProcessorAdaptorTest.java @@ -1,64 +1,64 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the CellProcessorAdaptor abstract processor. - * - * @author James Bassett - */ -public class CellProcessorAdaptorTest { - - @Test - public void testToString() { - assertEquals("org.supercsv.mock.IdentityTransform", new IdentityTransform().toString()); - } - - /** - * Tests construction of an unchained processor. - */ - @Test - public void testValidUnchained() { - IdentityTransform processor = new IdentityTransform(); - assertEquals("org.supercsv.cellprocessor.CellProcessorAdaptor$NullObjectPattern", processor.next.getClass() - .getName()); - - } - - /** - * Tests construction of an processor chain. - */ - @Test - public void testValidChained() { - ConvertNullTo processor = new ConvertNullTo("null"); - IdentityTransform processorChain = new IdentityTransform(processor); - assertEquals(processor, processorChain.next); - } - - /** - * Tests construction of a processor chain with a null processor (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testChainedWithNull() { - new IdentityTransform(null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the CellProcessorAdaptor abstract processor. + * + * @author James Bassett + */ +public class CellProcessorAdaptorTest { + + @Test + public void testToString() { + assertEquals("org.supercsv.mock.IdentityTransform", new IdentityTransform().toString()); + } + + /** + * Tests construction of an unchained processor. + */ + @Test + public void testValidUnchained() { + IdentityTransform processor = new IdentityTransform(); + assertEquals("org.supercsv.cellprocessor.CellProcessorAdaptor$NullObjectPattern", processor.next.getClass() + .getName()); + + } + + /** + * Tests construction of an processor chain. + */ + @Test + public void testValidChained() { + ConvertNullTo processor = new ConvertNullTo("null"); + IdentityTransform processorChain = new IdentityTransform(processor); + assertEquals(processor, processorChain.next); + } + + /** + * Tests construction of a processor chain with a null processor (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testChainedWithNull() { + new IdentityTransform(null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ConvertNullToTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ConvertNullToTest.java index ac24c18a..00dd5059 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ConvertNullToTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ConvertNullToTest.java @@ -1,66 +1,66 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ConvertNull processor. - * - * @author James Bassett - */ -public class ConvertNullToTest { - - private static final String CONVERTED_VALUE = "previously null!"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ConvertNullTo(CONVERTED_VALUE); - processorChain = new ConvertNullTo(CONVERTED_VALUE, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a null value (should return converted value). - */ - @Test - public void testWithNullValue() { - assertEquals(CONVERTED_VALUE, processor.execute(null, ANONYMOUS_CSVCONTEXT)); - assertEquals(CONVERTED_VALUE, processorChain.execute(null, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with a non-null value (should return input unchanged). - */ - @Test - public void testWithNonNullValue() { - String notNull = "not null!"; - assertEquals(notNull, processor.execute(notNull, ANONYMOUS_CSVCONTEXT)); - assertEquals(notNull, processorChain.execute(notNull, ANONYMOUS_CSVCONTEXT)); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ConvertNull processor. + * + * @author James Bassett + */ +public class ConvertNullToTest { + + private static final String CONVERTED_VALUE = "previously null!"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ConvertNullTo(CONVERTED_VALUE); + processorChain = new ConvertNullTo(CONVERTED_VALUE, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a null value (should return converted value). + */ + @Test + public void testWithNullValue() { + assertEquals(CONVERTED_VALUE, processor.execute(null, ANONYMOUS_CSVCONTEXT)); + assertEquals(CONVERTED_VALUE, processorChain.execute(null, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with a non-null value (should return input unchanged). + */ + @Test + public void testWithNonNullValue() { + String notNull = "not null!"; + assertEquals(notNull, processor.execute(notNull, ANONYMOUS_CSVCONTEXT)); + assertEquals(notNull, processorChain.execute(notNull, ANONYMOUS_CSVCONTEXT)); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/FmtBoolTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/FmtBoolTest.java index 62287cf3..956be8ea 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/FmtBoolTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/FmtBoolTest.java @@ -1,84 +1,84 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the FmtBool processor. - * - * @author Dominique De Vito - * @author James Bassett - */ -public class FmtBoolTest { - - private static final String TRUE_VALUE = "y"; - private static final String FALSE_VALUE = "n"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new FmtBool(TRUE_VALUE, FALSE_VALUE); - processorChain = new FmtBool(TRUE_VALUE, FALSE_VALUE, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with true. - */ - @Test - public void testWithTrue() { - assertEquals(TRUE_VALUE, processor.execute(true, ANONYMOUS_CSVCONTEXT)); - assertEquals(TRUE_VALUE, processorChain.execute(true, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with false. - */ - @Test - public void testWithFalse() { - assertEquals(FALSE_VALUE, processor.execute(false, ANONYMOUS_CSVCONTEXT)); - assertEquals(FALSE_VALUE, processorChain.execute(false, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non-Boolean input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonBoolean() { - processor.execute(123, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the FmtBool processor. + * + * @author Dominique De Vito + * @author James Bassett + */ +public class FmtBoolTest { + + private static final String TRUE_VALUE = "y"; + private static final String FALSE_VALUE = "n"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new FmtBool(TRUE_VALUE, FALSE_VALUE); + processorChain = new FmtBool(TRUE_VALUE, FALSE_VALUE, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with true. + */ + @Test + public void testWithTrue() { + assertEquals(TRUE_VALUE, processor.execute(true, ANONYMOUS_CSVCONTEXT)); + assertEquals(TRUE_VALUE, processorChain.execute(true, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with false. + */ + @Test + public void testWithFalse() { + assertEquals(FALSE_VALUE, processor.execute(false, ANONYMOUS_CSVCONTEXT)); + assertEquals(FALSE_VALUE, processorChain.execute(false, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non-Boolean input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonBoolean() { + processor.execute(123, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/FmtDateTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/FmtDateTest.java index e30e5ff2..6aaba0b3 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/FmtDateTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/FmtDateTest.java @@ -1,95 +1,95 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; -import static org.supercsv.SuperCsvTestUtils.date; - -import java.util.Date; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the FmtDate processor. - * - * @author Dominique De Vito - * @author James Bassett - */ -public class FmtDateTest { - - private static final String DATE_FORMAT = "dd/MM/yyyy"; - private static final Date DATE = date(2011, 12, 25); - private static final String FORMATTED_DATE = "25/12/2011"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new FmtDate(DATE_FORMAT); - processorChain = new FmtDate(DATE_FORMAT, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a valid date. - */ - @Test - public void testWithValidDate() { - assertEquals(FORMATTED_DATE, processor.execute(DATE, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_DATE, processorChain.execute(DATE, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non-Date input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonDate() { - processor.execute(123, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a invalid date format (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithInvalidDateFormat() { - CellProcessor invalidDateFormatProcessor = new FmtDate("abcd"); - invalidDateFormatProcessor.execute(DATE, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction of the processor with a null date format (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testWithNullDateFormat() { - new FmtDate(null); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; +import static org.supercsv.SuperCsvTestUtils.date; + +import java.util.Date; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the FmtDate processor. + * + * @author Dominique De Vito + * @author James Bassett + */ +public class FmtDateTest { + + private static final String DATE_FORMAT = "dd/MM/yyyy"; + private static final Date DATE = date(2011, 12, 25); + private static final String FORMATTED_DATE = "25/12/2011"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new FmtDate(DATE_FORMAT); + processorChain = new FmtDate(DATE_FORMAT, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a valid date. + */ + @Test + public void testWithValidDate() { + assertEquals(FORMATTED_DATE, processor.execute(DATE, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_DATE, processorChain.execute(DATE, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non-Date input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonDate() { + processor.execute(123, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a invalid date format (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithInvalidDateFormat() { + CellProcessor invalidDateFormatProcessor = new FmtDate("abcd"); + invalidDateFormatProcessor.execute(DATE, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction of the processor with a null date format (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testWithNullDateFormat() { + new FmtDate(null); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/FmtNumberTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/FmtNumberTest.java index ce73ab87..595e1f69 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/FmtNumberTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/FmtNumberTest.java @@ -1,142 +1,142 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.text.DecimalFormat; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the FmtNumber processor. As FmtNumber uses the default locale, this test must be written in a locale - * independent way (so the test will pass). The test can be run in a different local by specifying the - * user.language and user.country JVM properties (i.e. -Duser.language=de -Duser.country=DE). - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class FmtNumberTest { - - private static final String DECIMAL_FORMAT = "00.00"; - - // locale-independent - private static final String FORMATTED_NUMBER = new DecimalFormat(DECIMAL_FORMAT).format(12.34); - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new FmtNumber(DECIMAL_FORMAT); - processor2 = new FmtNumber(new DecimalFormat(DECIMAL_FORMAT)); - processorChain = new FmtNumber(DECIMAL_FORMAT, new IdentityTransform()); - processorChain2 = new FmtNumber(new DecimalFormat(DECIMAL_FORMAT), new IdentityTransform()); - } - - /** - * Tests unchained/chained execution. - */ - @Test - public void testFormat() { - final double number = 12.34; - assertEquals(FORMATTED_NUMBER, processor.execute(number, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processor2.execute(number, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processorChain.execute(number, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processorChain2.execute(number, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with an input that should round up. - */ - @Test - public void testRoundUp() { - final double toRoundUp = 12.339; - assertEquals(FORMATTED_NUMBER, processor.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processor2.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processorChain.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processorChain2.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with an input that should round down. - */ - @Test - public void testRoundDown() { - final double toRoundDown = 12.341; - assertEquals(FORMATTED_NUMBER, processor.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processor2.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processorChain.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); - assertEquals(FORMATTED_NUMBER, processorChain2.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non-Number input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonNumber() { - processor.execute("abc", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a invalid number format (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithInvalidNumberFormat() { - final double number = 12.34; - CellProcessor invalidNumberFormatProcessor = new FmtNumber("%%%"); - invalidNumberFormatProcessor.execute(number, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a invalid number format String (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testWithNullNumberFormatString() { - final double number = 12.34; - CellProcessor invalidNumberFormatProcessor = new FmtNumber((String) null); - invalidNumberFormatProcessor.execute(number, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a invalid number format object (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testWithNullNumberFormat() { - final double number = 12.34; - CellProcessor invalidNumberFormatProcessor = new FmtNumber((DecimalFormat) null); - invalidNumberFormatProcessor.execute(number, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.text.DecimalFormat; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the FmtNumber processor. As FmtNumber uses the default locale, this test must be written in a locale + * independent way (so the test will pass). The test can be run in a different local by specifying the + * user.language and user.country JVM properties (i.e. -Duser.language=de -Duser.country=DE). + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class FmtNumberTest { + + private static final String DECIMAL_FORMAT = "00.00"; + + // locale-independent + private static final String FORMATTED_NUMBER = new DecimalFormat(DECIMAL_FORMAT).format(12.34); + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new FmtNumber(DECIMAL_FORMAT); + processor2 = new FmtNumber(new DecimalFormat(DECIMAL_FORMAT)); + processorChain = new FmtNumber(DECIMAL_FORMAT, new IdentityTransform()); + processorChain2 = new FmtNumber(new DecimalFormat(DECIMAL_FORMAT), new IdentityTransform()); + } + + /** + * Tests unchained/chained execution. + */ + @Test + public void testFormat() { + final double number = 12.34; + assertEquals(FORMATTED_NUMBER, processor.execute(number, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processor2.execute(number, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processorChain.execute(number, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processorChain2.execute(number, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with an input that should round up. + */ + @Test + public void testRoundUp() { + final double toRoundUp = 12.339; + assertEquals(FORMATTED_NUMBER, processor.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processor2.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processorChain.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processorChain2.execute(toRoundUp, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with an input that should round down. + */ + @Test + public void testRoundDown() { + final double toRoundDown = 12.341; + assertEquals(FORMATTED_NUMBER, processor.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processor2.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processorChain.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); + assertEquals(FORMATTED_NUMBER, processorChain2.execute(toRoundDown, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non-Number input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonNumber() { + processor.execute("abc", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a invalid number format (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithInvalidNumberFormat() { + final double number = 12.34; + CellProcessor invalidNumberFormatProcessor = new FmtNumber("%%%"); + invalidNumberFormatProcessor.execute(number, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a invalid number format String (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testWithNullNumberFormatString() { + final double number = 12.34; + CellProcessor invalidNumberFormatProcessor = new FmtNumber((String) null); + invalidNumberFormatProcessor.execute(number, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a invalid number format object (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testWithNullNumberFormat() { + final double number = 12.34; + CellProcessor invalidNumberFormatProcessor = new FmtNumber((DecimalFormat) null); + invalidNumberFormatProcessor.execute(number, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/HashMapperTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/HashMapperTest.java index f2697fa6..fcea267c 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/HashMapperTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/HashMapperTest.java @@ -1,134 +1,134 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the HashMapper processor. - * - * @author Dominique De Vito - * @author James Bassett - */ -public class HashMapperTest { - - private static final String DEFAULT_VALUE = "Default"; - - private static final Map VALUE_MAP = new HashMap(); - static { - VALUE_MAP.put(1, "1"); - VALUE_MAP.put(2, "2"); - VALUE_MAP.put(3, "3"); - } - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new HashMapper(VALUE_MAP); - processor2 = new HashMapper(VALUE_MAP, DEFAULT_VALUE); - processorChain = new HashMapper(VALUE_MAP, new IdentityTransform()); - processorChain2 = new HashMapper(VALUE_MAP, DEFAULT_VALUE, new IdentityTransform()); - } - - /** - * Tests chained/unchained execution with a valid key from the map. - */ - @Test - public void testValidKey() { - int validKey = 1; - assertEquals("1", processor.execute(validKey, ANONYMOUS_CSVCONTEXT)); - assertEquals("1", processor2.execute(validKey, ANONYMOUS_CSVCONTEXT)); - assertEquals("1", processorChain.execute(validKey, ANONYMOUS_CSVCONTEXT)); - assertEquals("1", processorChain2.execute(validKey, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests chained/unchained execution with a key not in the map. - */ - @Test - public void testInvalidKey() { - int invalidKey = 4; - assertFalse(VALUE_MAP.containsKey(invalidKey)); - - // no default values - assertNull(processor.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); - assertNull(processorChain.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); - - // with default values - assertEquals(DEFAULT_VALUE, processor2.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); - assertEquals(DEFAULT_VALUE, processorChain2.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null Map (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullMap() { - new HashMapper(null, DEFAULT_VALUE); - } - - /** - * Tests chained execution with a null Map (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testChainedConstructionWithNullMap() { - new HashMapper(null, DEFAULT_VALUE, new IdentityTransform()); - } - - /** - * Tests construction with an empty Map (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyMap() { - new HashMapper(new HashMap(), DEFAULT_VALUE); - } - - /** - * Tests chained execution with an empty Map (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testChainedConstructionWithEmptyMap() { - new HashMapper(new HashMap(), DEFAULT_VALUE, new IdentityTransform()); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the HashMapper processor. + * + * @author Dominique De Vito + * @author James Bassett + */ +public class HashMapperTest { + + private static final String DEFAULT_VALUE = "Default"; + + private static final Map VALUE_MAP = new HashMap(); + static { + VALUE_MAP.put(1, "1"); + VALUE_MAP.put(2, "2"); + VALUE_MAP.put(3, "3"); + } + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new HashMapper(VALUE_MAP); + processor2 = new HashMapper(VALUE_MAP, DEFAULT_VALUE); + processorChain = new HashMapper(VALUE_MAP, new IdentityTransform()); + processorChain2 = new HashMapper(VALUE_MAP, DEFAULT_VALUE, new IdentityTransform()); + } + + /** + * Tests chained/unchained execution with a valid key from the map. + */ + @Test + public void testValidKey() { + int validKey = 1; + assertEquals("1", processor.execute(validKey, ANONYMOUS_CSVCONTEXT)); + assertEquals("1", processor2.execute(validKey, ANONYMOUS_CSVCONTEXT)); + assertEquals("1", processorChain.execute(validKey, ANONYMOUS_CSVCONTEXT)); + assertEquals("1", processorChain2.execute(validKey, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests chained/unchained execution with a key not in the map. + */ + @Test + public void testInvalidKey() { + int invalidKey = 4; + assertFalse(VALUE_MAP.containsKey(invalidKey)); + + // no default values + assertNull(processor.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); + assertNull(processorChain.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); + + // with default values + assertEquals(DEFAULT_VALUE, processor2.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); + assertEquals(DEFAULT_VALUE, processorChain2.execute(invalidKey, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null Map (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullMap() { + new HashMapper(null, DEFAULT_VALUE); + } + + /** + * Tests chained execution with a null Map (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testChainedConstructionWithNullMap() { + new HashMapper(null, DEFAULT_VALUE, new IdentityTransform()); + } + + /** + * Tests construction with an empty Map (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyMap() { + new HashMapper(new HashMap(), DEFAULT_VALUE); + } + + /** + * Tests chained execution with an empty Map (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testChainedConstructionWithEmptyMap() { + new HashMapper(new HashMap(), DEFAULT_VALUE, new IdentityTransform()); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/OptionalTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/OptionalTest.java index 1d3f1a7b..ef446897 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/OptionalTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/OptionalTest.java @@ -1,83 +1,83 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the Optional processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class OptionalTest { - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new Optional(); - processorChain = new Optional(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with empty string as input. - */ - @Test - public void testEmptyString() { - assertEquals("", processor.execute("", ANONYMOUS_CSVCONTEXT)); - assertEquals("", processorChain.execute("", ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with a space as input. - */ - @Test - public void testSpace() { - assertEquals(" ", processor.execute(" ", ANONYMOUS_CSVCONTEXT)); - assertEquals(" ", processorChain.execute(" ", ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with normal input (not ""). - */ - @Test - public void testNormalInput() { - String normal = "normal"; - assertEquals(normal, processor.execute(normal, ANONYMOUS_CSVCONTEXT)); - assertEquals(normal, processorChain.execute(normal, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should return null). - */ - @Test - public void testWithNull() { - assertNull(processor.execute(null, ANONYMOUS_CSVCONTEXT)); - assertNull(processorChain.execute(null, ANONYMOUS_CSVCONTEXT)); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the Optional processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class OptionalTest { + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new Optional(); + processorChain = new Optional(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with empty string as input. + */ + @Test + public void testEmptyString() { + assertEquals("", processor.execute("", ANONYMOUS_CSVCONTEXT)); + assertEquals("", processorChain.execute("", ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with a space as input. + */ + @Test + public void testSpace() { + assertEquals(" ", processor.execute(" ", ANONYMOUS_CSVCONTEXT)); + assertEquals(" ", processorChain.execute(" ", ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with normal input (not ""). + */ + @Test + public void testNormalInput() { + String normal = "normal"; + assertEquals(normal, processor.execute(normal, ANONYMOUS_CSVCONTEXT)); + assertEquals(normal, processorChain.execute(normal, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should return null). + */ + @Test + public void testWithNull() { + assertNull(processor.execute(null, ANONYMOUS_CSVCONTEXT)); + assertNull(processorChain.execute(null, ANONYMOUS_CSVCONTEXT)); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBigDecimalTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBigDecimalTest.java index 2963d4a5..fe360db2 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBigDecimalTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBigDecimalTest.java @@ -1,136 +1,136 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.math.BigDecimal; -import java.text.DecimalFormatSymbols; -import java.util.Locale; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ParseBigDecimal processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseBigDecimalTest { - - private static final DecimalFormatSymbols FRENCH_SYMBOLS = new DecimalFormatSymbols(Locale.FRANCE); - private static final DecimalFormatSymbols ENGLISH_SYMBOLS = new DecimalFormatSymbols(Locale.ENGLISH); - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processor3; - private CellProcessor processorChain; - private CellProcessor processorChain2; - private CellProcessor processorChain3; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ParseBigDecimal(); - processor2 = new ParseBigDecimal(ENGLISH_SYMBOLS); - processor3 = new ParseBigDecimal(FRENCH_SYMBOLS); - processorChain = new ParseBigDecimal(new IdentityTransform()); - processorChain2 = new ParseBigDecimal(ENGLISH_SYMBOLS, new IdentityTransform()); - processorChain3 = new ParseBigDecimal(FRENCH_SYMBOLS, new IdentityTransform()); - } - - /** - * Test unchained/chained execution with a valid positive input. - */ - @Test - public void testValidInput() { - - String normalInput = "1357.459"; - String frenchInput = "1357,459"; - BigDecimal expectedOutput = new BigDecimal(normalInput); - - // normal input - assertEquals(expectedOutput, processor.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processor2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processorChain.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processorChain2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - - // french input ("," instead of "." as decimal symbol) - assertEquals(expectedOutput, processor3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processorChain3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Test unchained/chained execution with a valid negative input. - */ - @Test - public void testValidNegativeInput() { - - String normalInput = "-1357.459"; - String frenchInput = "-1357,459"; - BigDecimal expectedOutput = new BigDecimal(normalInput); - - // normal input - assertEquals(expectedOutput, processor.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processor2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processorChain.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processorChain2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); - - // french input ("," instead of "." as decimal symbol) - assertEquals(expectedOutput, processor3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedOutput, processorChain3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a non-String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonString() { - processor.execute(1234, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with an empty-String input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithEmptyString() { - processor.execute("", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with null symbols (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testWithNullSymbols() { - new ParseBigDecimal((DecimalFormatSymbols) null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.math.BigDecimal; +import java.text.DecimalFormatSymbols; +import java.util.Locale; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ParseBigDecimal processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseBigDecimalTest { + + private static final DecimalFormatSymbols FRENCH_SYMBOLS = new DecimalFormatSymbols(Locale.FRANCE); + private static final DecimalFormatSymbols ENGLISH_SYMBOLS = new DecimalFormatSymbols(Locale.ENGLISH); + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processor3; + private CellProcessor processorChain; + private CellProcessor processorChain2; + private CellProcessor processorChain3; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ParseBigDecimal(); + processor2 = new ParseBigDecimal(ENGLISH_SYMBOLS); + processor3 = new ParseBigDecimal(FRENCH_SYMBOLS); + processorChain = new ParseBigDecimal(new IdentityTransform()); + processorChain2 = new ParseBigDecimal(ENGLISH_SYMBOLS, new IdentityTransform()); + processorChain3 = new ParseBigDecimal(FRENCH_SYMBOLS, new IdentityTransform()); + } + + /** + * Test unchained/chained execution with a valid positive input. + */ + @Test + public void testValidInput() { + + String normalInput = "1357.459"; + String frenchInput = "1357,459"; + BigDecimal expectedOutput = new BigDecimal(normalInput); + + // normal input + assertEquals(expectedOutput, processor.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processor2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processorChain.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processorChain2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + + // french input ("," instead of "." as decimal symbol) + assertEquals(expectedOutput, processor3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processorChain3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Test unchained/chained execution with a valid negative input. + */ + @Test + public void testValidNegativeInput() { + + String normalInput = "-1357.459"; + String frenchInput = "-1357,459"; + BigDecimal expectedOutput = new BigDecimal(normalInput); + + // normal input + assertEquals(expectedOutput, processor.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processor2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processorChain.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processorChain2.execute(normalInput, ANONYMOUS_CSVCONTEXT)); + + // french input ("," instead of "." as decimal symbol) + assertEquals(expectedOutput, processor3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedOutput, processorChain3.execute(frenchInput, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a non-String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonString() { + processor.execute(1234, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with an empty-String input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithEmptyString() { + processor.execute("", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with null symbols (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testWithNullSymbols() { + new ParseBigDecimal((DecimalFormatSymbols) null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBoolTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBoolTest.java index 7b236de1..410df26b 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBoolTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseBoolTest.java @@ -1,170 +1,170 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ParseBool processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseBoolTest { - - private static final String TRUE_VALUE = "y"; - private static final String FALSE_VALUE = "n"; - private static final String[] DEFAULT_TRUE_VALUES = new String[] { "1", "true", "t", "y" }; - private static final String[] DEFAULT_FALSE_VALUES = new String[] { "0", "false", "f", "n" }; - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processor3; - private CellProcessor processorChain; - private CellProcessor processorChain2; - private CellProcessor processorChain3; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ParseBool(); - processor2 = new ParseBool(TRUE_VALUE, FALSE_VALUE); - processor3 = new ParseBool(new String[] { TRUE_VALUE }, new String[] { FALSE_VALUE }); - processorChain = new ParseBool(new IdentityTransform()); - processorChain2 = new ParseBool(TRUE_VALUE, FALSE_VALUE, new IdentityTransform()); - processorChain3 = new ParseBool(new String[] { TRUE_VALUE }, new String[] { FALSE_VALUE }, - new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid true/false values. - */ - @Test - public void testValidInput() { - - // processors using default true/false values - for( String trueValue : DEFAULT_TRUE_VALUES ) { - assertTrue((Boolean) processor.execute(trueValue, ANONYMOUS_CSVCONTEXT)); - assertTrue((Boolean) processorChain.execute(trueValue, ANONYMOUS_CSVCONTEXT)); - } - for( String falseValue : DEFAULT_FALSE_VALUES ) { - assertFalse((Boolean) processor.execute(falseValue, ANONYMOUS_CSVCONTEXT)); - assertFalse((Boolean) processorChain.execute(falseValue, ANONYMOUS_CSVCONTEXT)); - } - - // other processors with single supplied true/false values - assertTrue((Boolean) processor2.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); - assertTrue((Boolean) processor3.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); - assertTrue((Boolean) processorChain2.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); - assertTrue((Boolean) processorChain3.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); - assertFalse((Boolean) processor2.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); - assertFalse((Boolean) processor3.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); - assertFalse((Boolean) processorChain2.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); - assertFalse((Boolean) processorChain3.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); - - } - - /** - * Tests execution with an non-boolean String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonBooleanString() { - processor.execute("not a boolean!", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non-String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonString() { - processor.execute(1, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with an empty-String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithEmptyString() { - processor.execute("", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null true String (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullTrueString() { - new ParseBool((String) null, FALSE_VALUE); - } - - /** - * Tests construction with a null false String (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullFalseString() { - new ParseBool(TRUE_VALUE, (String) null); - } - - /** - * Tests construction with a null true array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullTrueArray() { - new ParseBool((String[]) null, new String[] { FALSE_VALUE }); - } - - /** - * Tests construction with a null false array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullFalseArray() { - new ParseBool(new String[] { TRUE_VALUE }, (String[]) null); - } - - /** - * Tests construction with an empty true array (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyTrueArray() { - new ParseBool(new String[] {}, new String[] { FALSE_VALUE }); - } - - /** - * Tests construction with an empty false array (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyFalseArray() { - new ParseBool(new String[] { TRUE_VALUE }, new String[] {}); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ParseBool processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseBoolTest { + + private static final String TRUE_VALUE = "y"; + private static final String FALSE_VALUE = "n"; + private static final String[] DEFAULT_TRUE_VALUES = new String[] { "1", "true", "t", "y" }; + private static final String[] DEFAULT_FALSE_VALUES = new String[] { "0", "false", "f", "n" }; + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processor3; + private CellProcessor processorChain; + private CellProcessor processorChain2; + private CellProcessor processorChain3; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ParseBool(); + processor2 = new ParseBool(TRUE_VALUE, FALSE_VALUE); + processor3 = new ParseBool(new String[] { TRUE_VALUE }, new String[] { FALSE_VALUE }); + processorChain = new ParseBool(new IdentityTransform()); + processorChain2 = new ParseBool(TRUE_VALUE, FALSE_VALUE, new IdentityTransform()); + processorChain3 = new ParseBool(new String[] { TRUE_VALUE }, new String[] { FALSE_VALUE }, + new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid true/false values. + */ + @Test + public void testValidInput() { + + // processors using default true/false values + for( String trueValue : DEFAULT_TRUE_VALUES ) { + assertTrue((Boolean) processor.execute(trueValue, ANONYMOUS_CSVCONTEXT)); + assertTrue((Boolean) processorChain.execute(trueValue, ANONYMOUS_CSVCONTEXT)); + } + for( String falseValue : DEFAULT_FALSE_VALUES ) { + assertFalse((Boolean) processor.execute(falseValue, ANONYMOUS_CSVCONTEXT)); + assertFalse((Boolean) processorChain.execute(falseValue, ANONYMOUS_CSVCONTEXT)); + } + + // other processors with single supplied true/false values + assertTrue((Boolean) processor2.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); + assertTrue((Boolean) processor3.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); + assertTrue((Boolean) processorChain2.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); + assertTrue((Boolean) processorChain3.execute(TRUE_VALUE, ANONYMOUS_CSVCONTEXT)); + assertFalse((Boolean) processor2.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); + assertFalse((Boolean) processor3.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); + assertFalse((Boolean) processorChain2.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); + assertFalse((Boolean) processorChain3.execute(FALSE_VALUE, ANONYMOUS_CSVCONTEXT)); + + } + + /** + * Tests execution with an non-boolean String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonBooleanString() { + processor.execute("not a boolean!", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non-String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonString() { + processor.execute(1, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with an empty-String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithEmptyString() { + processor.execute("", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null true String (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullTrueString() { + new ParseBool((String) null, FALSE_VALUE); + } + + /** + * Tests construction with a null false String (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullFalseString() { + new ParseBool(TRUE_VALUE, (String) null); + } + + /** + * Tests construction with a null true array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullTrueArray() { + new ParseBool((String[]) null, new String[] { FALSE_VALUE }); + } + + /** + * Tests construction with a null false array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullFalseArray() { + new ParseBool(new String[] { TRUE_VALUE }, (String[]) null); + } + + /** + * Tests construction with an empty true array (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyTrueArray() { + new ParseBool(new String[] {}, new String[] { FALSE_VALUE }); + } + + /** + * Tests construction with an empty false array (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyFalseArray() { + new ParseBool(new String[] { TRUE_VALUE }, new String[] {}); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseCharTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseCharTest.java index 598fc94b..41ab4c4d 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseCharTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseCharTest.java @@ -1,92 +1,92 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ParseChar processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseCharTest { - - private static final char CHAR = 'c'; - private static final String STRING = String.valueOf(CHAR); - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ParseChar(); - processorChain = new ParseChar(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a valid char input (should be returned unchanged). - */ - @Test - public void testValidChar() { - assertEquals(CHAR, processor.execute(CHAR, ANONYMOUS_CSVCONTEXT)); - assertEquals(CHAR, processorChain.execute(CHAR, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with a valid single-char String input. - */ - @Test - public void testStringWithSingleChar() { - assertEquals(CHAR, processor.execute(STRING, ANONYMOUS_CSVCONTEXT)); - assertEquals(CHAR, processorChain.execute(STRING, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with an multi-character String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithMultiCharString() { - processor.execute("cc", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non char input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonCharInput() { - processor.execute(1, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ParseChar processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseCharTest { + + private static final char CHAR = 'c'; + private static final String STRING = String.valueOf(CHAR); + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ParseChar(); + processorChain = new ParseChar(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a valid char input (should be returned unchanged). + */ + @Test + public void testValidChar() { + assertEquals(CHAR, processor.execute(CHAR, ANONYMOUS_CSVCONTEXT)); + assertEquals(CHAR, processorChain.execute(CHAR, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with a valid single-char String input. + */ + @Test + public void testStringWithSingleChar() { + assertEquals(CHAR, processor.execute(STRING, ANONYMOUS_CSVCONTEXT)); + assertEquals(CHAR, processorChain.execute(STRING, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with an multi-character String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithMultiCharString() { + processor.execute("cc", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non char input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonCharInput() { + processor.execute(1, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDateTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDateTest.java index ad76c966..abff0140 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDateTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDateTest.java @@ -1,159 +1,159 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; -import static org.supercsv.SuperCsvTestUtils.date; - -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ParseDate processor. As ParseDate uses the default locale, this test must be written in a locale - * independent way (so the test will pass). The test can be run in a different local by specifying the - * user.language and user.country JVM properties (i.e. -Duser.language=de -Duser.country=DE). - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseDateTest { - - private static final Date DATE = date(2011, 12, 25); - private static final String DATE_FORMAT = "dd/MM/yyyy"; - private static final String FORMATTED_DATE = "25/12/2011"; - private static final String DATE_FORMAT2 = "EEE, MMM d, ''yy"; - - // locale-independent ("Sun, Dec 25, '11" in en) - private static final String FORMATTED_DATE2 = new SimpleDateFormat(DATE_FORMAT2).format(DATE); - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processor3; - private CellProcessor processorChain; - private CellProcessor processorChain2; - private CellProcessor processorChain3; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ParseDate(DATE_FORMAT); - processor2 = new ParseDate(DATE_FORMAT, true); - processor3 = new ParseDate(DATE_FORMAT, false); - processorChain = new ParseDate(DATE_FORMAT, new IdentityTransform()); - processorChain2 = new ParseDate(DATE_FORMAT, true, new IdentityTransform()); - processorChain3 = new ParseDate(DATE_FORMAT, false, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with various date formats. - */ - @Test - public void testValidDate() { - // first date format - assertEquals(DATE, processor.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); - assertEquals(DATE, processor2.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); - assertEquals(DATE, processor3.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); - assertEquals(DATE, processorChain.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); - assertEquals(DATE, processorChain2.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); - assertEquals(DATE, processorChain3.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); - - } - - /** - * Tests unchained/chained execution with a different date format. - */ - @Test - public void testValidDateDifferentFormat() { - - final CellProcessor differentFormat = new ParseDate(DATE_FORMAT2); - final CellProcessor differentFormatChain = new ParseDate(DATE_FORMAT2, new IdentityTransform()); - - // try a different date format - assertEquals(DATE, differentFormat.execute(FORMATTED_DATE2, ANONYMOUS_CSVCONTEXT)); - assertEquals(DATE, differentFormatChain.execute(FORMATTED_DATE2, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with an invalid date (doesn't match format), should throw an exception. - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testBadlyFormattedDate() { - processor.execute("2011-12-25", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with an invalid date (matches format, but data invalid) and non-lenient processors (should throw - * an exception). - */ - @Test - public void testInvalidDateWithNonLenient() { - final String dodgyDate = "30/02/2012"; - for( final CellProcessor cp : Arrays.asList(processor, processor3, processorChain, processorChain3) ) { - try { - cp.execute(dodgyDate, ANONYMOUS_CSVCONTEXT); - fail("should have thrown a SuperCsvCellProcessorException"); - } - catch(SuperCsvCellProcessorException e) {} - } - } - - /** - * Tests execution with an invalid date (matches format, but data invalid) and lenient processors (should work!). - */ - @Test - public void testInvalidDateWithLenient() { - final String dodgyDate = "30/02/2012"; - final Date expectedDate = date(2012, 3, 1); - assertEquals(expectedDate, processor2.execute(dodgyDate, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedDate, processorChain2.execute(dodgyDate, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a non String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonCharInput() { - processor.execute(1, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null date format (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullDateFormat() { - new ParseDate(null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; +import static org.supercsv.SuperCsvTestUtils.date; + +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ParseDate processor. As ParseDate uses the default locale, this test must be written in a locale + * independent way (so the test will pass). The test can be run in a different local by specifying the + * user.language and user.country JVM properties (i.e. -Duser.language=de -Duser.country=DE). + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseDateTest { + + private static final Date DATE = date(2011, 12, 25); + private static final String DATE_FORMAT = "dd/MM/yyyy"; + private static final String FORMATTED_DATE = "25/12/2011"; + private static final String DATE_FORMAT2 = "EEE, MMM d, ''yy"; + + // locale-independent ("Sun, Dec 25, '11" in en) + private static final String FORMATTED_DATE2 = new SimpleDateFormat(DATE_FORMAT2).format(DATE); + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processor3; + private CellProcessor processorChain; + private CellProcessor processorChain2; + private CellProcessor processorChain3; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ParseDate(DATE_FORMAT); + processor2 = new ParseDate(DATE_FORMAT, true); + processor3 = new ParseDate(DATE_FORMAT, false); + processorChain = new ParseDate(DATE_FORMAT, new IdentityTransform()); + processorChain2 = new ParseDate(DATE_FORMAT, true, new IdentityTransform()); + processorChain3 = new ParseDate(DATE_FORMAT, false, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with various date formats. + */ + @Test + public void testValidDate() { + // first date format + assertEquals(DATE, processor.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); + assertEquals(DATE, processor2.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); + assertEquals(DATE, processor3.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); + assertEquals(DATE, processorChain.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); + assertEquals(DATE, processorChain2.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); + assertEquals(DATE, processorChain3.execute(FORMATTED_DATE, ANONYMOUS_CSVCONTEXT)); + + } + + /** + * Tests unchained/chained execution with a different date format. + */ + @Test + public void testValidDateDifferentFormat() { + + final CellProcessor differentFormat = new ParseDate(DATE_FORMAT2); + final CellProcessor differentFormatChain = new ParseDate(DATE_FORMAT2, new IdentityTransform()); + + // try a different date format + assertEquals(DATE, differentFormat.execute(FORMATTED_DATE2, ANONYMOUS_CSVCONTEXT)); + assertEquals(DATE, differentFormatChain.execute(FORMATTED_DATE2, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with an invalid date (doesn't match format), should throw an exception. + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testBadlyFormattedDate() { + processor.execute("2011-12-25", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with an invalid date (matches format, but data invalid) and non-lenient processors (should throw + * an exception). + */ + @Test + public void testInvalidDateWithNonLenient() { + final String dodgyDate = "30/02/2012"; + for( final CellProcessor cp : Arrays.asList(processor, processor3, processorChain, processorChain3) ) { + try { + cp.execute(dodgyDate, ANONYMOUS_CSVCONTEXT); + fail("should have thrown a SuperCsvCellProcessorException"); + } + catch(SuperCsvCellProcessorException e) {} + } + } + + /** + * Tests execution with an invalid date (matches format, but data invalid) and lenient processors (should work!). + */ + @Test + public void testInvalidDateWithLenient() { + final String dodgyDate = "30/02/2012"; + final Date expectedDate = date(2012, 3, 1); + assertEquals(expectedDate, processor2.execute(dodgyDate, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedDate, processorChain2.execute(dodgyDate, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a non String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonCharInput() { + processor.execute(1, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null date format (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullDateFormat() { + new ParseDate(null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDoubleTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDoubleTest.java index 14e9c498..da438dc3 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDoubleTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseDoubleTest.java @@ -1,104 +1,104 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ParseDouble processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseDoubleTest { - - private static final double POSITIVE_VAL = 17.3; - private static final String POSITIVE_STRING = "17.3"; - private static final double NEGATIVE_VAL = -43.0; - private static final String NEGATIVE_STRING = "-43.0"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ParseDouble(); - processorChain = new ParseDouble(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid doubles as input. - */ - @Test - public void testValidDoubles() { - // positive values - assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); - assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); - - // negative values - assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); - assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with valid double Strings as input. - */ - @Test - public void testValidDoubleStrings() { - // positive values - assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); - assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); - - // negative values - assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); - assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with an badly formatted String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithInvalidFormatString() { - processor.execute("123.45s", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non Double input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonDoubleInput() { - processor.execute(1, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ParseDouble processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseDoubleTest { + + private static final double POSITIVE_VAL = 17.3; + private static final String POSITIVE_STRING = "17.3"; + private static final double NEGATIVE_VAL = -43.0; + private static final String NEGATIVE_STRING = "-43.0"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ParseDouble(); + processorChain = new ParseDouble(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid doubles as input. + */ + @Test + public void testValidDoubles() { + // positive values + assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); + assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); + + // negative values + assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); + assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with valid double Strings as input. + */ + @Test + public void testValidDoubleStrings() { + // positive values + assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); + assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); + + // negative values + assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); + assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with an badly formatted String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithInvalidFormatString() { + processor.execute("123.45s", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non Double input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonDoubleInput() { + processor.execute(1, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseIntTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseIntTest.java index b316eebe..95e6f62a 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseIntTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseIntTest.java @@ -1,104 +1,104 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ParseInt processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseIntTest { - - private static final int POSITIVE_VAL = 17; - private static final String POSITIVE_STRING = "17"; - private static final int NEGATIVE_VAL = -43; - private static final String NEGATIVE_STRING = "-43"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ParseInt(); - processorChain = new ParseInt(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid ints as input. - */ - @Test - public void testValidInts() { - // positive values - assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); - assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); - - // negative values - assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); - assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with valid int Strings as input. - */ - @Test - public void testValidIntStrings() { - // positive values - assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); - assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); - - // negative values - assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); - assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with an badly formatted String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithInvalidFormatString() { - processor.execute("123.45", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non Integer input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonIntInput() { - processor.execute(1.23, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ParseInt processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseIntTest { + + private static final int POSITIVE_VAL = 17; + private static final String POSITIVE_STRING = "17"; + private static final int NEGATIVE_VAL = -43; + private static final String NEGATIVE_STRING = "-43"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ParseInt(); + processorChain = new ParseInt(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid ints as input. + */ + @Test + public void testValidInts() { + // positive values + assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); + assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); + + // negative values + assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); + assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with valid int Strings as input. + */ + @Test + public void testValidIntStrings() { + // positive values + assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); + assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); + + // negative values + assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); + assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with an badly formatted String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithInvalidFormatString() { + processor.execute("123.45", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non Integer input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonIntInput() { + processor.execute(1.23, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseLongTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseLongTest.java index be6f6b1b..110ab40c 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/ParseLongTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/ParseLongTest.java @@ -1,105 +1,105 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ParseLong processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ParseLongTest { - - private static final long POSITIVE_VAL = 1234567891011L; - private static final String POSITIVE_STRING = "1234567891011"; - private static final long NEGATIVE_VAL = -246810121416L; - private static final String NEGATIVE_STRING = "-246810121416"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ParseLong(); - processorChain = new ParseLong(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid longs as input. - */ - @Test - public void testValidLongs() { - - // positive values - assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); - assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); - - // negative values - assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); - assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with valid long Strings as input. - */ - @Test - public void testValidLongStrings() { - // positive values - assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); - assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); - - // negative values - assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); - assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with an badly formatted String input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithInvalidFormatString() { - processor.execute("123.45", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non Long input (should throw an exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonIntInput() { - processor.execute(1.23, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ParseLong processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ParseLongTest { + + private static final long POSITIVE_VAL = 1234567891011L; + private static final String POSITIVE_STRING = "1234567891011"; + private static final long NEGATIVE_VAL = -246810121416L; + private static final String NEGATIVE_STRING = "-246810121416"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ParseLong(); + processorChain = new ParseLong(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid longs as input. + */ + @Test + public void testValidLongs() { + + // positive values + assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); + assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_VAL, ANONYMOUS_CSVCONTEXT)); + + // negative values + assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); + assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_VAL, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with valid long Strings as input. + */ + @Test + public void testValidLongStrings() { + // positive values + assertEquals(POSITIVE_VAL, processor.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); + assertEquals(POSITIVE_VAL, processorChain.execute(POSITIVE_STRING, ANONYMOUS_CSVCONTEXT)); + + // negative values + assertEquals(NEGATIVE_VAL, processor.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); + assertEquals(NEGATIVE_VAL, processorChain.execute(NEGATIVE_STRING, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with an badly formatted String input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithInvalidFormatString() { + processor.execute("123.45", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non Long input (should throw an exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonIntInput() { + processor.execute(1.23, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/StrReplaceTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/StrReplaceTest.java index c51ac2f6..1f038bab 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/StrReplaceTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/StrReplaceTest.java @@ -1,114 +1,114 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.regex.PatternSyntaxException; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the StrReplace processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class StrReplaceTest { - - private static final String REGEX = "\\s+"; // whitespace - private static final String REPLACEMENT = "_"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new StrReplace(REGEX, REPLACEMENT); - processorChain = new StrReplace(REGEX, REPLACEMENT, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid input. - */ - @Test - public void testValidInput() { - String input = "This is a \tString with some \n whitespace"; - String expected = "This_is_a_String_with_some_whitespace"; - assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with non-String input (toString() is called first). - */ - @Test - public void testNonStringInput() { - StringBuilder input = new StringBuilder("This is a \tString with some \n whitespace"); // how lazy! - String expected = "This_is_a_String_with_some_whitespace"; - assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null regex (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testWithNullRegex() { - processor = new StrReplace(null, REPLACEMENT); - } - - /** - * Tests execution with a null replacement (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testWithNullReplacement() { - processor = new StrReplace(REGEX, null); - } - - /** - * Tests execution with an empty regex (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithEmptyRegex() { - processor = new StrReplace("", REPLACEMENT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = PatternSyntaxException.class) - public void testWithInvalidRegex() { - processor = new StrReplace("***", REPLACEMENT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.regex.PatternSyntaxException; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the StrReplace processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class StrReplaceTest { + + private static final String REGEX = "\\s+"; // whitespace + private static final String REPLACEMENT = "_"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new StrReplace(REGEX, REPLACEMENT); + processorChain = new StrReplace(REGEX, REPLACEMENT, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid input. + */ + @Test + public void testValidInput() { + String input = "This is a \tString with some \n whitespace"; + String expected = "This_is_a_String_with_some_whitespace"; + assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with non-String input (toString() is called first). + */ + @Test + public void testNonStringInput() { + StringBuilder input = new StringBuilder("This is a \tString with some \n whitespace"); // how lazy! + String expected = "This_is_a_String_with_some_whitespace"; + assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null regex (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testWithNullRegex() { + processor = new StrReplace(null, REPLACEMENT); + } + + /** + * Tests execution with a null replacement (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testWithNullReplacement() { + processor = new StrReplace(REGEX, null); + } + + /** + * Tests execution with an empty regex (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithEmptyRegex() { + processor = new StrReplace("", REPLACEMENT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = PatternSyntaxException.class) + public void testWithInvalidRegex() { + processor = new StrReplace("***", REPLACEMENT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/TokenTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/TokenTest.java index 2c0ef10a..e6bb191e 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/TokenTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/TokenTest.java @@ -1,94 +1,94 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the Token processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class TokenTest { - - private static final String TOKEN = "foo"; - private static final String REPLACEMENT = "bar"; - private static final int TOKEN2 = 2; - private static final String REPLACEMENT2 = "two"; - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - // foo -> bar - processor = new Token(TOKEN, REPLACEMENT); - processorChain = new Token(TOKEN, REPLACEMENT, new IdentityTransform()); - - // 2 -> two - processor2 = new Token(TOKEN2, REPLACEMENT2); - processorChain2 = new Token(TOKEN2, REPLACEMENT2, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid input. - */ - @Test - public void testValidInput() { - // string input - assertEquals(REPLACEMENT, processor.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); - assertEquals(REPLACEMENT, processorChain.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); - - // int input - assertEquals(REPLACEMENT2, processor2.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); - assertEquals(REPLACEMENT2, processorChain2.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution when the token is not found (should return input unchanged). - */ - @Test - public void testTokenNotFound() { - // expecting 'foo', not 2 - assertEquals(TOKEN2, processor.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); - assertEquals(TOKEN2, processorChain.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); - - // expecting 2, not 'foo' - assertEquals(TOKEN, processor2.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); - assertEquals(TOKEN, processorChain2.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the Token processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class TokenTest { + + private static final String TOKEN = "foo"; + private static final String REPLACEMENT = "bar"; + private static final int TOKEN2 = 2; + private static final String REPLACEMENT2 = "two"; + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + // foo -> bar + processor = new Token(TOKEN, REPLACEMENT); + processorChain = new Token(TOKEN, REPLACEMENT, new IdentityTransform()); + + // 2 -> two + processor2 = new Token(TOKEN2, REPLACEMENT2); + processorChain2 = new Token(TOKEN2, REPLACEMENT2, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid input. + */ + @Test + public void testValidInput() { + // string input + assertEquals(REPLACEMENT, processor.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); + assertEquals(REPLACEMENT, processorChain.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); + + // int input + assertEquals(REPLACEMENT2, processor2.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); + assertEquals(REPLACEMENT2, processorChain2.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution when the token is not found (should return input unchanged). + */ + @Test + public void testTokenNotFound() { + // expecting 'foo', not 2 + assertEquals(TOKEN2, processor.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); + assertEquals(TOKEN2, processorChain.execute(TOKEN2, ANONYMOUS_CSVCONTEXT)); + + // expecting 2, not 'foo' + assertEquals(TOKEN, processor2.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); + assertEquals(TOKEN, processorChain2.execute(TOKEN, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/TrimTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/TrimTest.java index f48117b1..28d1c909 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/TrimTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/TrimTest.java @@ -1,87 +1,87 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the Trim processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class TrimTest { - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new Trim(); - processorChain = new Trim(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with input containing no surrounding whitespace. - */ - @Test - public void testInputNoWhitespace() { - String input = "abc"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with input containing surrounding spaces. - */ - @Test - public void testInputSurroundingSpace() { - String input = " abc "; - String expected = "abc"; - assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with input containing surrounding whitespace. - */ - @Test - public void testInputSurroundingWhitespace() { - String input = "\tabc \n"; - String expected = "abc"; - assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the Trim processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class TrimTest { + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new Trim(); + processorChain = new Trim(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with input containing no surrounding whitespace. + */ + @Test + public void testInputNoWhitespace() { + String input = "abc"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with input containing surrounding spaces. + */ + @Test + public void testInputSurroundingSpace() { + String input = " abc "; + String expected = "abc"; + assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with input containing surrounding whitespace. + */ + @Test + public void testInputSurroundingWhitespace() { + String input = "\tabc \n"; + String expected = "abc"; + assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/TruncateTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/TruncateTest.java index 2dfacfea..525a7dff 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/TruncateTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/TruncateTest.java @@ -1,116 +1,116 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the Truncate processor. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class TruncateTest { - - private static final int MAX_SIZE = 3; - private static final String SUFFIX = "..."; - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new Truncate(MAX_SIZE); - processor2 = new Truncate(MAX_SIZE, SUFFIX); - processorChain = new Truncate(MAX_SIZE, new IdentityTransform()); - processorChain2 = new Truncate(MAX_SIZE, SUFFIX, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with input the same as the max size (no truncating!). - */ - @Test - public void testInputSameAsMax() { - String input = "abc"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processor2.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with input longer than the max size (truncating!). - */ - @Test - public void testInputLongerThanMax() { - String input = "abcd"; - String expected = "abc"; - String expectedSuffix = expected + "..."; - - // no suffix - assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - - // suffix - assertEquals(expectedSuffix, processor2.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expectedSuffix, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with an invalid max value (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithInvalidMax() { - processor = new Truncate(0); - } - - /** - * Tests execution with an invalid max value and chaining (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithInvalidMaxChained() { - processorChain = new Truncate(0, new IdentityTransform()); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null suffix String (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullSuffix() { - new Truncate(MAX_SIZE, (String) null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the Truncate processor. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class TruncateTest { + + private static final int MAX_SIZE = 3; + private static final String SUFFIX = "..."; + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new Truncate(MAX_SIZE); + processor2 = new Truncate(MAX_SIZE, SUFFIX); + processorChain = new Truncate(MAX_SIZE, new IdentityTransform()); + processorChain2 = new Truncate(MAX_SIZE, SUFFIX, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with input the same as the max size (no truncating!). + */ + @Test + public void testInputSameAsMax() { + String input = "abc"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processor2.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with input longer than the max size (truncating!). + */ + @Test + public void testInputLongerThanMax() { + String input = "abcd"; + String expected = "abc"; + String expectedSuffix = expected + "..."; + + // no suffix + assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + + // suffix + assertEquals(expectedSuffix, processor2.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expectedSuffix, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with an invalid max value (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithInvalidMax() { + processor = new Truncate(0); + } + + /** + * Tests execution with an invalid max value and chaining (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithInvalidMaxChained() { + processorChain = new Truncate(0, new IdentityTransform()); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null suffix String (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullSuffix() { + new Truncate(MAX_SIZE, (String) null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/DMinMaxTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/DMinMaxTest.java index 3611330e..73077eca 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/DMinMaxTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/DMinMaxTest.java @@ -1,108 +1,108 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the DMinMax constaint. - * - * @author James Bassett - */ -public class DMinMaxTest { - - private static final double MIN = -5; - private static final double MAX = 10; - private static final double IN_RANGE = 0; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new DMinMax(MIN, MAX); - processorChain = new DMinMax(MIN, MAX, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a valid Double. - */ - @Test - public void testValidDouble() { - assertEquals(IN_RANGE, processor.execute(IN_RANGE, ANONYMOUS_CSVCONTEXT)); - assertEquals(IN_RANGE, processorChain.execute(IN_RANGE, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with a valid String. - */ - @Test - public void testValidString() { - assertEquals(IN_RANGE, processor.execute(String.valueOf(IN_RANGE), ANONYMOUS_CSVCONTEXT)); - assertEquals(IN_RANGE, processorChain.execute(String.valueOf(IN_RANGE), ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests an input above the max. - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testAboveMax() { - processor.execute(11, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests an input below the min. - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testBelowMin() { - processor.execute(-6, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with invalid min/max values (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithMaxLessThanMin() { - new DMinMax(2, 1); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a non-Number input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonNumber() { - processor.execute("abc", ANONYMOUS_CSVCONTEXT); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the DMinMax constaint. + * + * @author James Bassett + */ +public class DMinMaxTest { + + private static final double MIN = -5; + private static final double MAX = 10; + private static final double IN_RANGE = 0; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new DMinMax(MIN, MAX); + processorChain = new DMinMax(MIN, MAX, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a valid Double. + */ + @Test + public void testValidDouble() { + assertEquals(IN_RANGE, processor.execute(IN_RANGE, ANONYMOUS_CSVCONTEXT)); + assertEquals(IN_RANGE, processorChain.execute(IN_RANGE, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with a valid String. + */ + @Test + public void testValidString() { + assertEquals(IN_RANGE, processor.execute(String.valueOf(IN_RANGE), ANONYMOUS_CSVCONTEXT)); + assertEquals(IN_RANGE, processorChain.execute(String.valueOf(IN_RANGE), ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests an input above the max. + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testAboveMax() { + processor.execute(11, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests an input below the min. + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testBelowMin() { + processor.execute(-6, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with invalid min/max values (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithMaxLessThanMin() { + new DMinMax(2, 1); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a non-Number input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonNumber() { + processor.execute("abc", ANONYMOUS_CSVCONTEXT); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/EqualsTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/EqualsTest.java index 2e19d668..3dd68cde 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/EqualsTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/EqualsTest.java @@ -1,109 +1,109 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the Equals constraint. - * - * @author James Bassett - */ -public class EqualsTest { - - private static final String EXPECTED_VALUE = "expected"; - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new Equals(); - processor2 = new Equals(EXPECTED_VALUE); - processorChain = new Equals(new IdentityTransform()); - processorChain2 = new Equals(EXPECTED_VALUE, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid (equal) input. The non-constant processors have their constant value - * loaded after the first execution (no check is done on the first execution), so the subsequent call should check - * against that value. - */ - @Test - public void testValidInput() { - assertEquals(EXPECTED_VALUE, processor.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - assertEquals(EXPECTED_VALUE, processor2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - assertEquals(EXPECTED_VALUE, processorChain.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - assertEquals(EXPECTED_VALUE, processorChain2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - - // repeat for the benefit of the 'non-constant' processors which will now check against the first value found - assertEquals(EXPECTED_VALUE, processor.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - assertEquals(EXPECTED_VALUE, processorChain.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - - // and check the 'constant' processors again, just for good measure - assertEquals(EXPECTED_VALUE, processor2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - assertEquals(EXPECTED_VALUE, processorChain2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null expected value and null input. - */ - @Test - public void testNullConstantWithNull() { - CellProcessor equalsWithNullConstant = new Equals((Object) null); - assertNull(equalsWithNullConstant.execute(null, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null expected value, but a non-null input (should throw an exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testNullConstantWithNonNull() { - CellProcessor equalsWithNullConstant = new Equals((Object) null); - equalsWithNullConstant.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests a value that's not equal to the first value encountered (should throw an exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testNotEqual() { - assertEquals(EXPECTED_VALUE, processor.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); - processor.execute("something else", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests a value that's not equal to the constant value (should throw an exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testNotEqualWithConstant() { - processor2.execute("something else", ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the Equals constraint. + * + * @author James Bassett + */ +public class EqualsTest { + + private static final String EXPECTED_VALUE = "expected"; + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new Equals(); + processor2 = new Equals(EXPECTED_VALUE); + processorChain = new Equals(new IdentityTransform()); + processorChain2 = new Equals(EXPECTED_VALUE, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid (equal) input. The non-constant processors have their constant value + * loaded after the first execution (no check is done on the first execution), so the subsequent call should check + * against that value. + */ + @Test + public void testValidInput() { + assertEquals(EXPECTED_VALUE, processor.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + assertEquals(EXPECTED_VALUE, processor2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + assertEquals(EXPECTED_VALUE, processorChain.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + assertEquals(EXPECTED_VALUE, processorChain2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + + // repeat for the benefit of the 'non-constant' processors which will now check against the first value found + assertEquals(EXPECTED_VALUE, processor.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + assertEquals(EXPECTED_VALUE, processorChain.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + + // and check the 'constant' processors again, just for good measure + assertEquals(EXPECTED_VALUE, processor2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + assertEquals(EXPECTED_VALUE, processorChain2.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null expected value and null input. + */ + @Test + public void testNullConstantWithNull() { + CellProcessor equalsWithNullConstant = new Equals((Object) null); + assertNull(equalsWithNullConstant.execute(null, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null expected value, but a non-null input (should throw an exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testNullConstantWithNonNull() { + CellProcessor equalsWithNullConstant = new Equals((Object) null); + equalsWithNullConstant.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests a value that's not equal to the first value encountered (should throw an exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testNotEqual() { + assertEquals(EXPECTED_VALUE, processor.execute(EXPECTED_VALUE, ANONYMOUS_CSVCONTEXT)); + processor.execute("something else", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests a value that's not equal to the constant value (should throw an exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testNotEqualWithConstant() { + processor2.execute("something else", ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/ForbidSubStrTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/ForbidSubStrTest.java index 378fe6e2..b92a8715 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/ForbidSubStrTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/ForbidSubStrTest.java @@ -1,140 +1,140 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the ForbidSubStr constraint. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class ForbidSubStrTest { - - private static final String FORBIDDEN = "C++"; - private static final String FORBIDDEN2 = "Microsoft"; - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processorChain; - private CellProcessor processorChain2; - private CellProcessor processorChain3; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new ForbidSubStr(Arrays.asList(FORBIDDEN, FORBIDDEN2)); - processor2 = new ForbidSubStr(FORBIDDEN, FORBIDDEN2); - processorChain = new ForbidSubStr(Arrays.asList(FORBIDDEN, FORBIDDEN2), new IdentityTransform()); - processorChain2 = new ForbidSubStr(FORBIDDEN, new IdentityTransform()); - processorChain3 = new ForbidSubStr(new String[] { FORBIDDEN, FORBIDDEN2 }, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a String that doesn't contain any forbidden Strings. - */ - @Test - public void testValidInput() { - String input = "I think Java is an awesome language"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processor2.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain3.execute(input, ANONYMOUS_CSVCONTEXT)); - - } - - /** - * Tests input that contains the first forbidden String (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testForbidden() { - String input = "I think C++ is an awesome language"; // blasphemy! - processor.execute(input, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests input that contains the second forbidden String (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testForbidden2() { - String input = "I love Microsoft"; - processor.execute(input, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullArray() { - new ForbidSubStr((String[]) null); - } - - /** - * Tests construction with an empty array (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyArray() { - new ForbidSubStr(new String[] {}); - } - - /** - * Tests construction with a null List (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullList() { - new ForbidSubStr((List) null, new IdentityTransform()); - } - - /** - * Tests construction with an empty List (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyList() { - new ForbidSubStr(new ArrayList(), new IdentityTransform()); - } - - /** - * Tests construction with a null array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullSubstring() { - new ForbidSubStr(new String[] { null }); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the ForbidSubStr constraint. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class ForbidSubStrTest { + + private static final String FORBIDDEN = "C++"; + private static final String FORBIDDEN2 = "Microsoft"; + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processorChain; + private CellProcessor processorChain2; + private CellProcessor processorChain3; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new ForbidSubStr(Arrays.asList(FORBIDDEN, FORBIDDEN2)); + processor2 = new ForbidSubStr(FORBIDDEN, FORBIDDEN2); + processorChain = new ForbidSubStr(Arrays.asList(FORBIDDEN, FORBIDDEN2), new IdentityTransform()); + processorChain2 = new ForbidSubStr(FORBIDDEN, new IdentityTransform()); + processorChain3 = new ForbidSubStr(new String[] { FORBIDDEN, FORBIDDEN2 }, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a String that doesn't contain any forbidden Strings. + */ + @Test + public void testValidInput() { + String input = "I think Java is an awesome language"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processor2.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain3.execute(input, ANONYMOUS_CSVCONTEXT)); + + } + + /** + * Tests input that contains the first forbidden String (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testForbidden() { + String input = "I think C++ is an awesome language"; // blasphemy! + processor.execute(input, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests input that contains the second forbidden String (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testForbidden2() { + String input = "I love Microsoft"; + processor.execute(input, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullArray() { + new ForbidSubStr((String[]) null); + } + + /** + * Tests construction with an empty array (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyArray() { + new ForbidSubStr(new String[] {}); + } + + /** + * Tests construction with a null List (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullList() { + new ForbidSubStr((List) null, new IdentityTransform()); + } + + /** + * Tests construction with an empty List (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyList() { + new ForbidSubStr(new ArrayList(), new IdentityTransform()); + } + + /** + * Tests construction with a null array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullSubstring() { + new ForbidSubStr(new String[] { null }); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/IsIncludedInTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/IsIncludedInTest.java index 1f9f2058..5d8a88e7 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/IsIncludedInTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/IsIncludedInTest.java @@ -1,137 +1,137 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the IsIncludedIn constraint. - * - * @author Dominique De Vito - * @author James Bassett - */ -public class IsIncludedInTest { - - private static final Set VALUE_SET = new HashSet(); - - private static final Integer ONE = 1; - private static final String TWO = "Two"; - private static final Double THREE = 3.0; - - static { - VALUE_SET.add(ONE); - VALUE_SET.add(TWO); - VALUE_SET.add(THREE); - } - - private CellProcessor processor; - private CellProcessor processor2; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new IsIncludedIn(VALUE_SET); - processor2 = new IsIncludedIn(VALUE_SET.toArray()); - processorChain = new IsIncludedIn(VALUE_SET, new IdentityTransform()); - processorChain2 = new IsIncludedIn(VALUE_SET.toArray(), new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with values from the Set. - */ - @Test - public void testValidInput() { - assertEquals(ONE, processor.execute(ONE, ANONYMOUS_CSVCONTEXT)); - assertEquals(ONE, processor2.execute(ONE, ANONYMOUS_CSVCONTEXT)); - assertEquals(ONE, processorChain.execute(ONE, ANONYMOUS_CSVCONTEXT)); - assertEquals(ONE, processorChain2.execute(ONE, ANONYMOUS_CSVCONTEXT)); - - assertEquals(TWO, processor.execute(TWO, ANONYMOUS_CSVCONTEXT)); - assertEquals(TWO, processor2.execute(TWO, ANONYMOUS_CSVCONTEXT)); - assertEquals(TWO, processorChain.execute(TWO, ANONYMOUS_CSVCONTEXT)); - assertEquals(TWO, processorChain2.execute(TWO, ANONYMOUS_CSVCONTEXT)); - - assertEquals(THREE, processor.execute(THREE, ANONYMOUS_CSVCONTEXT)); - assertEquals(THREE, processor2.execute(THREE, ANONYMOUS_CSVCONTEXT)); - assertEquals(THREE, processorChain.execute(THREE, ANONYMOUS_CSVCONTEXT)); - assertEquals(THREE, processorChain2.execute(THREE, ANONYMOUS_CSVCONTEXT)); - - } - - /** - * Tests execution with a value that's not in the Set (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testWithInvalidInput() { - processor.execute(4, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullArray() { - new IsIncludedIn((Object[]) null); - } - - /** - * Tests construction with an empty array (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyArray() { - new IsIncludedIn(new Object[] {}); - } - - /** - * Tests construction with a null Set (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullSet() { - new IsIncludedIn((Set) null); - } - - /** - * Tests construction with an empty Set (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptySet() { - new IsIncludedIn(new HashSet()); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the IsIncludedIn constraint. + * + * @author Dominique De Vito + * @author James Bassett + */ +public class IsIncludedInTest { + + private static final Set VALUE_SET = new HashSet(); + + private static final Integer ONE = 1; + private static final String TWO = "Two"; + private static final Double THREE = 3.0; + + static { + VALUE_SET.add(ONE); + VALUE_SET.add(TWO); + VALUE_SET.add(THREE); + } + + private CellProcessor processor; + private CellProcessor processor2; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new IsIncludedIn(VALUE_SET); + processor2 = new IsIncludedIn(VALUE_SET.toArray()); + processorChain = new IsIncludedIn(VALUE_SET, new IdentityTransform()); + processorChain2 = new IsIncludedIn(VALUE_SET.toArray(), new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with values from the Set. + */ + @Test + public void testValidInput() { + assertEquals(ONE, processor.execute(ONE, ANONYMOUS_CSVCONTEXT)); + assertEquals(ONE, processor2.execute(ONE, ANONYMOUS_CSVCONTEXT)); + assertEquals(ONE, processorChain.execute(ONE, ANONYMOUS_CSVCONTEXT)); + assertEquals(ONE, processorChain2.execute(ONE, ANONYMOUS_CSVCONTEXT)); + + assertEquals(TWO, processor.execute(TWO, ANONYMOUS_CSVCONTEXT)); + assertEquals(TWO, processor2.execute(TWO, ANONYMOUS_CSVCONTEXT)); + assertEquals(TWO, processorChain.execute(TWO, ANONYMOUS_CSVCONTEXT)); + assertEquals(TWO, processorChain2.execute(TWO, ANONYMOUS_CSVCONTEXT)); + + assertEquals(THREE, processor.execute(THREE, ANONYMOUS_CSVCONTEXT)); + assertEquals(THREE, processor2.execute(THREE, ANONYMOUS_CSVCONTEXT)); + assertEquals(THREE, processorChain.execute(THREE, ANONYMOUS_CSVCONTEXT)); + assertEquals(THREE, processorChain2.execute(THREE, ANONYMOUS_CSVCONTEXT)); + + } + + /** + * Tests execution with a value that's not in the Set (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testWithInvalidInput() { + processor.execute(4, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullArray() { + new IsIncludedIn((Object[]) null); + } + + /** + * Tests construction with an empty array (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyArray() { + new IsIncludedIn(new Object[] {}); + } + + /** + * Tests construction with a null Set (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullSet() { + new IsIncludedIn((Set) null); + } + + /** + * Tests construction with an empty Set (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptySet() { + new IsIncludedIn(new HashSet()); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/LMinMaxTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/LMinMaxTest.java index e66a8039..93dc1360 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/LMinMaxTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/LMinMaxTest.java @@ -1,132 +1,132 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; -import static org.supercsv.cellprocessor.constraint.LMinMax.MAX_INTEGER; -import static org.supercsv.cellprocessor.constraint.LMinMax.MIN_INTEGER; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the LMinMax constraint. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class LMinMaxTest { - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new LMinMax(MIN_INTEGER, MAX_INTEGER); - processorChain = new LMinMax(MIN_INTEGER, MAX_INTEGER, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a long in the range. - */ - @Test - public void testValidLong() { - long input = 123L; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with a long String in the range (should be converted to a Long). - */ - @Test - public void testValidLongString() { - String input = "123"; - Long expected = 123L; - assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with the minimum allowed value. - */ - @Test - public void testMinBoundary() { - long input = MIN_INTEGER; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with the maximum allowed value. - */ - @Test - public void testMaxBoundary() { - long input = MAX_INTEGER; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a value less than the minimum (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testLessThanMin() { - long lessThanMin = MIN_INTEGER - 1L; - processor.execute(lessThanMin, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a value greater than the maximum (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testGreaterThanMax() { - long greaterThanMax = MAX_INTEGER + 1L; - processor.execute(greaterThanMax, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a String that can't be parsed to a Long (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNonLongString() { - processor.execute("not long!", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a max < min (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithInvalidMaxMin() { - new LMinMax(MAX_INTEGER, MIN_INTEGER); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; +import static org.supercsv.cellprocessor.constraint.LMinMax.MAX_INTEGER; +import static org.supercsv.cellprocessor.constraint.LMinMax.MIN_INTEGER; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the LMinMax constraint. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class LMinMaxTest { + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new LMinMax(MIN_INTEGER, MAX_INTEGER); + processorChain = new LMinMax(MIN_INTEGER, MAX_INTEGER, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a long in the range. + */ + @Test + public void testValidLong() { + long input = 123L; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with a long String in the range (should be converted to a Long). + */ + @Test + public void testValidLongString() { + String input = "123"; + Long expected = 123L; + assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with the minimum allowed value. + */ + @Test + public void testMinBoundary() { + long input = MIN_INTEGER; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with the maximum allowed value. + */ + @Test + public void testMaxBoundary() { + long input = MAX_INTEGER; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a value less than the minimum (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testLessThanMin() { + long lessThanMin = MIN_INTEGER - 1L; + processor.execute(lessThanMin, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a value greater than the maximum (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testGreaterThanMax() { + long greaterThanMax = MAX_INTEGER + 1L; + processor.execute(greaterThanMax, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a String that can't be parsed to a Long (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNonLongString() { + processor.execute("not long!", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a max < min (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithInvalidMaxMin() { + new LMinMax(MAX_INTEGER, MIN_INTEGER); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/NotNullTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/NotNullTest.java index c75d2d8d..8973414d 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/NotNullTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/NotNullTest.java @@ -1,75 +1,75 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the NotNull constraint. - * - * @author Dominique De Vito - * @author James Bassett - */ -public class NotNullTest { - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new NotNull(); - processorChain = new NotNull(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a non-null value. - */ - @Test - public void testValidInput() { - String input = "not null!"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with a empty String. - */ - @Test - public void testEmptyString() { - String input = ""; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the NotNull constraint. + * + * @author Dominique De Vito + * @author James Bassett + */ +public class NotNullTest { + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new NotNull(); + processorChain = new NotNull(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a non-null value. + */ + @Test + public void testValidInput() { + String input = "not null!"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with a empty String. + */ + @Test + public void testEmptyString() { + String input = ""; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireHashCodeTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireHashCodeTest.java index e538fe6e..84d6570b 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireHashCodeTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireHashCodeTest.java @@ -1,101 +1,101 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the RequireHashCode constraint. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class RequireHashCodeTest { - - private static final String INPUT1 = "One"; - private static final String INPUT2 = "Two"; - private static final int HASH1 = INPUT1.hashCode(); - private static final int HASH2 = INPUT2.hashCode(); - - private CellProcessor processor; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new RequireHashCode(HASH1, HASH2); - processorChain = new RequireHashCode(HASH1, new IdentityTransform()); - processorChain2 = new RequireHashCode(new int[] { HASH1, HASH2 }, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid values. - */ - @Test - public void testValidInput() { - assertEquals(INPUT1, processor.execute(INPUT1, ANONYMOUS_CSVCONTEXT)); - assertEquals(INPUT1, processorChain.execute(INPUT1, ANONYMOUS_CSVCONTEXT)); - assertEquals(INPUT1, processorChain2.execute(INPUT1, ANONYMOUS_CSVCONTEXT)); - - assertEquals(INPUT2, processor.execute(INPUT2, ANONYMOUS_CSVCONTEXT)); - // 'processorChain' doesn't have a second value to test with - assertEquals(INPUT2, processorChain2.execute(INPUT2, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with input that doesn't match any of the hashcodes (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testInvalidInput() { - String input = "invalid"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullArray() { - new RequireHashCode((int[]) null); - } - - /** - * Tests construction with an empty array (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyArray() { - new RequireHashCode(new int[] {}); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the RequireHashCode constraint. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class RequireHashCodeTest { + + private static final String INPUT1 = "One"; + private static final String INPUT2 = "Two"; + private static final int HASH1 = INPUT1.hashCode(); + private static final int HASH2 = INPUT2.hashCode(); + + private CellProcessor processor; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new RequireHashCode(HASH1, HASH2); + processorChain = new RequireHashCode(HASH1, new IdentityTransform()); + processorChain2 = new RequireHashCode(new int[] { HASH1, HASH2 }, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid values. + */ + @Test + public void testValidInput() { + assertEquals(INPUT1, processor.execute(INPUT1, ANONYMOUS_CSVCONTEXT)); + assertEquals(INPUT1, processorChain.execute(INPUT1, ANONYMOUS_CSVCONTEXT)); + assertEquals(INPUT1, processorChain2.execute(INPUT1, ANONYMOUS_CSVCONTEXT)); + + assertEquals(INPUT2, processor.execute(INPUT2, ANONYMOUS_CSVCONTEXT)); + // 'processorChain' doesn't have a second value to test with + assertEquals(INPUT2, processorChain2.execute(INPUT2, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with input that doesn't match any of the hashcodes (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testInvalidInput() { + String input = "invalid"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullArray() { + new RequireHashCode((int[]) null); + } + + /** + * Tests construction with an empty array (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyArray() { + new RequireHashCode(new int[] {}); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireSubStrTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireSubStrTest.java index 2236149b..b92dc757 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireSubStrTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/RequireSubStrTest.java @@ -1,128 +1,128 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the RequireSubStr constraint. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class RequireSubStrTest { - - private static final String REQUIRED1 = "in"; - private static final String REQUIRED2 = "to"; - - private CellProcessor processor; - private CellProcessor processorChain; - private CellProcessor processorChain2; - private CellProcessor processorChain3; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new RequireSubStr(REQUIRED1, REQUIRED2); - processorChain = new RequireSubStr(Arrays.asList(REQUIRED1, REQUIRED2), new IdentityTransform()); - processorChain2 = new RequireSubStr(REQUIRED1, new IdentityTransform()); // only allows 1 substring - processorChain3 = new RequireSubStr(new String[] { REQUIRED1, REQUIRED2 }, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a String that contains all of the required substrings. - */ - @Test - public void testValidInput() { - String input = "to infinity and beyond!"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); // only has 1 substring - assertEquals(input, processorChain3.execute(input, ANONYMOUS_CSVCONTEXT)); - - } - - /** - * Tests input that doesn't contain any of the substrings (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testInvalidInput() { - String input = "no matches here"; - processor.execute(input, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullArray() { - new RequireSubStr((String[]) null); - } - - /** - * Tests construction with an empty array (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyArray() { - new RequireSubStr(new String[] {}); - } - - /** - * Tests construction with a null List (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullList() { - new RequireSubStr((List) null, new IdentityTransform()); - } - - /** - * Tests construction with an empty List (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyList() { - new RequireSubStr(new ArrayList(), new IdentityTransform()); - } - - /** - * Tests construction with a null array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullSubstring() { - new RequireSubStr(new String[] { null }); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the RequireSubStr constraint. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class RequireSubStrTest { + + private static final String REQUIRED1 = "in"; + private static final String REQUIRED2 = "to"; + + private CellProcessor processor; + private CellProcessor processorChain; + private CellProcessor processorChain2; + private CellProcessor processorChain3; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new RequireSubStr(REQUIRED1, REQUIRED2); + processorChain = new RequireSubStr(Arrays.asList(REQUIRED1, REQUIRED2), new IdentityTransform()); + processorChain2 = new RequireSubStr(REQUIRED1, new IdentityTransform()); // only allows 1 substring + processorChain3 = new RequireSubStr(new String[] { REQUIRED1, REQUIRED2 }, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a String that contains all of the required substrings. + */ + @Test + public void testValidInput() { + String input = "to infinity and beyond!"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); // only has 1 substring + assertEquals(input, processorChain3.execute(input, ANONYMOUS_CSVCONTEXT)); + + } + + /** + * Tests input that doesn't contain any of the substrings (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testInvalidInput() { + String input = "no matches here"; + processor.execute(input, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullArray() { + new RequireSubStr((String[]) null); + } + + /** + * Tests construction with an empty array (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyArray() { + new RequireSubStr(new String[] {}); + } + + /** + * Tests construction with a null List (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullList() { + new RequireSubStr((List) null, new IdentityTransform()); + } + + /** + * Tests construction with an empty List (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyList() { + new RequireSubStr(new ArrayList(), new IdentityTransform()); + } + + /** + * Tests construction with a null array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullSubstring() { + new RequireSubStr(new String[] { null }); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrMinMaxTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrMinMaxTest.java index efd0c062..32772d3a 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrMinMaxTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrMinMaxTest.java @@ -1,134 +1,134 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the StrMinMax constraint. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class StrMinMaxTest { - - private static final int MIN = 3; - private static final int MAX = 6; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new StrMinMax(MIN, MAX); - processorChain = new StrMinMax(MIN, MAX, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a String of valid length. - */ - @Test - public void testValidInput() { - String input = "valid"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with a Integer String of valid length (should be converted to a String). - */ - @Test - public void testValidIntegerString() { - Integer input = 1234; - String expected = "1234"; - assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with the minimum allowed length. - */ - @Test - public void testMinBoundary() { - String input = "123"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests unchained/chained execution with the maximum allowed length. - */ - @Test - public void testMaxBoundary() { - String input = "123456"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a length less than the minimum (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testLessThanMin() { - String input = "12"; - processor.execute(input, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a length greater than the maximum (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testGreaterThanMax() { - String input = "1234567"; - processor.execute(input, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a min < 0(should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithNegativeMin() { - new StrMinMax(-1, MAX); - } - - /** - * Tests execution with a max < min (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithInvalidMaxMin() { - new StrMinMax(MAX, MIN); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the StrMinMax constraint. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class StrMinMaxTest { + + private static final int MIN = 3; + private static final int MAX = 6; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new StrMinMax(MIN, MAX); + processorChain = new StrMinMax(MIN, MAX, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a String of valid length. + */ + @Test + public void testValidInput() { + String input = "valid"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with a Integer String of valid length (should be converted to a String). + */ + @Test + public void testValidIntegerString() { + Integer input = 1234; + String expected = "1234"; + assertEquals(expected, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(expected, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with the minimum allowed length. + */ + @Test + public void testMinBoundary() { + String input = "123"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests unchained/chained execution with the maximum allowed length. + */ + @Test + public void testMaxBoundary() { + String input = "123456"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a length less than the minimum (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testLessThanMin() { + String input = "12"; + processor.execute(input, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a length greater than the maximum (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testGreaterThanMax() { + String input = "1234567"; + processor.execute(input, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a min < 0(should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithNegativeMin() { + new StrMinMax(-1, MAX); + } + + /** + * Tests execution with a max < min (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithInvalidMaxMin() { + new StrMinMax(MAX, MIN); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmptyTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmptyTest.java index b92daaaa..c8fc3f87 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmptyTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrNotNullOrEmptyTest.java @@ -1,83 +1,83 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the StrNotNullOrEmpty constraint. - * - * @author Dominique De Vito - * @author James Bassett - */ -public class StrNotNullOrEmptyTest { - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new StrNotNullOrEmpty(); - processorChain = new StrNotNullOrEmpty(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a non-null/empty value. - */ - @Test - public void testValidInput() { - String input = "not null or empty!"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a empty String (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testEmptyString() { - String input = ""; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with a non-String input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testNonStringInput() { - processor.execute(123, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the StrNotNullOrEmpty constraint. + * + * @author Dominique De Vito + * @author James Bassett + */ +public class StrNotNullOrEmptyTest { + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new StrNotNullOrEmpty(); + processorChain = new StrNotNullOrEmpty(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a non-null/empty value. + */ + @Test + public void testValidInput() { + String input = "not null or empty!"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a empty String (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testEmptyString() { + String input = ""; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with a non-String input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testNonStringInput() { + processor.execute(123, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrRegExTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrRegExTest.java index 3894f041..df8d84c4 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrRegExTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrRegExTest.java @@ -1,131 +1,131 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.regex.PatternSyntaxException; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the StrRegEx constraint. - * - * @author James Bassett - */ -public class StrRegExTest { - - private static final String REGEX = "\\$[0-9]+\\.[0-9]{2}"; - private static final String MSG = "Must be a valid dollar amount, e.g. $123.45"; - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new StrRegEx(REGEX); - processorChain = new StrRegEx(REGEX, new IdentityTransform()); - StrRegEx.registerMessage(REGEX, MSG); - } - - /** - * Tests unchained/chained execution with a String matching the regex. - */ - @Test - public void testValidInput() { - String input = "$123.45"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - /** - * Tests execution with input that doesn't match the regex. - */ - @Test - public void testInvalidInput() { - String input = "12345"; - try { - processor.execute(input, ANONYMOUS_CSVCONTEXT); - fail("should have thrown SuperCsvConstraintViolationException"); - } - catch(SuperCsvConstraintViolationException e) { - // exception msg should contain registered message - assertTrue(e.getMessage().contains(MSG)); - } - } - - /** - * Tests execution with input that doesn't match the regex (and no message is registered). - */ - @Test - public void testInvalidInputWithNoMessage() { - processor = new StrRegEx("\\s"); // only whitespace - String input = "12345"; - try { - processor.execute(input, ANONYMOUS_CSVCONTEXT); - fail("should have thrown SuperCsvConstraintViolationException"); - } - catch(SuperCsvConstraintViolationException e) { - // exception msg should not contain the registered message (it's a different regex) - assertFalse(e.getMessage().contains(MSG)); - } - } - - /** - * Tests construction of the processor with a null regex (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testWithNullRegex() { - new StrRegEx(null); - } - - /** - * Tests construction of the processor with an empty regex (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testWithEmptyRegex() { - new StrRegEx(""); - } - - /** - * Tests construction of the processor with an invalid regex (should throw an Exception). - */ - @Test(expected = PatternSyntaxException.class) - public void testWithInvalidRegex() { - new StrRegEx("*****"); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.regex.PatternSyntaxException; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the StrRegEx constraint. + * + * @author James Bassett + */ +public class StrRegExTest { + + private static final String REGEX = "\\$[0-9]+\\.[0-9]{2}"; + private static final String MSG = "Must be a valid dollar amount, e.g. $123.45"; + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new StrRegEx(REGEX); + processorChain = new StrRegEx(REGEX, new IdentityTransform()); + StrRegEx.registerMessage(REGEX, MSG); + } + + /** + * Tests unchained/chained execution with a String matching the regex. + */ + @Test + public void testValidInput() { + String input = "$123.45"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + /** + * Tests execution with input that doesn't match the regex. + */ + @Test + public void testInvalidInput() { + String input = "12345"; + try { + processor.execute(input, ANONYMOUS_CSVCONTEXT); + fail("should have thrown SuperCsvConstraintViolationException"); + } + catch(SuperCsvConstraintViolationException e) { + // exception msg should contain registered message + assertTrue(e.getMessage().contains(MSG)); + } + } + + /** + * Tests execution with input that doesn't match the regex (and no message is registered). + */ + @Test + public void testInvalidInputWithNoMessage() { + processor = new StrRegEx("\\s"); // only whitespace + String input = "12345"; + try { + processor.execute(input, ANONYMOUS_CSVCONTEXT); + fail("should have thrown SuperCsvConstraintViolationException"); + } + catch(SuperCsvConstraintViolationException e) { + // exception msg should not contain the registered message (it's a different regex) + assertFalse(e.getMessage().contains(MSG)); + } + } + + /** + * Tests construction of the processor with a null regex (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testWithNullRegex() { + new StrRegEx(null); + } + + /** + * Tests construction of the processor with an empty regex (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testWithEmptyRegex() { + new StrRegEx(""); + } + + /** + * Tests construction of the processor with an invalid regex (should throw an Exception). + */ + @Test(expected = PatternSyntaxException.class) + public void testWithInvalidRegex() { + new StrRegEx("*****"); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrlenTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrlenTest.java index 224c3dfa..2f04b6bc 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrlenTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/StrlenTest.java @@ -1,110 +1,110 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.SuperCsvTestUtils; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the Strlen constraint. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class StrlenTest { - - private static final int LENGTH1 = 2; - private static final int LENGTH2 = 3; - - private CellProcessor processor; - private CellProcessor processorChain; - private CellProcessor processorChain2; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new Strlen(LENGTH1, LENGTH2); - processorChain = new Strlen(LENGTH1, new IdentityTransform()); // only allows 1 length - processorChain2 = new Strlen(new int[] { LENGTH1, LENGTH2 }, new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with inputs of valid lengths. - */ - @Test - public void testValidInput() { - String input = "OK"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); - - input = "yep"; - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - // skip 'processorChain' as it only has 1 valid length - assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); - - } - - /** - * Tests execution with an input with an unexpected length (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testInvalidInput() { - processor.execute("four", SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction of the processor with a negative length (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testNegativeLength() { - new Strlen(-1); - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests construction with a null array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructionWithNullArray() { - new Strlen((int[]) null); - } - - /** - * Tests construction with an empty array (should throw an Exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructionWithEmptyArray() { - new Strlen(new int[] {}); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.SuperCsvTestUtils; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the Strlen constraint. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class StrlenTest { + + private static final int LENGTH1 = 2; + private static final int LENGTH2 = 3; + + private CellProcessor processor; + private CellProcessor processorChain; + private CellProcessor processorChain2; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new Strlen(LENGTH1, LENGTH2); + processorChain = new Strlen(LENGTH1, new IdentityTransform()); // only allows 1 length + processorChain2 = new Strlen(new int[] { LENGTH1, LENGTH2 }, new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with inputs of valid lengths. + */ + @Test + public void testValidInput() { + String input = "OK"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); + + input = "yep"; + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + // skip 'processorChain' as it only has 1 valid length + assertEquals(input, processorChain2.execute(input, ANONYMOUS_CSVCONTEXT)); + + } + + /** + * Tests execution with an input with an unexpected length (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testInvalidInput() { + processor.execute("four", SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction of the processor with a negative length (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testNegativeLength() { + new Strlen(-1); + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests construction with a null array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructionWithNullArray() { + new Strlen((int[]) null); + } + + /** + * Tests construction with an empty array (should throw an Exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testConstructionWithEmptyArray() { + new Strlen(new int[] {}); + } +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueHashCodeTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueHashCodeTest.java index 0dde7a5f..c9526c98 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueHashCodeTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueHashCodeTest.java @@ -1,125 +1,125 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; -import org.supercsv.mock.PersonBean; - -/** - * Tests the UniqueHashCode constraint. - * - * @author James Bassett - */ -public class UniqueHashCodeTest { - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new UniqueHashCode(); - processorChain = new UniqueHashCode(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with a String inputs that have different hash codes. - */ - @Test - public void testValidStringInput() { - for( String input : Arrays.asList("a", "b", "c", "d", "A", "B", "C", "D") ) { - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - } - - /** - * Tests unchained/chained execution with a Object inputs that have different hash codes. - */ - @Test - public void testValidObjectInput() { - - PersonBean p1 = new PersonBean(); - p1.setFirstName("Neo"); - PersonBean p2 = new PersonBean(); - p2.setFirstName("Trinity"); - PersonBean p3 = new PersonBean(); - p3.setFirstName("Morpheus"); - PersonBean p4 = new PersonBean(); - p4.setFirstName("Switch"); - - for( PersonBean input : Arrays.asList(p1, p2, p3, p4) ) { - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - } - - /** - * Tests execution with String inputs that have the same hash code (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testInvalidStringInput() { - assertEquals("a", processor.execute("a", ANONYMOUS_CSVCONTEXT)); - assertEquals("b", processor.execute("b", ANONYMOUS_CSVCONTEXT)); - assertEquals("c", processor.execute("c", ANONYMOUS_CSVCONTEXT)); - processor.execute("b", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests execution with Object inputs that have the same hash code (should throw an Exception). - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testInvalidObjectInput() { - - PersonBean p1 = new PersonBean(); - p1.setFirstName("Neo"); - PersonBean p2 = new PersonBean(); - p2.setFirstName("Trinity"); - PersonBean p3 = new PersonBean(); - p3.setFirstName("Morpheus"); - PersonBean p4 = new PersonBean(); - p4.setFirstName("Neo"); // invalid! there's only one 'one'! - - assertEquals(p1, processor.execute(p1, ANONYMOUS_CSVCONTEXT)); - assertEquals(p2, processor.execute(p2, ANONYMOUS_CSVCONTEXT)); - assertEquals(p3, processor.execute(p3, ANONYMOUS_CSVCONTEXT)); - processor.execute(p4, ANONYMOUS_CSVCONTEXT); - - } - - /** - * Tests execution with a null input (should throw an Exception). - */ - @Test(expected = SuperCsvCellProcessorException.class) - public void testWithNull() { - processor.execute(null, ANONYMOUS_CSVCONTEXT); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; +import org.supercsv.mock.PersonBean; + +/** + * Tests the UniqueHashCode constraint. + * + * @author James Bassett + */ +public class UniqueHashCodeTest { + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new UniqueHashCode(); + processorChain = new UniqueHashCode(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with a String inputs that have different hash codes. + */ + @Test + public void testValidStringInput() { + for( String input : Arrays.asList("a", "b", "c", "d", "A", "B", "C", "D") ) { + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + } + + /** + * Tests unchained/chained execution with a Object inputs that have different hash codes. + */ + @Test + public void testValidObjectInput() { + + PersonBean p1 = new PersonBean(); + p1.setFirstName("Neo"); + PersonBean p2 = new PersonBean(); + p2.setFirstName("Trinity"); + PersonBean p3 = new PersonBean(); + p3.setFirstName("Morpheus"); + PersonBean p4 = new PersonBean(); + p4.setFirstName("Switch"); + + for( PersonBean input : Arrays.asList(p1, p2, p3, p4) ) { + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + } + + /** + * Tests execution with String inputs that have the same hash code (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testInvalidStringInput() { + assertEquals("a", processor.execute("a", ANONYMOUS_CSVCONTEXT)); + assertEquals("b", processor.execute("b", ANONYMOUS_CSVCONTEXT)); + assertEquals("c", processor.execute("c", ANONYMOUS_CSVCONTEXT)); + processor.execute("b", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests execution with Object inputs that have the same hash code (should throw an Exception). + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testInvalidObjectInput() { + + PersonBean p1 = new PersonBean(); + p1.setFirstName("Neo"); + PersonBean p2 = new PersonBean(); + p2.setFirstName("Trinity"); + PersonBean p3 = new PersonBean(); + p3.setFirstName("Morpheus"); + PersonBean p4 = new PersonBean(); + p4.setFirstName("Neo"); // invalid! there's only one 'one'! + + assertEquals(p1, processor.execute(p1, ANONYMOUS_CSVCONTEXT)); + assertEquals(p2, processor.execute(p2, ANONYMOUS_CSVCONTEXT)); + assertEquals(p3, processor.execute(p3, ANONYMOUS_CSVCONTEXT)); + processor.execute(p4, ANONYMOUS_CSVCONTEXT); + + } + + /** + * Tests execution with a null input (should throw an Exception). + */ + @Test(expected = SuperCsvCellProcessorException.class) + public void testWithNull() { + processor.execute(null, ANONYMOUS_CSVCONTEXT); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueTest.java b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueTest.java index 1c48805a..dd671ca3 100644 --- a/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueTest.java +++ b/super-csv/src/test/java/org/supercsv/cellprocessor/constraint/UniqueTest.java @@ -1,91 +1,91 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.cellprocessor.constraint; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvConstraintViolationException; -import org.supercsv.mock.IdentityTransform; - -/** - * Tests the Unique constraint. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class UniqueTest { - - private CellProcessor processor; - private CellProcessor processorChain; - - /** - * Sets up the processors for the test using all constructor combinations. - */ - @Before - public void setUp() { - processor = new Unique(); - processorChain = new Unique(new IdentityTransform()); - } - - /** - * Tests unchained/chained execution with valid (unique) String input. - */ - @Test - public void testValidStringInput() { - for( String input : Arrays.asList("1", "2", "3", "4", "5") ) { - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - } - - /** - * Tests unchained/chained execution with valid (unique) Integer input. - */ - @Test - public void testValidIntegerInput() { - for( Integer input : Arrays.asList(1, 2, 3, 4, 5) ) { - assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); - assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); - } - - } - - /** - * Tests invalid (non-unique) String input. - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testInvalidStringInput() { - assertEquals("duplicate", processor.execute("duplicate", ANONYMOUS_CSVCONTEXT)); - processor.execute("duplicate", ANONYMOUS_CSVCONTEXT); - } - - /** - * Tests invalid (non-unique) Integer input. - */ - @Test(expected = SuperCsvConstraintViolationException.class) - public void testInvalidIntegerInput() { - assertEquals(Integer.valueOf(99), processor.execute(Integer.valueOf(99), ANONYMOUS_CSVCONTEXT)); - processor.execute(Integer.valueOf(99), ANONYMOUS_CSVCONTEXT); - - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.cellprocessor.constraint; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvConstraintViolationException; +import org.supercsv.mock.IdentityTransform; + +/** + * Tests the Unique constraint. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class UniqueTest { + + private CellProcessor processor; + private CellProcessor processorChain; + + /** + * Sets up the processors for the test using all constructor combinations. + */ + @Before + public void setUp() { + processor = new Unique(); + processorChain = new Unique(new IdentityTransform()); + } + + /** + * Tests unchained/chained execution with valid (unique) String input. + */ + @Test + public void testValidStringInput() { + for( String input : Arrays.asList("1", "2", "3", "4", "5") ) { + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + } + + /** + * Tests unchained/chained execution with valid (unique) Integer input. + */ + @Test + public void testValidIntegerInput() { + for( Integer input : Arrays.asList(1, 2, 3, 4, 5) ) { + assertEquals(input, processor.execute(input, ANONYMOUS_CSVCONTEXT)); + assertEquals(input, processorChain.execute(input, ANONYMOUS_CSVCONTEXT)); + } + + } + + /** + * Tests invalid (non-unique) String input. + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testInvalidStringInput() { + assertEquals("duplicate", processor.execute("duplicate", ANONYMOUS_CSVCONTEXT)); + processor.execute("duplicate", ANONYMOUS_CSVCONTEXT); + } + + /** + * Tests invalid (non-unique) Integer input. + */ + @Test(expected = SuperCsvConstraintViolationException.class) + public void testInvalidIntegerInput() { + assertEquals(Integer.valueOf(99), processor.execute(Integer.valueOf(99), ANONYMOUS_CSVCONTEXT)); + processor.execute(Integer.valueOf(99), ANONYMOUS_CSVCONTEXT); + + } +} diff --git a/super-csv/src/test/java/org/supercsv/example/Day.java b/super-csv/src/test/java/org/supercsv/example/Day.java index 67832c63..24072bd0 100644 --- a/super-csv/src/test/java/org/supercsv/example/Day.java +++ b/super-csv/src/test/java/org/supercsv/example/Day.java @@ -1,23 +1,23 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.example; - -/** - * An enumeration of days. - */ -public enum Day { - MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.example; + +/** + * An enumeration of days. + */ +public enum Day { + MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY +} diff --git a/super-csv/src/test/java/org/supercsv/example/ParseDay.java b/super-csv/src/test/java/org/supercsv/example/ParseDay.java index 9b319680..ebafa22e 100644 --- a/super-csv/src/test/java/org/supercsv/example/ParseDay.java +++ b/super-csv/src/test/java/org/supercsv/example/ParseDay.java @@ -1,50 +1,50 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.example; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvCellProcessorException; -import org.supercsv.util.CsvContext; - -/** - * An example of a custom cell processor. - */ -public class ParseDay extends CellProcessorAdaptor { - - public ParseDay() { - super(); - } - - public ParseDay(CellProcessor next) { - // this constructor allows other processors to be chained after ParseDay - super(next); - } - - public Object execute(Object value, CsvContext context) { - - validateInputNotNull(value, context); // throws an Exception if the input is null - - for( Day day : Day.values() ) { - if( day.name().equalsIgnoreCase(value.toString()) ) { - // passes the Day enum to the next processor in the chain - return next.execute(day, context); - } - } - - throw new SuperCsvCellProcessorException(String.format("Could not parse '%s' as a day", value), context, this); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.example; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvCellProcessorException; +import org.supercsv.util.CsvContext; + +/** + * An example of a custom cell processor. + */ +public class ParseDay extends CellProcessorAdaptor { + + public ParseDay() { + super(); + } + + public ParseDay(CellProcessor next) { + // this constructor allows other processors to be chained after ParseDay + super(next); + } + + public Object execute(Object value, CsvContext context) { + + validateInputNotNull(value, context); // throws an Exception if the input is null + + for( Day day : Day.values() ) { + if( day.name().equalsIgnoreCase(value.toString()) ) { + // passes the Day enum to the next processor in the chain + return next.execute(day, context); + } + } + + throw new SuperCsvCellProcessorException(String.format("Could not parse '%s' as a day", value), context, this); + } +} diff --git a/super-csv/src/test/java/org/supercsv/example/Reading.java b/super-csv/src/test/java/org/supercsv/example/Reading.java index 7ef34ab5..672cf5e0 100644 --- a/super-csv/src/test/java/org/supercsv/example/Reading.java +++ b/super-csv/src/test/java/org/supercsv/example/Reading.java @@ -1,228 +1,228 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.example; - -import java.io.FileReader; -import java.util.List; -import java.util.Map; - -import org.supercsv.cellprocessor.Optional; -import org.supercsv.cellprocessor.ParseBool; -import org.supercsv.cellprocessor.ParseDate; -import org.supercsv.cellprocessor.ParseInt; -import org.supercsv.cellprocessor.constraint.LMinMax; -import org.supercsv.cellprocessor.constraint.NotNull; -import org.supercsv.cellprocessor.constraint.StrRegEx; -import org.supercsv.cellprocessor.constraint.UniqueHashCode; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.io.CsvBeanReader; -import org.supercsv.io.CsvListReader; -import org.supercsv.io.CsvMapReader; -import org.supercsv.io.ICsvBeanReader; -import org.supercsv.io.ICsvListReader; -import org.supercsv.io.ICsvMapReader; -import org.supercsv.mock.CustomerBean; -import org.supercsv.prefs.CsvPreference; - -/** - * Examples of reading CSV files. - */ -public class Reading { - - private static final String CSV_FILENAME = "src/test/resources/customers.csv"; - - public static void main(String[] args) throws Exception { - readWithCsvBeanReader(); - readWithCsvListReader(); - readWithCsvMapReader(); - partialReadWithCsvBeanReader(); - partialReadWithCsvMapReader(); - } - - /** - * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. Empty - * columns are read as null (hence the NotNull() for mandatory columns). - * - * @return the cell processors - */ - private static CellProcessor[] getProcessors() { - - final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust! - StrRegEx.registerMessage(emailRegex, "must be a valid email address"); - - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) - new NotNull(), // firstName - new NotNull(), // lastName - new ParseDate("dd/MM/yyyy"), // birthDate - new NotNull(), // mailingAddress - new Optional(new ParseBool()), // married - new Optional(new ParseInt()), // numberOfKids - new NotNull(), // favouriteQuote - new StrRegEx(emailRegex), // email - new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints - }; - - return processors; - } - - /** - * An example of reading using CsvBeanReader. - */ - private static void readWithCsvBeanReader() throws Exception { - - ICsvBeanReader beanReader = null; - try { - beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - // the header elements are used to map the values to the bean (names must match) - final String[] header = beanReader.getHeader(true); - final CellProcessor[] processors = getProcessors(); - - CustomerBean customer; - while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), - beanReader.getRowNumber(), customer)); - } - - } - finally { - if( beanReader != null ) { - beanReader.close(); - } - } - } - - /** - * An example of reading using CsvListReader. - */ - private static void readWithCsvListReader() throws Exception { - - ICsvListReader listReader = null; - try { - listReader = new CsvListReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - listReader.getHeader(true); // skip the header (can't be used with CsvListReader) - final CellProcessor[] processors = getProcessors(); - - List customerList; - while( (customerList = listReader.read(processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customerList=%s", listReader.getLineNumber(), - listReader.getRowNumber(), customerList)); - } - - } - finally { - if( listReader != null ) { - listReader.close(); - } - } - } - - /** - * An example of reading using CsvMapReader. - */ - private static void readWithCsvMapReader() throws Exception { - - ICsvMapReader mapReader = null; - try { - mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - // the header columns are used as the keys to the Map - final String[] header = mapReader.getHeader(true); - final CellProcessor[] processors = getProcessors(); - - Map customerMap; - while( (customerMap = mapReader.read(header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), - mapReader.getRowNumber(), customerMap)); - } - - } - finally { - if( mapReader != null ) { - mapReader.close(); - } - } - } - - /** - * An example of partial reading using CsvBeanReader. - */ - private static void partialReadWithCsvBeanReader() throws Exception { - - ICsvBeanReader beanReader = null; - try { - beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - beanReader.getHeader(true); // skip past the header (we're defining our own) - - // only map the first 3 columns - setting header elements to null means those columns are ignored - final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, - null, null }; - - // no processing required for ignored columns - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), null, null, null, null, null, null, null }; - - CustomerBean customer; - while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), - beanReader.getRowNumber(), customer)); - } - - } - finally { - if( beanReader != null ) { - beanReader.close(); - } - } - } - - /** - * An example of partial reading using CsvMapReader. - */ - private static void partialReadWithCsvMapReader() throws Exception { - - ICsvMapReader mapReader = null; - try { - mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); - - mapReader.getHeader(true); // skip past the header (we're defining our own) - - // only map the first 3 columns - setting header elements to null means those columns are ignored - final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, - null, null }; - - // apply some constraints to ignored columns (just because we can) - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new NotNull(), new NotNull(), new Optional(), new Optional(), new NotNull(), - new NotNull(), new LMinMax(0L, LMinMax.MAX_LONG) }; - - Map customerMap; - while( (customerMap = mapReader.read(header, processors)) != null ) { - System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), - mapReader.getRowNumber(), customerMap)); - } - - } - finally { - if( mapReader != null ) { - mapReader.close(); - } - } - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.example; + +import java.io.FileReader; +import java.util.List; +import java.util.Map; + +import org.supercsv.cellprocessor.Optional; +import org.supercsv.cellprocessor.ParseBool; +import org.supercsv.cellprocessor.ParseDate; +import org.supercsv.cellprocessor.ParseInt; +import org.supercsv.cellprocessor.constraint.LMinMax; +import org.supercsv.cellprocessor.constraint.NotNull; +import org.supercsv.cellprocessor.constraint.StrRegEx; +import org.supercsv.cellprocessor.constraint.UniqueHashCode; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.io.CsvBeanReader; +import org.supercsv.io.CsvListReader; +import org.supercsv.io.CsvMapReader; +import org.supercsv.io.ICsvBeanReader; +import org.supercsv.io.ICsvListReader; +import org.supercsv.io.ICsvMapReader; +import org.supercsv.mock.CustomerBean; +import org.supercsv.prefs.CsvPreference; + +/** + * Examples of reading CSV files. + */ +public class Reading { + + private static final String CSV_FILENAME = "src/test/resources/customers.csv"; + + public static void main(String[] args) throws Exception { + readWithCsvBeanReader(); + readWithCsvListReader(); + readWithCsvMapReader(); + partialReadWithCsvBeanReader(); + partialReadWithCsvMapReader(); + } + + /** + * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. Empty + * columns are read as null (hence the NotNull() for mandatory columns). + * + * @return the cell processors + */ + private static CellProcessor[] getProcessors() { + + final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust! + StrRegEx.registerMessage(emailRegex, "must be a valid email address"); + + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) + new NotNull(), // firstName + new NotNull(), // lastName + new ParseDate("dd/MM/yyyy"), // birthDate + new NotNull(), // mailingAddress + new Optional(new ParseBool()), // married + new Optional(new ParseInt()), // numberOfKids + new NotNull(), // favouriteQuote + new StrRegEx(emailRegex), // email + new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints + }; + + return processors; + } + + /** + * An example of reading using CsvBeanReader. + */ + private static void readWithCsvBeanReader() throws Exception { + + ICsvBeanReader beanReader = null; + try { + beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + // the header elements are used to map the values to the bean (names must match) + final String[] header = beanReader.getHeader(true); + final CellProcessor[] processors = getProcessors(); + + CustomerBean customer; + while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), + beanReader.getRowNumber(), customer)); + } + + } + finally { + if( beanReader != null ) { + beanReader.close(); + } + } + } + + /** + * An example of reading using CsvListReader. + */ + private static void readWithCsvListReader() throws Exception { + + ICsvListReader listReader = null; + try { + listReader = new CsvListReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + listReader.getHeader(true); // skip the header (can't be used with CsvListReader) + final CellProcessor[] processors = getProcessors(); + + List customerList; + while( (customerList = listReader.read(processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customerList=%s", listReader.getLineNumber(), + listReader.getRowNumber(), customerList)); + } + + } + finally { + if( listReader != null ) { + listReader.close(); + } + } + } + + /** + * An example of reading using CsvMapReader. + */ + private static void readWithCsvMapReader() throws Exception { + + ICsvMapReader mapReader = null; + try { + mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + // the header columns are used as the keys to the Map + final String[] header = mapReader.getHeader(true); + final CellProcessor[] processors = getProcessors(); + + Map customerMap; + while( (customerMap = mapReader.read(header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), + mapReader.getRowNumber(), customerMap)); + } + + } + finally { + if( mapReader != null ) { + mapReader.close(); + } + } + } + + /** + * An example of partial reading using CsvBeanReader. + */ + private static void partialReadWithCsvBeanReader() throws Exception { + + ICsvBeanReader beanReader = null; + try { + beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + beanReader.getHeader(true); // skip past the header (we're defining our own) + + // only map the first 3 columns - setting header elements to null means those columns are ignored + final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, + null, null }; + + // no processing required for ignored columns + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), null, null, null, null, null, null, null }; + + CustomerBean customer; + while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(), + beanReader.getRowNumber(), customer)); + } + + } + finally { + if( beanReader != null ) { + beanReader.close(); + } + } + } + + /** + * An example of partial reading using CsvMapReader. + */ + private static void partialReadWithCsvMapReader() throws Exception { + + ICsvMapReader mapReader = null; + try { + mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); + + mapReader.getHeader(true); // skip past the header (we're defining our own) + + // only map the first 3 columns - setting header elements to null means those columns are ignored + final String[] header = new String[] { "customerNo", "firstName", "lastName", null, null, null, null, null, + null, null }; + + // apply some constraints to ignored columns (just because we can) + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new NotNull(), new NotNull(), new Optional(), new Optional(), new NotNull(), + new NotNull(), new LMinMax(0L, LMinMax.MAX_LONG) }; + + Map customerMap; + while( (customerMap = mapReader.read(header, processors)) != null ) { + System.out.println(String.format("lineNo=%s, rowNo=%s, customerMap=%s", mapReader.getLineNumber(), + mapReader.getRowNumber(), customerMap)); + } + + } + finally { + if( mapReader != null ) { + mapReader.close(); + } + } + } + +} diff --git a/super-csv/src/test/java/org/supercsv/example/Writing.java b/super-csv/src/test/java/org/supercsv/example/Writing.java index 31b5923a..0c067ed7 100644 --- a/super-csv/src/test/java/org/supercsv/example/Writing.java +++ b/super-csv/src/test/java/org/supercsv/example/Writing.java @@ -1,343 +1,343 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.example; - -import java.io.FileWriter; -import java.util.Arrays; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.supercsv.cellprocessor.ConvertNullTo; -import org.supercsv.cellprocessor.FmtBool; -import org.supercsv.cellprocessor.FmtDate; -import org.supercsv.cellprocessor.Optional; -import org.supercsv.cellprocessor.constraint.LMinMax; -import org.supercsv.cellprocessor.constraint.NotNull; -import org.supercsv.cellprocessor.constraint.UniqueHashCode; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.io.CsvBeanWriter; -import org.supercsv.io.CsvListWriter; -import org.supercsv.io.CsvMapWriter; -import org.supercsv.io.ICsvBeanWriter; -import org.supercsv.io.ICsvListWriter; -import org.supercsv.io.ICsvMapWriter; -import org.supercsv.mock.CustomerBean; -import org.supercsv.prefs.CsvPreference; - -/** - * Examples of writing CSV files. - */ -public class Writing { - - public static void main(String[] args) throws Exception { - writeWithCsvBeanWriter(); - writeWithCsvListWriter(); - writeWithCsvMapWriter(); - partialWriteWithCsvBeanWriter(); - partialWriteWithCsvListWriter(); - partialWriteWithCsvMapWriter(); - } - - /** - * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. All values - * are converted to Strings before writing (there's no need to convert them), and null values will be written as - * empty columns (no need to convert them to ""). - * - * @return the cell processors - */ - private static CellProcessor[] getProcessors() { - - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) - new NotNull(), // firstName - new NotNull(), // lastName - new FmtDate("dd/MM/yyyy"), // birthDate - new NotNull(), // mailingAddress - new Optional(new FmtBool("Y", "N")), // married - new Optional(), // numberOfKids - new NotNull(), // favouriteQuote - new NotNull(), // email - new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints - }; - - return processors; - } - - /** - * An example of writing using CsvBeanWriter. - */ - private static void writeWithCsvBeanWriter() throws Exception { - - // create the customer beans - final CustomerBean john = new CustomerBean("1", "John", "Dunbar", - new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), - "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, - "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); - final CustomerBean bob = new CustomerBean("2", "Bob", "Down", - new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), - "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, - "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); - final List customers = Arrays.asList(john, bob); - - ICsvBeanWriter beanWriter = null; - try { - beanWriter = new CsvBeanWriter(new FileWriter("target/writeWithCsvBeanWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // the header elements are used to map the bean values to each column (names must match) - final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", - "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; - final CellProcessor[] processors = getProcessors(); - - // write the header - beanWriter.writeHeader(header); - - // write the beans - for( final CustomerBean customer : customers ) { - beanWriter.write(customer, header, processors); - } - - } - finally { - if( beanWriter != null ) { - beanWriter.close(); - } - } - } - - /** - * An example of reading using CsvListWriter. - */ - private static void writeWithCsvListWriter() throws Exception { - - // create the customer Lists (CsvListWriter also accepts arrays!) - final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar", - new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), - "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, - "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L }); - - final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", - new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), - "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, - "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L }); - - ICsvListWriter listWriter = null; - try { - listWriter = new CsvListWriter(new FileWriter("target/writeWithCsvListWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - final CellProcessor[] processors = getProcessors(); - final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", - "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; - - // write the header - listWriter.writeHeader(header); - - // write the customer lists - listWriter.write(john, processors); - listWriter.write(bob, processors); - - } - finally { - if( listWriter != null ) { - listWriter.close(); - } - } - } - - /** - * An example of reading using CsvMapWriter. - */ - private static void writeWithCsvMapWriter() throws Exception { - - final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress", - "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; - - // create the customer Maps (using the header elements for the column keys) - final Map john = new HashMap(); - john.put(header[0], "1"); - john.put(header[1], "John"); - john.put(header[2], "Dunbar"); - john.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTime()); - john.put(header[4], "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States"); - john.put(header[5], null); - john.put(header[6], null); - john.put(header[7], "\"May the Force be with you.\" - Star Wars"); - john.put(header[8], "jdunbar@gmail.com"); - john.put(header[9], 0L); - - final Map bob = new HashMap(); - bob.put(header[0], "2"); - bob.put(header[1], "Bob"); - bob.put(header[2], "Down"); - bob.put(header[3], new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime()); - bob.put(header[4], "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States"); - bob.put(header[5], true); - bob.put(header[6], 0); - bob.put(header[7], "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind"); - bob.put(header[8], "bobdown@hotmail.com"); - bob.put(header[9], 123456L); - - ICsvMapWriter mapWriter = null; - try { - mapWriter = new CsvMapWriter(new FileWriter("target/writeWithCsvMapWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - final CellProcessor[] processors = getProcessors(); - - // write the header - mapWriter.writeHeader(header); - - // write the customer maps - mapWriter.write(john, header, processors); - mapWriter.write(bob, header, processors); - - } - finally { - if( mapWriter != null ) { - mapWriter.close(); - } - } - } - - /** - * An example of partial reading using CsvBeanWriter. - */ - private static void partialWriteWithCsvBeanWriter() throws Exception { - - // create the customer beans - final CustomerBean john = new CustomerBean("1", "John", "Dunbar", - new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), - "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, - "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); - final CustomerBean bob = new CustomerBean("2", "Bob", "Down", - new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), - "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, - "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); - final List customers = Arrays.asList(john, bob); - - ICsvBeanWriter beanWriter = null; - try { - beanWriter = new CsvBeanWriter(new FileWriter("target/partialWriteWithCsvBeanWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // only map 5 of the 10 fields - final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; - - // assign a default value for married (if null), and write numberOfKids as an empty column if null - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; - - // write the header - beanWriter.writeHeader(header); - - // write the customer beans - for( final CustomerBean customer : customers ) { - beanWriter.write(customer, header, processors); - } - - } - finally { - if( beanWriter != null ) { - beanWriter.close(); - } - } - } - - /** - * An example of partial reading using CsvListWriter. - */ - private static void partialWriteWithCsvListWriter() throws Exception { - - final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; - - // create the customer Lists (CsvListWriter also accepts arrays!) - final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar",null, null}); - final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", true, 0 }); - - ICsvListWriter listWriter = null; - try { - listWriter = new CsvListWriter(new FileWriter("target/partialWriteWithCsvListWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // assign a default value for married (if null), and write numberOfKids as an empty column if null - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; - - // write the header - listWriter.writeHeader(header); - - // write the customer Lists - listWriter.write(john, processors); - listWriter.write(bob, processors); - - } - finally { - if( listWriter != null ) { - listWriter.close(); - } - } - } - - /** - * An example of partial reading using CsvMapWriter. - */ - private static void partialWriteWithCsvMapWriter() throws Exception { - - final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; - - // create the customer Maps (using the header elements for the column keys) - final Map john = new HashMap(); - john.put(header[0], "1"); - john.put(header[1], "John"); - john.put(header[2], "Dunbar"); - john.put(header[3], null); - john.put(header[4], null); - - final Map bob = new HashMap(); - bob.put(header[0], "2"); - bob.put(header[1], "Bob"); - bob.put(header[2], "Down"); - bob.put(header[3], true); - bob.put(header[4], 0); - - ICsvMapWriter mapWriter = null; - try { - mapWriter = new CsvMapWriter(new FileWriter("target/partialWriteWithCsvMapWriter.csv"), - CsvPreference.STANDARD_PREFERENCE); - - // assign a default value for married (if null), and write numberOfKids as an empty column if null - final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), - new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), null }; - - // write the header - mapWriter.writeHeader(header); - - // write the customer Maps - mapWriter.write(john, header, processors); - mapWriter.write(bob, header, processors); - - } - finally { - if( mapWriter != null ) { - mapWriter.close(); - } - } - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.example; + +import java.io.FileWriter; +import java.util.Arrays; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.supercsv.cellprocessor.ConvertNullTo; +import org.supercsv.cellprocessor.FmtBool; +import org.supercsv.cellprocessor.FmtDate; +import org.supercsv.cellprocessor.Optional; +import org.supercsv.cellprocessor.constraint.LMinMax; +import org.supercsv.cellprocessor.constraint.NotNull; +import org.supercsv.cellprocessor.constraint.UniqueHashCode; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.io.CsvBeanWriter; +import org.supercsv.io.CsvListWriter; +import org.supercsv.io.CsvMapWriter; +import org.supercsv.io.ICsvBeanWriter; +import org.supercsv.io.ICsvListWriter; +import org.supercsv.io.ICsvMapWriter; +import org.supercsv.mock.CustomerBean; +import org.supercsv.prefs.CsvPreference; + +/** + * Examples of writing CSV files. + */ +public class Writing { + + public static void main(String[] args) throws Exception { + writeWithCsvBeanWriter(); + writeWithCsvListWriter(); + writeWithCsvMapWriter(); + partialWriteWithCsvBeanWriter(); + partialWriteWithCsvListWriter(); + partialWriteWithCsvMapWriter(); + } + + /** + * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. All values + * are converted to Strings before writing (there's no need to convert them), and null values will be written as + * empty columns (no need to convert them to ""). + * + * @return the cell processors + */ + private static CellProcessor[] getProcessors() { + + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) + new NotNull(), // firstName + new NotNull(), // lastName + new FmtDate("dd/MM/yyyy"), // birthDate + new NotNull(), // mailingAddress + new Optional(new FmtBool("Y", "N")), // married + new Optional(), // numberOfKids + new NotNull(), // favouriteQuote + new NotNull(), // email + new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints + }; + + return processors; + } + + /** + * An example of writing using CsvBeanWriter. + */ + private static void writeWithCsvBeanWriter() throws Exception { + + // create the customer beans + final CustomerBean john = new CustomerBean("1", "John", "Dunbar", + new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), + "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, + "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); + final CustomerBean bob = new CustomerBean("2", "Bob", "Down", + new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), + "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, + "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); + final List customers = Arrays.asList(john, bob); + + ICsvBeanWriter beanWriter = null; + try { + beanWriter = new CsvBeanWriter(new FileWriter("target/writeWithCsvBeanWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // the header elements are used to map the bean values to each column (names must match) + final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", + "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; + final CellProcessor[] processors = getProcessors(); + + // write the header + beanWriter.writeHeader(header); + + // write the beans + for( final CustomerBean customer : customers ) { + beanWriter.write(customer, header, processors); + } + + } + finally { + if( beanWriter != null ) { + beanWriter.close(); + } + } + } + + /** + * An example of reading using CsvListWriter. + */ + private static void writeWithCsvListWriter() throws Exception { + + // create the customer Lists (CsvListWriter also accepts arrays!) + final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar", + new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), + "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, + "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L }); + + final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", + new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), + "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, + "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L }); + + ICsvListWriter listWriter = null; + try { + listWriter = new CsvListWriter(new FileWriter("target/writeWithCsvListWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + final CellProcessor[] processors = getProcessors(); + final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", + "mailingAddress", "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; + + // write the header + listWriter.writeHeader(header); + + // write the customer lists + listWriter.write(john, processors); + listWriter.write(bob, processors); + + } + finally { + if( listWriter != null ) { + listWriter.close(); + } + } + } + + /** + * An example of reading using CsvMapWriter. + */ + private static void writeWithCsvMapWriter() throws Exception { + + final String[] header = new String[] { "customerNo", "firstName", "lastName", "birthDate", "mailingAddress", + "married", "numberOfKids", "favouriteQuote", "email", "loyaltyPoints" }; + + // create the customer Maps (using the header elements for the column keys) + final Map john = new HashMap(); + john.put(header[0], "1"); + john.put(header[1], "John"); + john.put(header[2], "Dunbar"); + john.put(header[3], new GregorianCalendar(1945, Calendar.JUNE, 13).getTime()); + john.put(header[4], "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States"); + john.put(header[5], null); + john.put(header[6], null); + john.put(header[7], "\"May the Force be with you.\" - Star Wars"); + john.put(header[8], "jdunbar@gmail.com"); + john.put(header[9], 0L); + + final Map bob = new HashMap(); + bob.put(header[0], "2"); + bob.put(header[1], "Bob"); + bob.put(header[2], "Down"); + bob.put(header[3], new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime()); + bob.put(header[4], "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States"); + bob.put(header[5], true); + bob.put(header[6], 0); + bob.put(header[7], "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind"); + bob.put(header[8], "bobdown@hotmail.com"); + bob.put(header[9], 123456L); + + ICsvMapWriter mapWriter = null; + try { + mapWriter = new CsvMapWriter(new FileWriter("target/writeWithCsvMapWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + final CellProcessor[] processors = getProcessors(); + + // write the header + mapWriter.writeHeader(header); + + // write the customer maps + mapWriter.write(john, header, processors); + mapWriter.write(bob, header, processors); + + } + finally { + if( mapWriter != null ) { + mapWriter.close(); + } + } + } + + /** + * An example of partial reading using CsvBeanWriter. + */ + private static void partialWriteWithCsvBeanWriter() throws Exception { + + // create the customer beans + final CustomerBean john = new CustomerBean("1", "John", "Dunbar", + new GregorianCalendar(1945, Calendar.JUNE, 13).getTime(), + "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States", null, null, + "\"May the Force be with you.\" - Star Wars", "jdunbar@gmail.com", 0L); + final CustomerBean bob = new CustomerBean("2", "Bob", "Down", + new GregorianCalendar(1919, Calendar.FEBRUARY, 25).getTime(), + "1601 Willow Rd.\nMenlo Park, CA 94025\nUnited States", true, 0, + "\"Frankly, my dear, I don't give a damn.\" - Gone With The Wind", "bobdown@hotmail.com", 123456L); + final List customers = Arrays.asList(john, bob); + + ICsvBeanWriter beanWriter = null; + try { + beanWriter = new CsvBeanWriter(new FileWriter("target/partialWriteWithCsvBeanWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // only map 5 of the 10 fields + final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; + + // assign a default value for married (if null), and write numberOfKids as an empty column if null + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; + + // write the header + beanWriter.writeHeader(header); + + // write the customer beans + for( final CustomerBean customer : customers ) { + beanWriter.write(customer, header, processors); + } + + } + finally { + if( beanWriter != null ) { + beanWriter.close(); + } + } + } + + /** + * An example of partial reading using CsvListWriter. + */ + private static void partialWriteWithCsvListWriter() throws Exception { + + final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; + + // create the customer Lists (CsvListWriter also accepts arrays!) + final List john = Arrays.asList(new Object[] { "1", "John", "Dunbar",null, null}); + final List bob = Arrays.asList(new Object[] { "2", "Bob", "Down", true, 0 }); + + ICsvListWriter listWriter = null; + try { + listWriter = new CsvListWriter(new FileWriter("target/partialWriteWithCsvListWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // assign a default value for married (if null), and write numberOfKids as an empty column if null + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), new Optional() }; + + // write the header + listWriter.writeHeader(header); + + // write the customer Lists + listWriter.write(john, processors); + listWriter.write(bob, processors); + + } + finally { + if( listWriter != null ) { + listWriter.close(); + } + } + } + + /** + * An example of partial reading using CsvMapWriter. + */ + private static void partialWriteWithCsvMapWriter() throws Exception { + + final String[] header = new String[] { "customerNo", "firstName", "lastName", "married", "numberOfKids" }; + + // create the customer Maps (using the header elements for the column keys) + final Map john = new HashMap(); + john.put(header[0], "1"); + john.put(header[1], "John"); + john.put(header[2], "Dunbar"); + john.put(header[3], null); + john.put(header[4], null); + + final Map bob = new HashMap(); + bob.put(header[0], "2"); + bob.put(header[1], "Bob"); + bob.put(header[2], "Down"); + bob.put(header[3], true); + bob.put(header[4], 0); + + ICsvMapWriter mapWriter = null; + try { + mapWriter = new CsvMapWriter(new FileWriter("target/partialWriteWithCsvMapWriter.csv"), + CsvPreference.STANDARD_PREFERENCE); + + // assign a default value for married (if null), and write numberOfKids as an empty column if null + final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), new NotNull(), + new NotNull(), new ConvertNullTo("no response", new FmtBool("yes", "no")), null }; + + // write the header + mapWriter.writeHeader(header); + + // write the customer Maps + mapWriter.write(john, header, processors); + mapWriter.write(bob, header, processors); + + } + finally { + if( mapWriter != null ) { + mapWriter.close(); + } + } + } + +} diff --git a/super-csv/src/test/java/org/supercsv/exception/SuperCsvCellProcessorExceptionTest.java b/super-csv/src/test/java/org/supercsv/exception/SuperCsvCellProcessorExceptionTest.java index 7ddca377..8446adbf 100644 --- a/super-csv/src/test/java/org/supercsv/exception/SuperCsvCellProcessorExceptionTest.java +++ b/super-csv/src/test/java/org/supercsv/exception/SuperCsvCellProcessorExceptionTest.java @@ -1,108 +1,108 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.mock.IdentityTransform; -import org.supercsv.util.CsvContext; - -/** - * Tests the SuperCsvCellProcessorException class. - * - * @author James Bassett - */ -public class SuperCsvCellProcessorExceptionTest { - - private static final String MSG = "Cell processing failed!"; - private static final Throwable THROWABLE = new RuntimeException("I'm the cause of the problem"); - private static final CellProcessor PROCESSOR = new IdentityTransform(); - - /** - * Tests the first constructor. - */ - @Test - public void testConstuctor1() { - SuperCsvCellProcessorException e = new SuperCsvCellProcessorException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR); - assertEquals(MSG, e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - assertEquals(PROCESSOR, e.getProcessor()); - e.printStackTrace(); - - // test with null values - e = new SuperCsvCellProcessorException(null, (CsvContext) null, (CellProcessor) null); - assertNull(e.getMessage()); - assertNull(e.getCsvContext()); - assertNull(e.getProcessor()); - e.printStackTrace(); - } - - /** - * Tests the second constructor. - */ - @Test - public void testConstuctor2() { - SuperCsvCellProcessorException e = new SuperCsvCellProcessorException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR, THROWABLE); - assertEquals(MSG, e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - assertEquals(PROCESSOR, e.getProcessor()); - assertEquals(THROWABLE, e.getCause()); - e.printStackTrace(); - - // test with null values - e = new SuperCsvCellProcessorException(null, null, null, (Throwable) null); - assertNull(e.getMessage()); - assertNull(e.getCsvContext()); - assertNull(e.getProcessor()); - assertNull(e.getCause()); - e.printStackTrace(); - } - - /** - * Tests the second constructor. - */ - @Test - public void testConstuctor3() { - - // actual value not null - SuperCsvCellProcessorException e = new SuperCsvCellProcessorException(String.class, 123, ANONYMOUS_CSVCONTEXT, PROCESSOR); - assertEquals("the input value should be of type java.lang.String but is java.lang.Integer", e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - assertEquals(PROCESSOR, e.getProcessor()); - e.printStackTrace(); - - // null actual value - e = new SuperCsvCellProcessorException(String.class, null, ANONYMOUS_CSVCONTEXT, PROCESSOR); - assertEquals("the input value should be of type java.lang.String but is null", e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - assertEquals(PROCESSOR, e.getProcessor()); - e.printStackTrace(); - - // test with null values - try { - new SuperCsvCellProcessorException(null, null, null, (CellProcessor) null); - fail("should have thrown NullPointerException"); - } catch (NullPointerException npe){ - assertEquals("expectedType should not be null", npe.getMessage()); - } - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.mock.IdentityTransform; +import org.supercsv.util.CsvContext; + +/** + * Tests the SuperCsvCellProcessorException class. + * + * @author James Bassett + */ +public class SuperCsvCellProcessorExceptionTest { + + private static final String MSG = "Cell processing failed!"; + private static final Throwable THROWABLE = new RuntimeException("I'm the cause of the problem"); + private static final CellProcessor PROCESSOR = new IdentityTransform(); + + /** + * Tests the first constructor. + */ + @Test + public void testConstuctor1() { + SuperCsvCellProcessorException e = new SuperCsvCellProcessorException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR); + assertEquals(MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(PROCESSOR, e.getProcessor()); + e.printStackTrace(); + + // test with null values + e = new SuperCsvCellProcessorException(null, (CsvContext) null, (CellProcessor) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + assertNull(e.getProcessor()); + e.printStackTrace(); + } + + /** + * Tests the second constructor. + */ + @Test + public void testConstuctor2() { + SuperCsvCellProcessorException e = new SuperCsvCellProcessorException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR, THROWABLE); + assertEquals(MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(PROCESSOR, e.getProcessor()); + assertEquals(THROWABLE, e.getCause()); + e.printStackTrace(); + + // test with null values + e = new SuperCsvCellProcessorException(null, null, null, (Throwable) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + assertNull(e.getProcessor()); + assertNull(e.getCause()); + e.printStackTrace(); + } + + /** + * Tests the second constructor. + */ + @Test + public void testConstuctor3() { + + // actual value not null + SuperCsvCellProcessorException e = new SuperCsvCellProcessorException(String.class, 123, ANONYMOUS_CSVCONTEXT, PROCESSOR); + assertEquals("the input value should be of type java.lang.String but is java.lang.Integer", e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(PROCESSOR, e.getProcessor()); + e.printStackTrace(); + + // null actual value + e = new SuperCsvCellProcessorException(String.class, null, ANONYMOUS_CSVCONTEXT, PROCESSOR); + assertEquals("the input value should be of type java.lang.String but is null", e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(PROCESSOR, e.getProcessor()); + e.printStackTrace(); + + // test with null values + try { + new SuperCsvCellProcessorException(null, null, null, (CellProcessor) null); + fail("should have thrown NullPointerException"); + } catch (NullPointerException npe){ + assertEquals("expectedType should not be null", npe.getMessage()); + } + } + +} diff --git a/super-csv/src/test/java/org/supercsv/exception/SuperCsvConstraintViolationExceptionTest.java b/super-csv/src/test/java/org/supercsv/exception/SuperCsvConstraintViolationExceptionTest.java index b4ef1599..c97a0904 100644 --- a/super-csv/src/test/java/org/supercsv/exception/SuperCsvConstraintViolationExceptionTest.java +++ b/super-csv/src/test/java/org/supercsv/exception/SuperCsvConstraintViolationExceptionTest.java @@ -1,78 +1,78 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.mock.IdentityTransform; -import org.supercsv.util.CsvContext; - -/** - * Tests the SuperCsvConstraintViolationException class. - * - * @author James Bassett - */ -public class SuperCsvConstraintViolationExceptionTest { - - private static final String MSG = "You violated the rules!"; - private static final Throwable THROWABLE = new RuntimeException("I'm the cause of the problem"); - private static final CellProcessor PROCESSOR = new IdentityTransform(); - - /** - * Tests the first constructor. - */ - @Test - public void testConstuctor1() { - SuperCsvConstraintViolationException e = new SuperCsvConstraintViolationException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR); - assertEquals(MSG, e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - assertEquals(PROCESSOR, e.getProcessor()); - e.printStackTrace(); - - // test with null values - e = new SuperCsvConstraintViolationException(null, (CsvContext) null, (CellProcessor) null); - assertNull(e.getMessage()); - assertNull(e.getCsvContext()); - assertNull(e.getProcessor()); - e.printStackTrace(); - } - - /** - * Tests the second constructor. - */ - @Test - public void testConstuctor2() { - SuperCsvConstraintViolationException e = new SuperCsvConstraintViolationException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR, THROWABLE); - assertEquals(MSG, e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - assertEquals(PROCESSOR, e.getProcessor()); - assertEquals(THROWABLE, e.getCause()); - e.printStackTrace(); - - // test with null values - e = new SuperCsvConstraintViolationException(null, null, null, (Throwable) null); - assertNull(e.getMessage()); - assertNull(e.getCsvContext()); - assertNull(e.getProcessor()); - assertNull(e.getCause()); - e.printStackTrace(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.mock.IdentityTransform; +import org.supercsv.util.CsvContext; + +/** + * Tests the SuperCsvConstraintViolationException class. + * + * @author James Bassett + */ +public class SuperCsvConstraintViolationExceptionTest { + + private static final String MSG = "You violated the rules!"; + private static final Throwable THROWABLE = new RuntimeException("I'm the cause of the problem"); + private static final CellProcessor PROCESSOR = new IdentityTransform(); + + /** + * Tests the first constructor. + */ + @Test + public void testConstuctor1() { + SuperCsvConstraintViolationException e = new SuperCsvConstraintViolationException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR); + assertEquals(MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(PROCESSOR, e.getProcessor()); + e.printStackTrace(); + + // test with null values + e = new SuperCsvConstraintViolationException(null, (CsvContext) null, (CellProcessor) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + assertNull(e.getProcessor()); + e.printStackTrace(); + } + + /** + * Tests the second constructor. + */ + @Test + public void testConstuctor2() { + SuperCsvConstraintViolationException e = new SuperCsvConstraintViolationException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR, THROWABLE); + assertEquals(MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(PROCESSOR, e.getProcessor()); + assertEquals(THROWABLE, e.getCause()); + e.printStackTrace(); + + // test with null values + e = new SuperCsvConstraintViolationException(null, null, null, (Throwable) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + assertNull(e.getProcessor()); + assertNull(e.getCause()); + e.printStackTrace(); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/exception/SuperCsvExceptionTest.java b/super-csv/src/test/java/org/supercsv/exception/SuperCsvExceptionTest.java index 3a54fc9a..010c8692 100644 --- a/super-csv/src/test/java/org/supercsv/exception/SuperCsvExceptionTest.java +++ b/super-csv/src/test/java/org/supercsv/exception/SuperCsvExceptionTest.java @@ -1,86 +1,86 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; - -import org.junit.Test; -import org.supercsv.util.CsvContext; - -/** - * Tests the SuperCsvException class. - * - * @author James Bassett - */ -public class SuperCsvExceptionTest { - - private static final String MSG = "Something terrible happened!"; - private static final Throwable THROWABLE = new RuntimeException("I'm the cause of the problem"); - - /** - * Tests the first constructor. - */ - @Test - public void testConstuctor1() { - SuperCsvException e = new SuperCsvException(MSG); - assertEquals(MSG, e.getMessage()); - e.printStackTrace(); - - // test with null msg - e = new SuperCsvException(null); - assertNull(e.getMessage()); - e.printStackTrace(); - } - - /** - * Tests the second constructor. - */ - @Test - public void testConstuctor2() { - SuperCsvException e = new SuperCsvException(MSG, ANONYMOUS_CSVCONTEXT); - assertEquals(MSG, e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - e.printStackTrace(); - - // test with null msg and context - e = new SuperCsvException(null, (CsvContext) null); - assertNull(e.getMessage()); - assertNull(e.getCsvContext()); - e.printStackTrace(); - } - - /** - * Tests the third constructor. - */ - @Test - public void testConstuctor3() { - SuperCsvException e = new SuperCsvException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); - assertEquals(MSG, e.getMessage()); - assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); - assertEquals(THROWABLE, e.getCause()); - e.printStackTrace(); - - // test with null msg, context and throwable - e = new SuperCsvException(null, (CsvContext) null, (Throwable) null); - assertNull(e.getMessage()); - assertNull(e.getCsvContext()); - assertNull(e.getCause()); - e.printStackTrace(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.supercsv.SuperCsvTestUtils.ANONYMOUS_CSVCONTEXT; + +import org.junit.Test; +import org.supercsv.util.CsvContext; + +/** + * Tests the SuperCsvException class. + * + * @author James Bassett + */ +public class SuperCsvExceptionTest { + + private static final String MSG = "Something terrible happened!"; + private static final Throwable THROWABLE = new RuntimeException("I'm the cause of the problem"); + + /** + * Tests the first constructor. + */ + @Test + public void testConstuctor1() { + SuperCsvException e = new SuperCsvException(MSG); + assertEquals(MSG, e.getMessage()); + e.printStackTrace(); + + // test with null msg + e = new SuperCsvException(null); + assertNull(e.getMessage()); + e.printStackTrace(); + } + + /** + * Tests the second constructor. + */ + @Test + public void testConstuctor2() { + SuperCsvException e = new SuperCsvException(MSG, ANONYMOUS_CSVCONTEXT); + assertEquals(MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + e.printStackTrace(); + + // test with null msg and context + e = new SuperCsvException(null, (CsvContext) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + e.printStackTrace(); + } + + /** + * Tests the third constructor. + */ + @Test + public void testConstuctor3() { + SuperCsvException e = new SuperCsvException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); + assertEquals(MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(THROWABLE, e.getCause()); + e.printStackTrace(); + + // test with null msg, context and throwable + e = new SuperCsvException(null, (CsvContext) null, (Throwable) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + assertNull(e.getCause()); + e.printStackTrace(); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/exception/SuperCsvReflectionExceptionTest.java b/super-csv/src/test/java/org/supercsv/exception/SuperCsvReflectionExceptionTest.java index 41a6d245..ded7b832 100644 --- a/super-csv/src/test/java/org/supercsv/exception/SuperCsvReflectionExceptionTest.java +++ b/super-csv/src/test/java/org/supercsv/exception/SuperCsvReflectionExceptionTest.java @@ -1,65 +1,65 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.exception; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -/** - * Tests the SuperCsvReflectionException class. - * - * @author James Bassett - */ -public class SuperCsvReflectionExceptionTest { - - private static final String MSG = "Reflection failed"; - private static final Throwable THROWABLE = new RuntimeException("Mirror is broken"); - - /** - * Tests the first constructor. - */ - @Test - public void testConstructor1() { - SuperCsvReflectionException e = new SuperCsvReflectionException(MSG); - assertEquals(MSG, e.getMessage()); - e.printStackTrace(); - - // test with null msg - e = new SuperCsvReflectionException(null); - assertNull(e.getMessage()); - e.printStackTrace(); - } - - /** - * Tests the second constructor. - */ - @Test - public void testConstructor2() { - SuperCsvReflectionException e = new SuperCsvReflectionException(MSG, THROWABLE); - assertEquals(MSG, e.getMessage()); - assertEquals(THROWABLE, e.getCause()); - e.printStackTrace(); - - // test with null msg - e = new SuperCsvReflectionException(null, null); - assertNull(e.getMessage()); - assertNull(e.getCause()); - e.printStackTrace(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +/** + * Tests the SuperCsvReflectionException class. + * + * @author James Bassett + */ +public class SuperCsvReflectionExceptionTest { + + private static final String MSG = "Reflection failed"; + private static final Throwable THROWABLE = new RuntimeException("Mirror is broken"); + + /** + * Tests the first constructor. + */ + @Test + public void testConstructor1() { + SuperCsvReflectionException e = new SuperCsvReflectionException(MSG); + assertEquals(MSG, e.getMessage()); + e.printStackTrace(); + + // test with null msg + e = new SuperCsvReflectionException(null); + assertNull(e.getMessage()); + e.printStackTrace(); + } + + /** + * Tests the second constructor. + */ + @Test + public void testConstructor2() { + SuperCsvReflectionException e = new SuperCsvReflectionException(MSG, THROWABLE); + assertEquals(MSG, e.getMessage()); + assertEquals(THROWABLE, e.getCause()); + e.printStackTrace(); + + // test with null msg + e = new SuperCsvReflectionException(null, null); + assertNull(e.getMessage()); + assertNull(e.getCause()); + e.printStackTrace(); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/io/AbstractCsvReaderTest.java b/super-csv/src/test/java/org/supercsv/io/AbstractCsvReaderTest.java index 3c9970bc..f13ad585 100644 --- a/super-csv/src/test/java/org/supercsv/io/AbstractCsvReaderTest.java +++ b/super-csv/src/test/java/org/supercsv/io/AbstractCsvReaderTest.java @@ -1,337 +1,337 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests AbstractCsvReader. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class AbstractCsvReaderTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private static final CsvPreference SURROUNDING_SPACES_NEED_QUOTES_PREFS = new CsvPreference.Builder( - CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); - - private Reader reader; - - private Reader surroundingSpacesNeedQuotesReader; - - private AbstractCsvReader abstractReader; - - private AbstractCsvReader tokenizerAbstractReader; - - private AbstractCsvReader surroundingSpacesNeedQuotesAbstractReader; - - private ITokenizer tokenizer; - - /** - * Implementation of AbstractCsvReader for testing. - */ - private static class MockCsvReader extends AbstractCsvReader { - - public MockCsvReader(ITokenizer tokenizer, CsvPreference preferences) { - super(tokenizer, preferences); - } - - public MockCsvReader(Reader reader, CsvPreference preferences) { - super(reader, preferences); - } - - } - - /** - * Sets up the reader for the tests. - */ - @Before - public void setUp() { - reader = new StringReader("firstName,lastName,age,address\n" + "John,Smith,23,\n" - + "Harry,Potter,,\"Gryffindor\nHogwarts Castle\nUK\""); - abstractReader = new MockCsvReader(reader, PREFS); - - tokenizer = new Tokenizer(reader, PREFS); - tokenizerAbstractReader = new MockCsvReader(tokenizer, PREFS); - - surroundingSpacesNeedQuotesReader = new StringReader("firstName, lastName, age, address\n" - + " John , Smith, 23 , \n" + "Harry, Potter, , \"Gryffindor\nHogwarts Castle\nUK\" "); - surroundingSpacesNeedQuotesAbstractReader = new MockCsvReader(surroundingSpacesNeedQuotesReader, - SURROUNDING_SPACES_NEED_QUOTES_PREFS); - } - - /** - * Closes the readers after the test. - */ - @After - public void tearDown() throws IOException { - abstractReader.close(); - tokenizerAbstractReader.close(); - surroundingSpacesNeedQuotesAbstractReader.close(); - } - - /** - * Tests a normal reading scenario, asserting all of the properties available each time. - */ - @Test - public void testReadingWithNormalReader() throws IOException { - assertReading(abstractReader); - } - - /** - * Tests a normal reading scenario (with the custom tokenizer reader), asserting all of the properties available - * each time. - */ - @Test - public void testReadingWithTokenizerReader() throws IOException { - assertReading(tokenizerAbstractReader); - } - - /** - * Reusable method to test a normal reading scenario, asserting all of the properties are available each time. - */ - private void assertReading(final AbstractCsvReader csvReader) throws IOException { - - assertEquals(PREFS, csvReader.getPreferences()); - - assertEquals(0, csvReader.getLineNumber()); - assertEquals(0, csvReader.getRowNumber()); - assertEquals("", csvReader.getUntokenizedRow()); - assertEquals(0, csvReader.length()); - - // read the header - final String[] header = csvReader.getHeader(true); - assertEquals(4, header.length); - assertEquals("firstName", header[0]); - assertEquals("lastName", header[1]); - assertEquals("age", header[2]); - assertEquals("address", header[3]); - - assertEquals(1, csvReader.getLineNumber()); - assertEquals(1, csvReader.getRowNumber()); - assertEquals("firstName,lastName,age,address", csvReader.getUntokenizedRow()); - assertEquals(4, csvReader.length()); - - // read the first data row - assertTrue(csvReader.readRow()); - List line = csvReader.getColumns(); // John,Smith,23,\"1 Sesame St\nNew York\" - assertEquals(4, csvReader.length()); - assertEquals("John", line.get(0)); - assertEquals("Smith", line.get(1)); - assertEquals("23", line.get(2)); - assertNull(line.get(3)); - - // get() should return the same values as the List from read() - assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), - csvReader.get(4) })); - - assertEquals(2, csvReader.getLineNumber()); - assertEquals(2, csvReader.getRowNumber()); - assertEquals("John,Smith,23,", csvReader.getUntokenizedRow()); - assertEquals(4, csvReader.length()); - - // read the second data row - assertTrue(csvReader.readRow()); - line = csvReader.getColumns(); // Harry,Potter,13,\"Gryffindor\nHogwarts Castle\nUK\" - assertEquals(4, csvReader.length()); - assertEquals("Harry", line.get(0)); - assertEquals("Potter", line.get(1)); - assertNull(line.get(2)); - assertEquals("Gryffindor\nHogwarts Castle\nUK", line.get(3)); - - // get() should return the same values as the List from read() - assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), - csvReader.get(4) })); - - assertEquals(5, csvReader.getLineNumber()); // 2 newlines in harry's address - assertEquals(3, csvReader.getRowNumber()); - assertEquals("Harry,Potter,,\"Gryffindor\nHogwarts Castle\nUK\"", csvReader.getUntokenizedRow()); - assertEquals(4, csvReader.length()); - - // read again (should be EOF) - assertFalse(csvReader.readRow()); - assertEquals(5, csvReader.getLineNumber()); - assertEquals(3, csvReader.getRowNumber()); - assertEquals("", csvReader.getUntokenizedRow()); - assertEquals(0, csvReader.length()); - - } - - /** - * Tests a normal reading scenario (with surroundingSpacesNeedQuotes enabled), asserting all of the properties available - * each time. - */ - @Test - public void testReadingWithSurroundingSpacesNeedQuotesReader() throws IOException { - assertReadingWithSurroundingSpacesNeedQuotesEnabled(surroundingSpacesNeedQuotesAbstractReader); - } - - /** - * Reusable method to test a reading scenario (with surroundingSpacesNeedQuotes enabled), asserting all of the - * properties are available each time. - */ - private void assertReadingWithSurroundingSpacesNeedQuotesEnabled(final AbstractCsvReader csvReader) throws IOException { - - assertEquals(SURROUNDING_SPACES_NEED_QUOTES_PREFS, csvReader.getPreferences()); - - assertEquals(0, csvReader.getLineNumber()); - assertEquals(0, csvReader.getRowNumber()); - assertEquals("", csvReader.getUntokenizedRow()); - assertEquals(0, csvReader.length()); - - // read the header - final String[] header = csvReader.getHeader(true); - assertEquals(4, header.length); - assertEquals("firstName", header[0]); - assertEquals("lastName", header[1]); - assertEquals("age", header[2]); - assertEquals("address", header[3]); - - assertEquals(1, csvReader.getLineNumber()); - assertEquals(1, csvReader.getRowNumber()); - assertEquals("firstName, lastName, age, address", csvReader.getUntokenizedRow()); - assertEquals(4, csvReader.length()); - - // read the first data row - assertTrue(csvReader.readRow()); - List line = csvReader.getColumns(); // John , Smith, 23 , \"1 Sesame St\nNew York\" - assertEquals(4, csvReader.length()); - assertEquals("John", line.get(0)); - assertEquals("Smith", line.get(1)); - assertEquals("23", line.get(2)); - assertNull(line.get(3)); - - // get() should return the same values as the List from read() - assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), - csvReader.get(4) })); - - assertEquals(2, csvReader.getLineNumber()); - assertEquals(2, csvReader.getRowNumber()); - assertEquals(" John , Smith, 23 , ", csvReader.getUntokenizedRow()); - assertEquals(4, csvReader.length()); - - // read the second data row - assertTrue(csvReader.readRow()); - line = csvReader.getColumns(); // Harry, Potter, 13, \"Gryffindor\nHogwarts Castle\nUK\" - assertEquals(4, csvReader.length()); - assertEquals("Harry", line.get(0)); - assertEquals("Potter", line.get(1)); - assertNull(line.get(2)); - assertEquals("Gryffindor\nHogwarts Castle\nUK", line.get(3)); - - // get() should return the same values as the List from read() - assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), - csvReader.get(4) })); - - assertEquals(5, csvReader.getLineNumber()); // 2 newlines in harry's address - assertEquals(3, csvReader.getRowNumber()); - assertEquals("Harry, Potter, , \"Gryffindor\nHogwarts Castle\nUK\" ", csvReader.getUntokenizedRow()); - assertEquals(4, csvReader.length()); - - // read again (should be EOF) - assertFalse(csvReader.readRow()); - assertEquals(5, csvReader.getLineNumber()); - assertEquals(3, csvReader.getRowNumber()); - assertEquals("", csvReader.getUntokenizedRow()); - assertEquals(0, csvReader.length()); - - } - - /** - * Tests the getCsvHeader(true) can't be called when a line has already been read. - */ - @Test - public void testIllegalGetHeader() throws IOException { - - abstractReader.getHeader(true); - - try { - abstractReader.getHeader(true); - fail("should have thrown SuperCsvException"); - } - catch(SuperCsvException e) { - assertEquals("CSV header must be fetched as the first read operation, but 1 lines have already been read", - e.getMessage()); - } - - } - - /** - * Tests getCsvHeader(false). - */ - @Test - public void testGetHeaderNoCheck() throws IOException { - assertEquals(4, abstractReader.getHeader(false).length); - assertEquals(4, abstractReader.getHeader(false).length); - assertEquals(4, abstractReader.getHeader(false).length); - assertNull(abstractReader.getHeader(false)); // should be EOF - } - - /** - * Tests the Reader constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullReader() { - new CsvListReader((Reader) null, PREFS); - } - - /** - * Tests the Reader constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullPreferences() { - new CsvListReader(reader, null); - } - - /** - * Tests the Tokenizer constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullReader() { - new CsvListReader((Tokenizer) null, PREFS); - } - - /** - * Tests the Tokenizer constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullPreferences() { - new CsvListReader(tokenizer, null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.Arrays; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests AbstractCsvReader. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class AbstractCsvReaderTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private static final CsvPreference SURROUNDING_SPACES_NEED_QUOTES_PREFS = new CsvPreference.Builder( + CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); + + private Reader reader; + + private Reader surroundingSpacesNeedQuotesReader; + + private AbstractCsvReader abstractReader; + + private AbstractCsvReader tokenizerAbstractReader; + + private AbstractCsvReader surroundingSpacesNeedQuotesAbstractReader; + + private ITokenizer tokenizer; + + /** + * Implementation of AbstractCsvReader for testing. + */ + private static class MockCsvReader extends AbstractCsvReader { + + public MockCsvReader(ITokenizer tokenizer, CsvPreference preferences) { + super(tokenizer, preferences); + } + + public MockCsvReader(Reader reader, CsvPreference preferences) { + super(reader, preferences); + } + + } + + /** + * Sets up the reader for the tests. + */ + @Before + public void setUp() { + reader = new StringReader("firstName,lastName,age,address\n" + "John,Smith,23,\n" + + "Harry,Potter,,\"Gryffindor\nHogwarts Castle\nUK\""); + abstractReader = new MockCsvReader(reader, PREFS); + + tokenizer = new Tokenizer(reader, PREFS); + tokenizerAbstractReader = new MockCsvReader(tokenizer, PREFS); + + surroundingSpacesNeedQuotesReader = new StringReader("firstName, lastName, age, address\n" + + " John , Smith, 23 , \n" + "Harry, Potter, , \"Gryffindor\nHogwarts Castle\nUK\" "); + surroundingSpacesNeedQuotesAbstractReader = new MockCsvReader(surroundingSpacesNeedQuotesReader, + SURROUNDING_SPACES_NEED_QUOTES_PREFS); + } + + /** + * Closes the readers after the test. + */ + @After + public void tearDown() throws IOException { + abstractReader.close(); + tokenizerAbstractReader.close(); + surroundingSpacesNeedQuotesAbstractReader.close(); + } + + /** + * Tests a normal reading scenario, asserting all of the properties available each time. + */ + @Test + public void testReadingWithNormalReader() throws IOException { + assertReading(abstractReader); + } + + /** + * Tests a normal reading scenario (with the custom tokenizer reader), asserting all of the properties available + * each time. + */ + @Test + public void testReadingWithTokenizerReader() throws IOException { + assertReading(tokenizerAbstractReader); + } + + /** + * Reusable method to test a normal reading scenario, asserting all of the properties are available each time. + */ + private void assertReading(final AbstractCsvReader csvReader) throws IOException { + + assertEquals(PREFS, csvReader.getPreferences()); + + assertEquals(0, csvReader.getLineNumber()); + assertEquals(0, csvReader.getRowNumber()); + assertEquals("", csvReader.getUntokenizedRow()); + assertEquals(0, csvReader.length()); + + // read the header + final String[] header = csvReader.getHeader(true); + assertEquals(4, header.length); + assertEquals("firstName", header[0]); + assertEquals("lastName", header[1]); + assertEquals("age", header[2]); + assertEquals("address", header[3]); + + assertEquals(1, csvReader.getLineNumber()); + assertEquals(1, csvReader.getRowNumber()); + assertEquals("firstName,lastName,age,address", csvReader.getUntokenizedRow()); + assertEquals(4, csvReader.length()); + + // read the first data row + assertTrue(csvReader.readRow()); + List line = csvReader.getColumns(); // John,Smith,23,\"1 Sesame St\nNew York\" + assertEquals(4, csvReader.length()); + assertEquals("John", line.get(0)); + assertEquals("Smith", line.get(1)); + assertEquals("23", line.get(2)); + assertNull(line.get(3)); + + // get() should return the same values as the List from read() + assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), + csvReader.get(4) })); + + assertEquals(2, csvReader.getLineNumber()); + assertEquals(2, csvReader.getRowNumber()); + assertEquals("John,Smith,23,", csvReader.getUntokenizedRow()); + assertEquals(4, csvReader.length()); + + // read the second data row + assertTrue(csvReader.readRow()); + line = csvReader.getColumns(); // Harry,Potter,13,\"Gryffindor\nHogwarts Castle\nUK\" + assertEquals(4, csvReader.length()); + assertEquals("Harry", line.get(0)); + assertEquals("Potter", line.get(1)); + assertNull(line.get(2)); + assertEquals("Gryffindor\nHogwarts Castle\nUK", line.get(3)); + + // get() should return the same values as the List from read() + assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), + csvReader.get(4) })); + + assertEquals(5, csvReader.getLineNumber()); // 2 newlines in harry's address + assertEquals(3, csvReader.getRowNumber()); + assertEquals("Harry,Potter,,\"Gryffindor\nHogwarts Castle\nUK\"", csvReader.getUntokenizedRow()); + assertEquals(4, csvReader.length()); + + // read again (should be EOF) + assertFalse(csvReader.readRow()); + assertEquals(5, csvReader.getLineNumber()); + assertEquals(3, csvReader.getRowNumber()); + assertEquals("", csvReader.getUntokenizedRow()); + assertEquals(0, csvReader.length()); + + } + + /** + * Tests a normal reading scenario (with surroundingSpacesNeedQuotes enabled), asserting all of the properties available + * each time. + */ + @Test + public void testReadingWithSurroundingSpacesNeedQuotesReader() throws IOException { + assertReadingWithSurroundingSpacesNeedQuotesEnabled(surroundingSpacesNeedQuotesAbstractReader); + } + + /** + * Reusable method to test a reading scenario (with surroundingSpacesNeedQuotes enabled), asserting all of the + * properties are available each time. + */ + private void assertReadingWithSurroundingSpacesNeedQuotesEnabled(final AbstractCsvReader csvReader) throws IOException { + + assertEquals(SURROUNDING_SPACES_NEED_QUOTES_PREFS, csvReader.getPreferences()); + + assertEquals(0, csvReader.getLineNumber()); + assertEquals(0, csvReader.getRowNumber()); + assertEquals("", csvReader.getUntokenizedRow()); + assertEquals(0, csvReader.length()); + + // read the header + final String[] header = csvReader.getHeader(true); + assertEquals(4, header.length); + assertEquals("firstName", header[0]); + assertEquals("lastName", header[1]); + assertEquals("age", header[2]); + assertEquals("address", header[3]); + + assertEquals(1, csvReader.getLineNumber()); + assertEquals(1, csvReader.getRowNumber()); + assertEquals("firstName, lastName, age, address", csvReader.getUntokenizedRow()); + assertEquals(4, csvReader.length()); + + // read the first data row + assertTrue(csvReader.readRow()); + List line = csvReader.getColumns(); // John , Smith, 23 , \"1 Sesame St\nNew York\" + assertEquals(4, csvReader.length()); + assertEquals("John", line.get(0)); + assertEquals("Smith", line.get(1)); + assertEquals("23", line.get(2)); + assertNull(line.get(3)); + + // get() should return the same values as the List from read() + assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), + csvReader.get(4) })); + + assertEquals(2, csvReader.getLineNumber()); + assertEquals(2, csvReader.getRowNumber()); + assertEquals(" John , Smith, 23 , ", csvReader.getUntokenizedRow()); + assertEquals(4, csvReader.length()); + + // read the second data row + assertTrue(csvReader.readRow()); + line = csvReader.getColumns(); // Harry, Potter, 13, \"Gryffindor\nHogwarts Castle\nUK\" + assertEquals(4, csvReader.length()); + assertEquals("Harry", line.get(0)); + assertEquals("Potter", line.get(1)); + assertNull(line.get(2)); + assertEquals("Gryffindor\nHogwarts Castle\nUK", line.get(3)); + + // get() should return the same values as the List from read() + assertTrue(Arrays.equals(line.toArray(), new Object[] { csvReader.get(1), csvReader.get(2), csvReader.get(3), + csvReader.get(4) })); + + assertEquals(5, csvReader.getLineNumber()); // 2 newlines in harry's address + assertEquals(3, csvReader.getRowNumber()); + assertEquals("Harry, Potter, , \"Gryffindor\nHogwarts Castle\nUK\" ", csvReader.getUntokenizedRow()); + assertEquals(4, csvReader.length()); + + // read again (should be EOF) + assertFalse(csvReader.readRow()); + assertEquals(5, csvReader.getLineNumber()); + assertEquals(3, csvReader.getRowNumber()); + assertEquals("", csvReader.getUntokenizedRow()); + assertEquals(0, csvReader.length()); + + } + + /** + * Tests the getCsvHeader(true) can't be called when a line has already been read. + */ + @Test + public void testIllegalGetHeader() throws IOException { + + abstractReader.getHeader(true); + + try { + abstractReader.getHeader(true); + fail("should have thrown SuperCsvException"); + } + catch(SuperCsvException e) { + assertEquals("CSV header must be fetched as the first read operation, but 1 lines have already been read", + e.getMessage()); + } + + } + + /** + * Tests getCsvHeader(false). + */ + @Test + public void testGetHeaderNoCheck() throws IOException { + assertEquals(4, abstractReader.getHeader(false).length); + assertEquals(4, abstractReader.getHeader(false).length); + assertEquals(4, abstractReader.getHeader(false).length); + assertNull(abstractReader.getHeader(false)); // should be EOF + } + + /** + * Tests the Reader constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullReader() { + new CsvListReader((Reader) null, PREFS); + } + + /** + * Tests the Reader constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullPreferences() { + new CsvListReader(reader, null); + } + + /** + * Tests the Tokenizer constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullReader() { + new CsvListReader((Tokenizer) null, PREFS); + } + + /** + * Tests the Tokenizer constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullPreferences() { + new CsvListReader(tokenizer, null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/io/AbstractCsvWriterTest.java b/super-csv/src/test/java/org/supercsv/io/AbstractCsvWriterTest.java index 308f7273..5982bcd9 100644 --- a/super-csv/src/test/java/org/supercsv/io/AbstractCsvWriterTest.java +++ b/super-csv/src/test/java/org/supercsv/io/AbstractCsvWriterTest.java @@ -1,160 +1,160 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.HEADER; -import static org.supercsv.SuperCsvTestUtils.HEADER_CSV; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests AbstractCsvWriter. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class AbstractCsvWriterTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - private static final CsvPreference SURROUNDING_SPACES_REQUIRE_QUOTES_PREFS = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); - - private Writer writer; - - private AbstractCsvWriter abstractWriter; - private AbstractCsvWriter surroundingSpacesNeedQuotesAbstractWriter; - - /** - * Implementation of AbstractCsvWriter for testing. - */ - static class MockCsvWriter extends AbstractCsvWriter { - - public MockCsvWriter(Writer writer, CsvPreference preference) { - super(writer, preference); - } - } - - /** - * Sets up the writer for the tests. - */ - @Before - public void setUp() { - writer = new StringWriter(); - abstractWriter = new MockCsvWriter(writer, PREFS); - surroundingSpacesNeedQuotesAbstractWriter = new MockCsvWriter(writer, SURROUNDING_SPACES_REQUIRE_QUOTES_PREFS); - } - - /** - * Closes the writer after the test. - */ - @After - public void tearDown() throws IOException { - abstractWriter.close(); - surroundingSpacesNeedQuotesAbstractWriter.close(); - } - - /** - * Tests the writeHeader() method. - */ - @Test - public void testWriteHeader() throws IOException { - assertEquals(0, abstractWriter.getLineNumber()); - assertEquals(0, abstractWriter.getRowNumber()); - - abstractWriter.writeHeader(HEADER); - - assertEquals(1, abstractWriter.getLineNumber()); - assertEquals(1, abstractWriter.getRowNumber()); - - abstractWriter.flush(); - assertEquals(HEADER_CSV + "\r\n", writer.toString()); - } - - /** - * Tests the escapeString() method with and without surroundingSpacesNeedQuotes enabled. - */ - @Test - public void testEscapeString(){ - - assertEquals("", abstractWriter.escapeString("")); - assertEquals("", surroundingSpacesNeedQuotesAbstractWriter.escapeString("")); - - assertEquals(" ", abstractWriter.escapeString(" ")); - assertEquals("\" \"", surroundingSpacesNeedQuotesAbstractWriter.escapeString(" ")); - - assertEquals(" leading space", abstractWriter.escapeString(" leading space")); - assertEquals("\" leading space\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString(" leading space")); - - assertEquals("trailing space ", abstractWriter.escapeString("trailing space ")); - assertEquals("\"trailing space \"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("trailing space ")); - - assertEquals("just a normal phrase", abstractWriter.escapeString("just a normal phrase")); - assertEquals("just a normal phrase", surroundingSpacesNeedQuotesAbstractWriter.escapeString("just a normal phrase")); - - assertEquals("\"oh look, a comma\"", abstractWriter.escapeString("oh look, a comma")); - assertEquals("\"oh look, a comma\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("oh look, a comma")); - - assertEquals("\"\"\"Watch out for quotes\"\", he said\"", abstractWriter.escapeString("\"Watch out for quotes\", he said")); - assertEquals("\"\"\"Watch out for quotes\"\", he said\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("\"Watch out for quotes\", he said")); - - assertEquals("\"text that spans\r\ntwo lines\"", abstractWriter.escapeString("text that spans\ntwo lines")); - assertEquals("\"text that spans\r\ntwo lines\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("text that spans\ntwo lines")); - - assertEquals("\"text \"\"with quotes\"\" that spans\r\ntwo lines\"", abstractWriter.escapeString("text \"with quotes\" that spans\ntwo lines")); - assertEquals("\"text \"\"with quotes\"\" that spans\r\ntwo lines\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("text \"with quotes\" that spans\ntwo lines")); - } - - /** - * Tests the writeHeader() method with a null array. - */ - @Test(expected = NullPointerException.class) - public void writeHeaderWithNull() throws IOException { - abstractWriter.writeHeader((String[]) null); - } - - /** - * Tests the writeHeader() method with an empty array. - */ - @Test(expected = IllegalArgumentException.class) - public void writeHeaderWithEmptyArray() throws IOException { - abstractWriter.writeHeader(new String[] {}); - } - - /** - * Tests the constructor with a null writer. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWithNullWriter() { - new MockCsvWriter(null, PREFS); - } - - /** - * Tests the constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWithNullPreferences() { - new MockCsvWriter(writer, null); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.HEADER; +import static org.supercsv.SuperCsvTestUtils.HEADER_CSV; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests AbstractCsvWriter. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class AbstractCsvWriterTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + private static final CsvPreference SURROUNDING_SPACES_REQUIRE_QUOTES_PREFS = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); + + private Writer writer; + + private AbstractCsvWriter abstractWriter; + private AbstractCsvWriter surroundingSpacesNeedQuotesAbstractWriter; + + /** + * Implementation of AbstractCsvWriter for testing. + */ + static class MockCsvWriter extends AbstractCsvWriter { + + public MockCsvWriter(Writer writer, CsvPreference preference) { + super(writer, preference); + } + } + + /** + * Sets up the writer for the tests. + */ + @Before + public void setUp() { + writer = new StringWriter(); + abstractWriter = new MockCsvWriter(writer, PREFS); + surroundingSpacesNeedQuotesAbstractWriter = new MockCsvWriter(writer, SURROUNDING_SPACES_REQUIRE_QUOTES_PREFS); + } + + /** + * Closes the writer after the test. + */ + @After + public void tearDown() throws IOException { + abstractWriter.close(); + surroundingSpacesNeedQuotesAbstractWriter.close(); + } + + /** + * Tests the writeHeader() method. + */ + @Test + public void testWriteHeader() throws IOException { + assertEquals(0, abstractWriter.getLineNumber()); + assertEquals(0, abstractWriter.getRowNumber()); + + abstractWriter.writeHeader(HEADER); + + assertEquals(1, abstractWriter.getLineNumber()); + assertEquals(1, abstractWriter.getRowNumber()); + + abstractWriter.flush(); + assertEquals(HEADER_CSV + "\r\n", writer.toString()); + } + + /** + * Tests the escapeString() method with and without surroundingSpacesNeedQuotes enabled. + */ + @Test + public void testEscapeString(){ + + assertEquals("", abstractWriter.escapeString("")); + assertEquals("", surroundingSpacesNeedQuotesAbstractWriter.escapeString("")); + + assertEquals(" ", abstractWriter.escapeString(" ")); + assertEquals("\" \"", surroundingSpacesNeedQuotesAbstractWriter.escapeString(" ")); + + assertEquals(" leading space", abstractWriter.escapeString(" leading space")); + assertEquals("\" leading space\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString(" leading space")); + + assertEquals("trailing space ", abstractWriter.escapeString("trailing space ")); + assertEquals("\"trailing space \"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("trailing space ")); + + assertEquals("just a normal phrase", abstractWriter.escapeString("just a normal phrase")); + assertEquals("just a normal phrase", surroundingSpacesNeedQuotesAbstractWriter.escapeString("just a normal phrase")); + + assertEquals("\"oh look, a comma\"", abstractWriter.escapeString("oh look, a comma")); + assertEquals("\"oh look, a comma\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("oh look, a comma")); + + assertEquals("\"\"\"Watch out for quotes\"\", he said\"", abstractWriter.escapeString("\"Watch out for quotes\", he said")); + assertEquals("\"\"\"Watch out for quotes\"\", he said\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("\"Watch out for quotes\", he said")); + + assertEquals("\"text that spans\r\ntwo lines\"", abstractWriter.escapeString("text that spans\ntwo lines")); + assertEquals("\"text that spans\r\ntwo lines\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("text that spans\ntwo lines")); + + assertEquals("\"text \"\"with quotes\"\" that spans\r\ntwo lines\"", abstractWriter.escapeString("text \"with quotes\" that spans\ntwo lines")); + assertEquals("\"text \"\"with quotes\"\" that spans\r\ntwo lines\"", surroundingSpacesNeedQuotesAbstractWriter.escapeString("text \"with quotes\" that spans\ntwo lines")); + } + + /** + * Tests the writeHeader() method with a null array. + */ + @Test(expected = NullPointerException.class) + public void writeHeaderWithNull() throws IOException { + abstractWriter.writeHeader((String[]) null); + } + + /** + * Tests the writeHeader() method with an empty array. + */ + @Test(expected = IllegalArgumentException.class) + public void writeHeaderWithEmptyArray() throws IOException { + abstractWriter.writeHeader(new String[] {}); + } + + /** + * Tests the constructor with a null writer. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWithNullWriter() { + new MockCsvWriter(null, PREFS); + } + + /** + * Tests the constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWithNullPreferences() { + new MockCsvWriter(writer, null); + } +} diff --git a/super-csv/src/test/java/org/supercsv/io/CsvBeanReaderTest.java b/super-csv/src/test/java/org/supercsv/io/CsvBeanReaderTest.java index 150083b3..b72a05c3 100644 --- a/super-csv/src/test/java/org/supercsv/io/CsvBeanReaderTest.java +++ b/super-csv/src/test/java/org/supercsv/io/CsvBeanReaderTest.java @@ -1,365 +1,365 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.supercsv.SuperCsvTestUtils.ADA; -import static org.supercsv.SuperCsvTestUtils.ADA_STRING; -import static org.supercsv.SuperCsvTestUtils.ALICE; -import static org.supercsv.SuperCsvTestUtils.ALICE_STRING; -import static org.supercsv.SuperCsvTestUtils.BILL; -import static org.supercsv.SuperCsvTestUtils.BILL_STRING; -import static org.supercsv.SuperCsvTestUtils.BOB; -import static org.supercsv.SuperCsvTestUtils.BOB_STRING; -import static org.supercsv.SuperCsvTestUtils.CSV_FILE; -import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.GRACE; -import static org.supercsv.SuperCsvTestUtils.GRACE_STRING; -import static org.supercsv.SuperCsvTestUtils.HEADER; -import static org.supercsv.SuperCsvTestUtils.JOHN; -import static org.supercsv.SuperCsvTestUtils.JOHN_STRING; -import static org.supercsv.SuperCsvTestUtils.LARRY; -import static org.supercsv.SuperCsvTestUtils.LARRY_STRING; -import static org.supercsv.SuperCsvTestUtils.MIRANDA; -import static org.supercsv.SuperCsvTestUtils.MIRANDA_STRING; -import static org.supercsv.SuperCsvTestUtils.PARTIAL_HEADER; -import static org.supercsv.SuperCsvTestUtils.READ_PROCESSORS; -import static org.supercsv.SuperCsvTestUtils.SERGEI; -import static org.supercsv.SuperCsvTestUtils.SERGEI_STRING; -import static org.supercsv.SuperCsvTestUtils.STEVE; -import static org.supercsv.SuperCsvTestUtils.STEVE_STRING; -import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvReflectionException; -import org.supercsv.mock.Customer; -import org.supercsv.mock.CustomerBean; -import org.supercsv.mock.CustomerStringBean; -import org.supercsv.mock.PersonBean; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests the CsvBeanReader class. - * - * @author James Bassett - */ -public class CsvBeanReaderTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private Reader reader; - - private CsvBeanReader beanReader; - - private CsvBeanReader tokenizerBeanReader; - - /** - * Sets up the reader for the tests. - */ - @Before - public void setUp() { - reader = new StringReader(CSV_FILE); - beanReader = new CsvBeanReader(reader, PREFS); - - final Tokenizer tokenizer = new Tokenizer(reader, PREFS); - tokenizerBeanReader = new CsvBeanReader(tokenizer, PREFS); - } - - /** - * Closes the readers after the test. - */ - @After - public void tearDown() throws IOException { - beanReader.close(); - tokenizerBeanReader.close(); - } - - /** - * Tests the read() method using processors. - */ - @Test - public void testReadWithProcessors() throws IOException { - - final String[] header = beanReader.getHeader(true); - assertArrayEquals(HEADER, header); - - assertEquals(JOHN, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(BOB, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(ALICE, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(BILL, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(MIRANDA, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(STEVE, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(ADA, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(SERGEI, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(LARRY, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertEquals(GRACE, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - assertNull(beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - } - - /** - * Tests the read() method using processors, but only mapping a few columns. - */ - @Test - public void testPartialReadWithProcessors() throws IOException { - - assertArrayEquals(HEADER, beanReader.getHeader(true)); - - final String[] header = PARTIAL_HEADER; - for (CustomerBean fullCustomer : CUSTOMERS){ - - // create the expected customer (same as full but with only first/last name and email) - CustomerBean expectedCustomer = new CustomerBean(); - expectedCustomer.setFirstName(fullCustomer.getFirstName()); - expectedCustomer.setLastName(fullCustomer.getLastName()); - expectedCustomer.setEmail(fullCustomer.getEmail()); - assertEquals(expectedCustomer, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - } - - assertNull(beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); - } - - /** - * Tests the read() method with no processors. - */ - @Test - public void testRead() throws IOException { - - final String[] header = beanReader.getHeader(true); - assertArrayEquals(HEADER, header); - - assertEquals(JOHN_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(BOB_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(ALICE_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(BILL_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(MIRANDA_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(STEVE_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(ADA_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(SERGEI_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(LARRY_STRING, beanReader.read(CustomerStringBean.class, header)); - assertEquals(GRACE_STRING, beanReader.read(CustomerStringBean.class, header)); - assertNull(beanReader.read(CustomerStringBean.class, header)); - } - - /** - * Tests the read() method, but only mapping a few columns. - */ - @Test - public void testPartialRead() throws IOException { - - assertArrayEquals(HEADER, beanReader.getHeader(true)); - - final String[] header = PARTIAL_HEADER; - for (CustomerStringBean fullCustomer : STRING_CUSTOMERS){ - - // create the expected customer (same as full but with only first/last name and email) - CustomerBean expectedCustomer = new CustomerBean(); - expectedCustomer.setFirstName(fullCustomer.getFirstName()); - expectedCustomer.setLastName(fullCustomer.getLastName()); - expectedCustomer.setEmail(fullCustomer.getEmail()); - assertEquals(expectedCustomer, beanReader.read(CustomerBean.class, header)); - } - - assertNull(beanReader.read(CustomerBean.class, header)); - } - - /** - * Tests the read() method with no processors, using the tokenizer version of CsvBeanReader (just to make sure it - * behaves exactly the same as the reader version). - */ - @Test - public void testReadUsingTokenizerReader() throws IOException { - - final String[] header = tokenizerBeanReader.getHeader(true); - assertArrayEquals(HEADER, header); - - assertEquals(JOHN_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(BOB_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(ALICE_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(BILL_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(MIRANDA_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(STEVE_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(ADA_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(SERGEI_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(LARRY_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertEquals(GRACE_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); - assertNull(tokenizerBeanReader.read(CustomerStringBean.class, header)); - } - - /** - * Tests the read() method with an interface and using processors. - */ - @Test - public void testReadWithProcessorsUsingInterface() throws IOException { - assertArrayEquals(HEADER, beanReader.getHeader(true)); - - // only map the fields relevant to the interface - final String[] header = new String[] { "customerNo", null, null, null, "mailingAddress", null, null, null, - null, "loyaltyPoints" }; - - int i = 0; - Customer customer; - while( (customer = beanReader.read(Customer.class, header, READ_PROCESSORS)) != null ) { - assertEquals(CUSTOMERS.get(i).getCustomerNo(), customer.getCustomerNo()); - assertEquals(CUSTOMERS.get(i).getMailingAddress(), customer.getMailingAddress()); - assertEquals(CUSTOMERS.get(i).getLoyaltyPoints(), customer.getLoyaltyPoints()); - i++; - } - - assertEquals(CUSTOMERS.size() + 1, beanReader.getRowNumber()); - - } - - /** - * Tests the read() method with an class that has no default no-arg constructor. - */ - @Test(expected = SuperCsvReflectionException.class) - public void testReadWithNonJavabean() throws IOException { - beanReader.read(Integer.class, HEADER); - } - - /** - * Tests the read() method, with a null bean class. - */ - @Test(expected = NullPointerException.class) - public void testReadWithNullBeanClass() throws IOException { - beanReader.read(null, HEADER); - } - - /** - * Tests the read() method, with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testReadWithNullNameMapping() throws IOException { - beanReader.read(PersonBean.class, (String[]) null); - } - - /** - * Tests the read() method, with a name mapping array that's not the right size. - */ - @Test(expected = IllegalArgumentException.class) - public void testReadWithInvalidSizeNameMapping() throws IOException { - beanReader.getHeader(true); - beanReader.read(PersonBean.class, new String[]{null, "firstName"}); - } - - /** - * Tests the read() method (with processors), with a null bean class. - */ - @Test(expected = NullPointerException.class) - public void testReadProcessorsWithNullBeanClass() throws IOException { - beanReader.read(null, HEADER, READ_PROCESSORS); - } - - /** - * Tests the read() method (with processors), with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testReadProcessorsWithNullNameMapping() throws IOException { - beanReader.read(PersonBean.class, (String[]) null, READ_PROCESSORS); - } - - /** - * Tests the read() method (with processors), with a null cell processor array. - */ - @Test(expected = NullPointerException.class) - public void testReadProcessorsWithNullProcessors() throws IOException { - beanReader.read(PersonBean.class, HEADER, (CellProcessor[]) null); - } - - /** - * Tests the Reader constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullReader() { - new CsvBeanReader((Reader) null, PREFS); - } - - /** - * Tests the Reader constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullPreferences() { - new CsvBeanReader(reader, null); - } - - /** - * Tests the Tokenizer constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullReader() { - new CsvBeanReader((Tokenizer) null, PREFS); - } - - /** - * Tests the Tokenizer constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullPreferences() { - new CsvBeanReader(new Tokenizer(reader, PREFS), null); - } - - /** - * Tests the read() method when invoking the bean's constructor throws IllegalAccessException. - */ - @Test(expected = SuperCsvReflectionException.class) - public void testBeanInstantationThrowingIllegalAccessException() throws IOException { - beanReader.read(IllegalAccessBean.class, HEADER); - } - - /** - * Tests the read() method when invoking a setter throws an Exception. - */ - @SuppressWarnings("resource") - @Test(expected = SuperCsvReflectionException.class) - public void testSetterThrowingException() throws IOException { - new CsvBeanReader(new StringReader("value"), PREFS).read(ExceptionBean.class, "illegalArgument"); - } - - /** - * Bean to test exceptions when invoking setters using CsvBeanReader. - */ - public static class ExceptionBean extends CustomerBean { - - public void setIllegalArgument(String s) { - throw new IllegalArgumentException("i don't like it!"); - } - - } - - /** - * Bean to test exceptions when invoking the constructor using CsvBeanWriter. - */ - public static class IllegalAccessBean extends CustomerBean { - - public IllegalAccessBean() throws IllegalAccessException { - throw new IllegalAccessException("naughty naughty!"); - } - - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.supercsv.SuperCsvTestUtils.ADA; +import static org.supercsv.SuperCsvTestUtils.ADA_STRING; +import static org.supercsv.SuperCsvTestUtils.ALICE; +import static org.supercsv.SuperCsvTestUtils.ALICE_STRING; +import static org.supercsv.SuperCsvTestUtils.BILL; +import static org.supercsv.SuperCsvTestUtils.BILL_STRING; +import static org.supercsv.SuperCsvTestUtils.BOB; +import static org.supercsv.SuperCsvTestUtils.BOB_STRING; +import static org.supercsv.SuperCsvTestUtils.CSV_FILE; +import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.GRACE; +import static org.supercsv.SuperCsvTestUtils.GRACE_STRING; +import static org.supercsv.SuperCsvTestUtils.HEADER; +import static org.supercsv.SuperCsvTestUtils.JOHN; +import static org.supercsv.SuperCsvTestUtils.JOHN_STRING; +import static org.supercsv.SuperCsvTestUtils.LARRY; +import static org.supercsv.SuperCsvTestUtils.LARRY_STRING; +import static org.supercsv.SuperCsvTestUtils.MIRANDA; +import static org.supercsv.SuperCsvTestUtils.MIRANDA_STRING; +import static org.supercsv.SuperCsvTestUtils.PARTIAL_HEADER; +import static org.supercsv.SuperCsvTestUtils.READ_PROCESSORS; +import static org.supercsv.SuperCsvTestUtils.SERGEI; +import static org.supercsv.SuperCsvTestUtils.SERGEI_STRING; +import static org.supercsv.SuperCsvTestUtils.STEVE; +import static org.supercsv.SuperCsvTestUtils.STEVE_STRING; +import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvReflectionException; +import org.supercsv.mock.Customer; +import org.supercsv.mock.CustomerBean; +import org.supercsv.mock.CustomerStringBean; +import org.supercsv.mock.PersonBean; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests the CsvBeanReader class. + * + * @author James Bassett + */ +public class CsvBeanReaderTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private Reader reader; + + private CsvBeanReader beanReader; + + private CsvBeanReader tokenizerBeanReader; + + /** + * Sets up the reader for the tests. + */ + @Before + public void setUp() { + reader = new StringReader(CSV_FILE); + beanReader = new CsvBeanReader(reader, PREFS); + + final Tokenizer tokenizer = new Tokenizer(reader, PREFS); + tokenizerBeanReader = new CsvBeanReader(tokenizer, PREFS); + } + + /** + * Closes the readers after the test. + */ + @After + public void tearDown() throws IOException { + beanReader.close(); + tokenizerBeanReader.close(); + } + + /** + * Tests the read() method using processors. + */ + @Test + public void testReadWithProcessors() throws IOException { + + final String[] header = beanReader.getHeader(true); + assertArrayEquals(HEADER, header); + + assertEquals(JOHN, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(BOB, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(ALICE, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(BILL, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(MIRANDA, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(STEVE, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(ADA, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(SERGEI, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(LARRY, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertEquals(GRACE, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + assertNull(beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + } + + /** + * Tests the read() method using processors, but only mapping a few columns. + */ + @Test + public void testPartialReadWithProcessors() throws IOException { + + assertArrayEquals(HEADER, beanReader.getHeader(true)); + + final String[] header = PARTIAL_HEADER; + for (CustomerBean fullCustomer : CUSTOMERS){ + + // create the expected customer (same as full but with only first/last name and email) + CustomerBean expectedCustomer = new CustomerBean(); + expectedCustomer.setFirstName(fullCustomer.getFirstName()); + expectedCustomer.setLastName(fullCustomer.getLastName()); + expectedCustomer.setEmail(fullCustomer.getEmail()); + assertEquals(expectedCustomer, beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + } + + assertNull(beanReader.read(CustomerBean.class, header, READ_PROCESSORS)); + } + + /** + * Tests the read() method with no processors. + */ + @Test + public void testRead() throws IOException { + + final String[] header = beanReader.getHeader(true); + assertArrayEquals(HEADER, header); + + assertEquals(JOHN_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(BOB_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(ALICE_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(BILL_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(MIRANDA_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(STEVE_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(ADA_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(SERGEI_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(LARRY_STRING, beanReader.read(CustomerStringBean.class, header)); + assertEquals(GRACE_STRING, beanReader.read(CustomerStringBean.class, header)); + assertNull(beanReader.read(CustomerStringBean.class, header)); + } + + /** + * Tests the read() method, but only mapping a few columns. + */ + @Test + public void testPartialRead() throws IOException { + + assertArrayEquals(HEADER, beanReader.getHeader(true)); + + final String[] header = PARTIAL_HEADER; + for (CustomerStringBean fullCustomer : STRING_CUSTOMERS){ + + // create the expected customer (same as full but with only first/last name and email) + CustomerBean expectedCustomer = new CustomerBean(); + expectedCustomer.setFirstName(fullCustomer.getFirstName()); + expectedCustomer.setLastName(fullCustomer.getLastName()); + expectedCustomer.setEmail(fullCustomer.getEmail()); + assertEquals(expectedCustomer, beanReader.read(CustomerBean.class, header)); + } + + assertNull(beanReader.read(CustomerBean.class, header)); + } + + /** + * Tests the read() method with no processors, using the tokenizer version of CsvBeanReader (just to make sure it + * behaves exactly the same as the reader version). + */ + @Test + public void testReadUsingTokenizerReader() throws IOException { + + final String[] header = tokenizerBeanReader.getHeader(true); + assertArrayEquals(HEADER, header); + + assertEquals(JOHN_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(BOB_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(ALICE_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(BILL_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(MIRANDA_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(STEVE_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(ADA_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(SERGEI_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(LARRY_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertEquals(GRACE_STRING, tokenizerBeanReader.read(CustomerStringBean.class, header)); + assertNull(tokenizerBeanReader.read(CustomerStringBean.class, header)); + } + + /** + * Tests the read() method with an interface and using processors. + */ + @Test + public void testReadWithProcessorsUsingInterface() throws IOException { + assertArrayEquals(HEADER, beanReader.getHeader(true)); + + // only map the fields relevant to the interface + final String[] header = new String[] { "customerNo", null, null, null, "mailingAddress", null, null, null, + null, "loyaltyPoints" }; + + int i = 0; + Customer customer; + while( (customer = beanReader.read(Customer.class, header, READ_PROCESSORS)) != null ) { + assertEquals(CUSTOMERS.get(i).getCustomerNo(), customer.getCustomerNo()); + assertEquals(CUSTOMERS.get(i).getMailingAddress(), customer.getMailingAddress()); + assertEquals(CUSTOMERS.get(i).getLoyaltyPoints(), customer.getLoyaltyPoints()); + i++; + } + + assertEquals(CUSTOMERS.size() + 1, beanReader.getRowNumber()); + + } + + /** + * Tests the read() method with an class that has no default no-arg constructor. + */ + @Test(expected = SuperCsvReflectionException.class) + public void testReadWithNonJavabean() throws IOException { + beanReader.read(Integer.class, HEADER); + } + + /** + * Tests the read() method, with a null bean class. + */ + @Test(expected = NullPointerException.class) + public void testReadWithNullBeanClass() throws IOException { + beanReader.read(null, HEADER); + } + + /** + * Tests the read() method, with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testReadWithNullNameMapping() throws IOException { + beanReader.read(PersonBean.class, (String[]) null); + } + + /** + * Tests the read() method, with a name mapping array that's not the right size. + */ + @Test(expected = IllegalArgumentException.class) + public void testReadWithInvalidSizeNameMapping() throws IOException { + beanReader.getHeader(true); + beanReader.read(PersonBean.class, new String[]{null, "firstName"}); + } + + /** + * Tests the read() method (with processors), with a null bean class. + */ + @Test(expected = NullPointerException.class) + public void testReadProcessorsWithNullBeanClass() throws IOException { + beanReader.read(null, HEADER, READ_PROCESSORS); + } + + /** + * Tests the read() method (with processors), with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testReadProcessorsWithNullNameMapping() throws IOException { + beanReader.read(PersonBean.class, (String[]) null, READ_PROCESSORS); + } + + /** + * Tests the read() method (with processors), with a null cell processor array. + */ + @Test(expected = NullPointerException.class) + public void testReadProcessorsWithNullProcessors() throws IOException { + beanReader.read(PersonBean.class, HEADER, (CellProcessor[]) null); + } + + /** + * Tests the Reader constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullReader() { + new CsvBeanReader((Reader) null, PREFS); + } + + /** + * Tests the Reader constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullPreferences() { + new CsvBeanReader(reader, null); + } + + /** + * Tests the Tokenizer constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullReader() { + new CsvBeanReader((Tokenizer) null, PREFS); + } + + /** + * Tests the Tokenizer constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullPreferences() { + new CsvBeanReader(new Tokenizer(reader, PREFS), null); + } + + /** + * Tests the read() method when invoking the bean's constructor throws IllegalAccessException. + */ + @Test(expected = SuperCsvReflectionException.class) + public void testBeanInstantationThrowingIllegalAccessException() throws IOException { + beanReader.read(IllegalAccessBean.class, HEADER); + } + + /** + * Tests the read() method when invoking a setter throws an Exception. + */ + @SuppressWarnings("resource") + @Test(expected = SuperCsvReflectionException.class) + public void testSetterThrowingException() throws IOException { + new CsvBeanReader(new StringReader("value"), PREFS).read(ExceptionBean.class, "illegalArgument"); + } + + /** + * Bean to test exceptions when invoking setters using CsvBeanReader. + */ + public static class ExceptionBean extends CustomerBean { + + public void setIllegalArgument(String s) { + throw new IllegalArgumentException("i don't like it!"); + } + + } + + /** + * Bean to test exceptions when invoking the constructor using CsvBeanWriter. + */ + public static class IllegalAccessBean extends CustomerBean { + + public IllegalAccessBean() throws IllegalAccessException { + throw new IllegalAccessException("naughty naughty!"); + } + + } +} diff --git a/super-csv/src/test/java/org/supercsv/io/CsvBeanWriterTest.java b/super-csv/src/test/java/org/supercsv/io/CsvBeanWriterTest.java index ac59f344..9b04b8a2 100644 --- a/super-csv/src/test/java/org/supercsv/io/CsvBeanWriterTest.java +++ b/super-csv/src/test/java/org/supercsv/io/CsvBeanWriterTest.java @@ -1,189 +1,189 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.CSV_FILE; -import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.HEADER; -import static org.supercsv.SuperCsvTestUtils.JOHN; -import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.WRITE_PROCESSORS; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.exception.SuperCsvReflectionException; -import org.supercsv.mock.CustomerBean; -import org.supercsv.mock.CustomerStringBean; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests the CsvBeanWriter class. - * - * @author James Bassett - */ -public class CsvBeanWriterTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private Writer writer; - - private CsvBeanWriter beanWriter; - - private CustomerBean customer; - - /** - * Sets up the writer for the tests. - */ - @Before - public void setUp() { - writer = new StringWriter(); - beanWriter = new CsvBeanWriter(writer, PREFS); - customer = new CustomerBean(); - } - - /** - * Closes the bean writer after the test. - */ - @After - public void tearDown() throws IOException { - beanWriter.close(); - } - - /** - * Tests the constructor with a null writer. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWillNullWriter() { - new CsvBeanWriter(null, PREFS); - } - - /** - * Tests the constructor with a null CsvPreference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWillNullPreference() { - new CsvBeanWriter(writer, null); - } - - /** - * Tests the write() method. - */ - @Test - public void testWrite() throws IOException { - beanWriter.writeHeader(HEADER); - for( CustomerStringBean customer : STRING_CUSTOMERS ) { - beanWriter.write(customer, HEADER); - } - beanWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with processors. - */ - @Test - public void testWriteProcessors() throws IOException { - beanWriter.writeHeader(HEADER); - for( CustomerBean customer : CUSTOMERS ) { - beanWriter.write(customer, HEADER, WRITE_PROCESSORS); - } - beanWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with a null bean. - */ - @Test(expected = NullPointerException.class) - public void testWriteWithNullSource() throws IOException { - beanWriter.write(null, HEADER); - } - - /** - * Tests the write() method with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testWriteWithNullNameMappingArray() throws IOException { - beanWriter.write(customer, (String[]) null); - } - - /** - * Tests the write() method with a a name mapping containing nulls (should be empty columns). - */ - @Test - public void testWriteWithNullNameMapping() throws IOException { - - final String[] headerWithNulls = new String[] { "customerNo", null, "firstName", null, "lastName" }; - final String expectedCsv = JOHN.getCustomerNo() + ",," + JOHN.getFirstName() + ",," + JOHN.getLastName() - + "\r\n"; - - beanWriter.write(JOHN, headerWithNulls); - beanWriter.flush(); - assertEquals(expectedCsv, writer.toString()); - } - - /** - * Tests the write() method (with processors) with a null bean. - */ - @Test(expected = NullPointerException.class) - public void testWriteProcessorsWithNullSource() throws IOException { - beanWriter.write(null, HEADER, WRITE_PROCESSORS); - } - - /** - * Tests the write() method (with processors) with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testWriteProcessorsWithNullNameMapping() throws IOException { - beanWriter.write(customer, null, WRITE_PROCESSORS); - } - - /** - * Tests the write() method (with processors) with a null cell processor array. - */ - @Test(expected = NullPointerException.class) - public void testWriteProcessorsWithNullProcessors() throws IOException { - beanWriter.write(customer, HEADER, null); - - } - - /** - * Tests the write() method when a getter throws an Exception. - */ - @Test(expected = SuperCsvReflectionException.class) - public void testGetterThrowingException() throws IOException { - beanWriter.write(new ExceptionBean(), "exception"); - } - - /** - * Bean to test exceptions when invoking getters using CsvBeanWriter. - */ - public static class ExceptionBean extends CustomerBean { - - public String getException() { - throw new RuntimeException("oops!"); - } - - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.CSV_FILE; +import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.HEADER; +import static org.supercsv.SuperCsvTestUtils.JOHN; +import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.WRITE_PROCESSORS; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.exception.SuperCsvReflectionException; +import org.supercsv.mock.CustomerBean; +import org.supercsv.mock.CustomerStringBean; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests the CsvBeanWriter class. + * + * @author James Bassett + */ +public class CsvBeanWriterTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private Writer writer; + + private CsvBeanWriter beanWriter; + + private CustomerBean customer; + + /** + * Sets up the writer for the tests. + */ + @Before + public void setUp() { + writer = new StringWriter(); + beanWriter = new CsvBeanWriter(writer, PREFS); + customer = new CustomerBean(); + } + + /** + * Closes the bean writer after the test. + */ + @After + public void tearDown() throws IOException { + beanWriter.close(); + } + + /** + * Tests the constructor with a null writer. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWillNullWriter() { + new CsvBeanWriter(null, PREFS); + } + + /** + * Tests the constructor with a null CsvPreference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWillNullPreference() { + new CsvBeanWriter(writer, null); + } + + /** + * Tests the write() method. + */ + @Test + public void testWrite() throws IOException { + beanWriter.writeHeader(HEADER); + for( CustomerStringBean customer : STRING_CUSTOMERS ) { + beanWriter.write(customer, HEADER); + } + beanWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with processors. + */ + @Test + public void testWriteProcessors() throws IOException { + beanWriter.writeHeader(HEADER); + for( CustomerBean customer : CUSTOMERS ) { + beanWriter.write(customer, HEADER, WRITE_PROCESSORS); + } + beanWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with a null bean. + */ + @Test(expected = NullPointerException.class) + public void testWriteWithNullSource() throws IOException { + beanWriter.write(null, HEADER); + } + + /** + * Tests the write() method with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testWriteWithNullNameMappingArray() throws IOException { + beanWriter.write(customer, (String[]) null); + } + + /** + * Tests the write() method with a a name mapping containing nulls (should be empty columns). + */ + @Test + public void testWriteWithNullNameMapping() throws IOException { + + final String[] headerWithNulls = new String[] { "customerNo", null, "firstName", null, "lastName" }; + final String expectedCsv = JOHN.getCustomerNo() + ",," + JOHN.getFirstName() + ",," + JOHN.getLastName() + + "\r\n"; + + beanWriter.write(JOHN, headerWithNulls); + beanWriter.flush(); + assertEquals(expectedCsv, writer.toString()); + } + + /** + * Tests the write() method (with processors) with a null bean. + */ + @Test(expected = NullPointerException.class) + public void testWriteProcessorsWithNullSource() throws IOException { + beanWriter.write(null, HEADER, WRITE_PROCESSORS); + } + + /** + * Tests the write() method (with processors) with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testWriteProcessorsWithNullNameMapping() throws IOException { + beanWriter.write(customer, null, WRITE_PROCESSORS); + } + + /** + * Tests the write() method (with processors) with a null cell processor array. + */ + @Test(expected = NullPointerException.class) + public void testWriteProcessorsWithNullProcessors() throws IOException { + beanWriter.write(customer, HEADER, null); + + } + + /** + * Tests the write() method when a getter throws an Exception. + */ + @Test(expected = SuperCsvReflectionException.class) + public void testGetterThrowingException() throws IOException { + beanWriter.write(new ExceptionBean(), "exception"); + } + + /** + * Bean to test exceptions when invoking getters using CsvBeanWriter. + */ + public static class ExceptionBean extends CustomerBean { + + public String getException() { + throw new RuntimeException("oops!"); + } + + } +} diff --git a/super-csv/src/test/java/org/supercsv/io/CsvListReaderTest.java b/super-csv/src/test/java/org/supercsv/io/CsvListReaderTest.java index 2671c19e..6c5b5498 100644 --- a/super-csv/src/test/java/org/supercsv/io/CsvListReaderTest.java +++ b/super-csv/src/test/java/org/supercsv/io/CsvListReaderTest.java @@ -1,221 +1,221 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.CSV_FILE; -import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.HEADER; -import static org.supercsv.SuperCsvTestUtils.READ_PROCESSORS; -import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests the CsvListReader class. - * - * @author James Bassett - */ -public class CsvListReaderTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private Reader reader; - - private CsvListReader listReader; - - private CsvListReader tokenizerListReader; - - /** - * Sets up the reader for the tests. - */ - @Before - public void setUp() { - reader = new StringReader(CSV_FILE); - listReader = new CsvListReader(reader, PREFS); - - final Tokenizer tokenizer = new Tokenizer(reader, PREFS); - tokenizerListReader = new CsvListReader(tokenizer, PREFS); - } - - /** - * Closes the readers after the test. - */ - @After - public void tearDown() throws IOException { - listReader.close(); - tokenizerListReader.close(); - } - - /** - * Tests the read() method. - */ - @Test - public void testRead() throws IOException { - - final String[] header = listReader.getHeader(true); - assertArrayEquals(HEADER, header); - - // read all of the customers in - final List> customers = new ArrayList>(); - List customer; - while( (customer = listReader.read()) != null ) { - customers.add(customer); - } - - // assert that the List for each customer is correct (ensures Lists haven't been modified) - for( int i = 0; i < customers.size(); i++ ) { - customer = customers.get(i); - assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get(0)); - assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get(1)); - assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get(2)); - assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get(3)); - assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get(4)); - assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get(5)); - assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get(6)); - assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get(7)); - assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get(8)); - assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get(9)); - } - - assertEquals(STRING_CUSTOMERS.size() + 1, listReader.getRowNumber()); - } - - /** - * Tests the read() method with processors. - */ - @Test - public void testReadWithProcessors() throws IOException { - - final String[] header = listReader.getHeader(true); - assertArrayEquals(HEADER, header); - - // read all of the customers in - final List> customers = new ArrayList>(); - List customer; - while( (customer = listReader.read(READ_PROCESSORS)) != null ) { - customers.add(customer); - } - - // assert that the List for each customer is correct (ensures Lists haven't been modified) - for( int i = 0; i < customers.size(); i++ ) { - customer = customers.get(i); - assertEquals(CUSTOMERS.get(i).getCustomerNo(), customer.get(0)); - assertEquals(CUSTOMERS.get(i).getFirstName(), customer.get(1)); - assertEquals(CUSTOMERS.get(i).getLastName(), customer.get(2)); - assertEquals(CUSTOMERS.get(i).getBirthDate(), customer.get(3)); - assertEquals(CUSTOMERS.get(i).getMailingAddress(), customer.get(4)); - assertEquals(CUSTOMERS.get(i).getMarried(), customer.get(5)); - assertEquals(CUSTOMERS.get(i).getNumberOfKids(), customer.get(6)); - assertEquals(CUSTOMERS.get(i).getFavouriteQuote(), customer.get(7)); - assertEquals(CUSTOMERS.get(i).getEmail(), customer.get(8)); - assertEquals(CUSTOMERS.get(i).getLoyaltyPoints(), customer.get(9)); - } - - assertEquals(CUSTOMERS.size() + 1, listReader.getRowNumber()); - } - - /** - * Tests the read() method using the tokenizer version of CsvListReader (just to make sure it behaves exactly the - * same as the reader version). - */ - @Test - public void testReadUsingTokenizerReader() throws IOException { - - final String[] header = tokenizerListReader.getHeader(true); - assertArrayEquals(HEADER, header); - - // read all of the customers in - final List> customers = new ArrayList>(); - List customer; - while( (customer = tokenizerListReader.read()) != null ) { - customers.add(customer); - } - - // assert that the List for each customer is correct (ensures Lists haven't been modified) - for( int i = 0; i < customers.size(); i++ ) { - customer = customers.get(i); - assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get(0)); - assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get(1)); - assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get(2)); - assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get(3)); - assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get(4)); - assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get(5)); - assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get(6)); - assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get(7)); - assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get(8)); - assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get(9)); - } - - assertEquals(STRING_CUSTOMERS.size() + 1, tokenizerListReader.getRowNumber()); - } - - /** - * Tests the read() method (with processors), with a null cell processor array. - */ - @Test(expected = NullPointerException.class) - public void testReadProcessorsWithNullProcessors() throws IOException { - listReader.read((CellProcessor[]) null); - } - - /** - * Tests the Reader constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullReader() { - new CsvListReader((Reader) null, PREFS); - } - - /** - * Tests the Reader constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullPreferences() { - new CsvListReader(reader, null); - } - - /** - * Tests the Tokenizer constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullReader() { - new CsvListReader((Tokenizer) null, PREFS); - } - - /** - * Tests the Tokenizer constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullPreferences() { - new CsvListReader(new Tokenizer(reader, PREFS), null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.CSV_FILE; +import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.HEADER; +import static org.supercsv.SuperCsvTestUtils.READ_PROCESSORS; +import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests the CsvListReader class. + * + * @author James Bassett + */ +public class CsvListReaderTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private Reader reader; + + private CsvListReader listReader; + + private CsvListReader tokenizerListReader; + + /** + * Sets up the reader for the tests. + */ + @Before + public void setUp() { + reader = new StringReader(CSV_FILE); + listReader = new CsvListReader(reader, PREFS); + + final Tokenizer tokenizer = new Tokenizer(reader, PREFS); + tokenizerListReader = new CsvListReader(tokenizer, PREFS); + } + + /** + * Closes the readers after the test. + */ + @After + public void tearDown() throws IOException { + listReader.close(); + tokenizerListReader.close(); + } + + /** + * Tests the read() method. + */ + @Test + public void testRead() throws IOException { + + final String[] header = listReader.getHeader(true); + assertArrayEquals(HEADER, header); + + // read all of the customers in + final List> customers = new ArrayList>(); + List customer; + while( (customer = listReader.read()) != null ) { + customers.add(customer); + } + + // assert that the List for each customer is correct (ensures Lists haven't been modified) + for( int i = 0; i < customers.size(); i++ ) { + customer = customers.get(i); + assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get(0)); + assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get(1)); + assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get(2)); + assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get(3)); + assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get(4)); + assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get(5)); + assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get(6)); + assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get(7)); + assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get(8)); + assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get(9)); + } + + assertEquals(STRING_CUSTOMERS.size() + 1, listReader.getRowNumber()); + } + + /** + * Tests the read() method with processors. + */ + @Test + public void testReadWithProcessors() throws IOException { + + final String[] header = listReader.getHeader(true); + assertArrayEquals(HEADER, header); + + // read all of the customers in + final List> customers = new ArrayList>(); + List customer; + while( (customer = listReader.read(READ_PROCESSORS)) != null ) { + customers.add(customer); + } + + // assert that the List for each customer is correct (ensures Lists haven't been modified) + for( int i = 0; i < customers.size(); i++ ) { + customer = customers.get(i); + assertEquals(CUSTOMERS.get(i).getCustomerNo(), customer.get(0)); + assertEquals(CUSTOMERS.get(i).getFirstName(), customer.get(1)); + assertEquals(CUSTOMERS.get(i).getLastName(), customer.get(2)); + assertEquals(CUSTOMERS.get(i).getBirthDate(), customer.get(3)); + assertEquals(CUSTOMERS.get(i).getMailingAddress(), customer.get(4)); + assertEquals(CUSTOMERS.get(i).getMarried(), customer.get(5)); + assertEquals(CUSTOMERS.get(i).getNumberOfKids(), customer.get(6)); + assertEquals(CUSTOMERS.get(i).getFavouriteQuote(), customer.get(7)); + assertEquals(CUSTOMERS.get(i).getEmail(), customer.get(8)); + assertEquals(CUSTOMERS.get(i).getLoyaltyPoints(), customer.get(9)); + } + + assertEquals(CUSTOMERS.size() + 1, listReader.getRowNumber()); + } + + /** + * Tests the read() method using the tokenizer version of CsvListReader (just to make sure it behaves exactly the + * same as the reader version). + */ + @Test + public void testReadUsingTokenizerReader() throws IOException { + + final String[] header = tokenizerListReader.getHeader(true); + assertArrayEquals(HEADER, header); + + // read all of the customers in + final List> customers = new ArrayList>(); + List customer; + while( (customer = tokenizerListReader.read()) != null ) { + customers.add(customer); + } + + // assert that the List for each customer is correct (ensures Lists haven't been modified) + for( int i = 0; i < customers.size(); i++ ) { + customer = customers.get(i); + assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get(0)); + assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get(1)); + assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get(2)); + assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get(3)); + assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get(4)); + assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get(5)); + assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get(6)); + assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get(7)); + assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get(8)); + assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get(9)); + } + + assertEquals(STRING_CUSTOMERS.size() + 1, tokenizerListReader.getRowNumber()); + } + + /** + * Tests the read() method (with processors), with a null cell processor array. + */ + @Test(expected = NullPointerException.class) + public void testReadProcessorsWithNullProcessors() throws IOException { + listReader.read((CellProcessor[]) null); + } + + /** + * Tests the Reader constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullReader() { + new CsvListReader((Reader) null, PREFS); + } + + /** + * Tests the Reader constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullPreferences() { + new CsvListReader(reader, null); + } + + /** + * Tests the Tokenizer constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullReader() { + new CsvListReader((Tokenizer) null, PREFS); + } + + /** + * Tests the Tokenizer constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullPreferences() { + new CsvListReader(new Tokenizer(reader, PREFS), null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/io/CsvListWriterTest.java b/super-csv/src/test/java/org/supercsv/io/CsvListWriterTest.java index 07666206..7995128a 100644 --- a/super-csv/src/test/java/org/supercsv/io/CsvListWriterTest.java +++ b/super-csv/src/test/java/org/supercsv/io/CsvListWriterTest.java @@ -1,194 +1,194 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.CSV_FILE; -import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.HEADER; -import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.WRITE_PROCESSORS; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Arrays; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.mock.CustomerBean; -import org.supercsv.mock.CustomerStringBean; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests the CsvListWriter class. - * - * @author James Bassett - */ -public class CsvListWriterTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private Writer writer; - - private CsvListWriter listWriter; - - /** - * Sets up the writer for the tests. - */ - @Before - public void setUp() { - writer = new StringWriter(); - listWriter = new CsvListWriter(writer, PREFS); - } - - /** - * Closes the list writer after the test. - */ - @After - public void tearDown() throws IOException { - listWriter.close(); - } - - /** - * Tests the write() method with a List and array of CellProcessors. - */ - @Test - public void testWriteListAndProcessors() throws IOException { - listWriter.writeHeader(HEADER); - for( CustomerBean customer : CUSTOMERS ) { - final List customerList = Arrays.asList(new Object[] { customer.getCustomerNo(), - customer.getFirstName(), customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), - customer.getMarried(), customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), - customer.getLoyaltyPoints() }); - listWriter.write(customerList, WRITE_PROCESSORS); - } - listWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with a null List and array of CellProcessors. - */ - @Test(expected = NullPointerException.class) - public void testWriteListAndProcessorsWithNullList() throws IOException { - listWriter.write(null, WRITE_PROCESSORS); - } - - /** - * Tests the write() method with a List and null array of CellProcessors. - */ - @Test(expected = NullPointerException.class) - public void testWriteListAndProcessorsWithNullProcessors() throws IOException { - listWriter.write(Arrays.asList(""), null); - } - - /** - * Tests the write() method with a List. - */ - @Test - public void testWriteList() throws IOException { - listWriter.writeHeader(HEADER); - for( CustomerStringBean customer : STRING_CUSTOMERS ) { - final List customerList = Arrays.asList(new Object[] { customer.getCustomerNo(), - customer.getFirstName(), customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), - customer.getMarried(), customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), - customer.getLoyaltyPoints() }); - listWriter.write(customerList); - } - listWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with a null List. - */ - @Test(expected = NullPointerException.class) - public void testWriteListWithNullList() throws IOException { - listWriter.write((List) null); - } - - /** - * Tests the write() method with an Object array. - */ - @Test - public void testWriteObjectArray() throws Exception { - listWriter.writeHeader(HEADER); - for( CustomerStringBean customer : STRING_CUSTOMERS ) { - final Object[] customerArray = new Object[] { customer.getCustomerNo(), customer.getFirstName(), - customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), - customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), - customer.getLoyaltyPoints() }; - listWriter.write(customerArray); - } - listWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with a null Object array. - */ - @Test(expected = NullPointerException.class) - public void testWriteObjectArrayWithNullArray() throws IOException { - listWriter.write((Object[]) null); - } - - /** - * Tests the write() method with a String array. - */ - @Test - public void testWriteStringArray() throws IOException { - listWriter.writeHeader(HEADER); - for( CustomerStringBean customer : STRING_CUSTOMERS ) { - final String[] customerArray = new String[] { customer.getCustomerNo(), customer.getFirstName(), - customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), - customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), - customer.getLoyaltyPoints() }; - listWriter.write(customerArray); - } - listWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with a null String array. - */ - @Test(expected = NullPointerException.class) - public void testWriteStringArrayWithNullArray() throws IOException { - listWriter.write((String[]) null); - } - - /** - * Tests the constructor with a null writer. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWillNullWriter() { - new CsvListWriter(null, PREFS); - } - - /** - * Tests the constructor with a null CsvPreference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWillNullPreference() { - new CsvListWriter(writer, null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.CSV_FILE; +import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.HEADER; +import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.WRITE_PROCESSORS; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Arrays; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.mock.CustomerBean; +import org.supercsv.mock.CustomerStringBean; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests the CsvListWriter class. + * + * @author James Bassett + */ +public class CsvListWriterTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private Writer writer; + + private CsvListWriter listWriter; + + /** + * Sets up the writer for the tests. + */ + @Before + public void setUp() { + writer = new StringWriter(); + listWriter = new CsvListWriter(writer, PREFS); + } + + /** + * Closes the list writer after the test. + */ + @After + public void tearDown() throws IOException { + listWriter.close(); + } + + /** + * Tests the write() method with a List and array of CellProcessors. + */ + @Test + public void testWriteListAndProcessors() throws IOException { + listWriter.writeHeader(HEADER); + for( CustomerBean customer : CUSTOMERS ) { + final List customerList = Arrays.asList(new Object[] { customer.getCustomerNo(), + customer.getFirstName(), customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), + customer.getMarried(), customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), + customer.getLoyaltyPoints() }); + listWriter.write(customerList, WRITE_PROCESSORS); + } + listWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with a null List and array of CellProcessors. + */ + @Test(expected = NullPointerException.class) + public void testWriteListAndProcessorsWithNullList() throws IOException { + listWriter.write(null, WRITE_PROCESSORS); + } + + /** + * Tests the write() method with a List and null array of CellProcessors. + */ + @Test(expected = NullPointerException.class) + public void testWriteListAndProcessorsWithNullProcessors() throws IOException { + listWriter.write(Arrays.asList(""), null); + } + + /** + * Tests the write() method with a List. + */ + @Test + public void testWriteList() throws IOException { + listWriter.writeHeader(HEADER); + for( CustomerStringBean customer : STRING_CUSTOMERS ) { + final List customerList = Arrays.asList(new Object[] { customer.getCustomerNo(), + customer.getFirstName(), customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), + customer.getMarried(), customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), + customer.getLoyaltyPoints() }); + listWriter.write(customerList); + } + listWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with a null List. + */ + @Test(expected = NullPointerException.class) + public void testWriteListWithNullList() throws IOException { + listWriter.write((List) null); + } + + /** + * Tests the write() method with an Object array. + */ + @Test + public void testWriteObjectArray() throws Exception { + listWriter.writeHeader(HEADER); + for( CustomerStringBean customer : STRING_CUSTOMERS ) { + final Object[] customerArray = new Object[] { customer.getCustomerNo(), customer.getFirstName(), + customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), + customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), + customer.getLoyaltyPoints() }; + listWriter.write(customerArray); + } + listWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with a null Object array. + */ + @Test(expected = NullPointerException.class) + public void testWriteObjectArrayWithNullArray() throws IOException { + listWriter.write((Object[]) null); + } + + /** + * Tests the write() method with a String array. + */ + @Test + public void testWriteStringArray() throws IOException { + listWriter.writeHeader(HEADER); + for( CustomerStringBean customer : STRING_CUSTOMERS ) { + final String[] customerArray = new String[] { customer.getCustomerNo(), customer.getFirstName(), + customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), + customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), + customer.getLoyaltyPoints() }; + listWriter.write(customerArray); + } + listWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with a null String array. + */ + @Test(expected = NullPointerException.class) + public void testWriteStringArrayWithNullArray() throws IOException { + listWriter.write((String[]) null); + } + + /** + * Tests the constructor with a null writer. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWillNullWriter() { + new CsvListWriter(null, PREFS); + } + + /** + * Tests the constructor with a null CsvPreference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWillNullPreference() { + new CsvListWriter(writer, null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/io/CsvMapReaderTest.java b/super-csv/src/test/java/org/supercsv/io/CsvMapReaderTest.java index ddc259fb..a6f2d197 100644 --- a/super-csv/src/test/java/org/supercsv/io/CsvMapReaderTest.java +++ b/super-csv/src/test/java/org/supercsv/io/CsvMapReaderTest.java @@ -1,273 +1,273 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.supercsv.SuperCsvTestUtils.CSV_FILE; -import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.HEADER; -import static org.supercsv.SuperCsvTestUtils.PARTIAL_HEADER; -import static org.supercsv.SuperCsvTestUtils.READ_PROCESSORS; -import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.prefs.CsvPreference; - -/** - * Tests the CsvMapReader class. - * - * @author James Bassett - */ -public class CsvMapReaderTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private Reader reader; - - private CsvMapReader mapReader; - - private CsvMapReader tokenizerMapReader; - - /** - * Sets up the reader for the tests. - */ - @Before - public void setUp() { - reader = new StringReader(CSV_FILE); - mapReader = new CsvMapReader(reader, PREFS); - - final Tokenizer tokenizer = new Tokenizer(reader, PREFS); - tokenizerMapReader = new CsvMapReader(tokenizer, PREFS); - } - - /** - * Closes the readers after the test. - */ - @After - public void tearDown() throws IOException { - mapReader.close(); - tokenizerMapReader.close(); - } - - /** - * Tests the read() method. - */ - @Test - public void testRead() throws IOException { - - final String[] header = mapReader.getHeader(true); - assertArrayEquals(HEADER, header); - - int i = 0; - Map customer; - while( (customer = mapReader.read(header)) != null ) { - assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get("customerNo")); - assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); - assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get("lastName")); - assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get("birthDate")); - assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get("mailingAddress")); - assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get("married")); - assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get("numberOfKids")); - assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get("favouriteQuote")); - assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get("email")); - assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get("loyaltyPoints")); - i++; - } - - assertEquals(STRING_CUSTOMERS.size() + 1, mapReader.getRowNumber()); - } - - /** - * Tests the read() method, but only mapping a few columns. - */ - @Test - public void testPartialRead() throws IOException { - - assertArrayEquals(HEADER, mapReader.getHeader(true)); - - int i = 0; - Map customer; - while( (customer = mapReader.read(PARTIAL_HEADER)) != null ) { - assertNull(customer.get("customerNo")); - assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); - assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get("lastName")); - assertNull(customer.get("birthDate")); - assertNull(customer.get("mailingAddress")); - assertNull(customer.get("married")); - assertNull(customer.get("numberOfKids")); - assertNull(customer.get("favouriteQuote")); - assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get("email")); - assertNull(customer.get("loyaltyPoints")); - i++; - } - - assertEquals(STRING_CUSTOMERS.size() + 1, mapReader.getRowNumber()); - } - - /** - * Tests the read() method with processors. - */ - @Test - public void testReadWithProcessors() throws IOException { - - final String[] header = mapReader.getHeader(true); - assertArrayEquals(HEADER, header); - - int i = 0; - Map customer; - while( (customer = mapReader.read(header, READ_PROCESSORS)) != null ) { - assertEquals(CUSTOMERS.get(i).getCustomerNo(), customer.get("customerNo")); - assertEquals(CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); - assertEquals(CUSTOMERS.get(i).getLastName(), customer.get("lastName")); - assertEquals(CUSTOMERS.get(i).getBirthDate(), customer.get("birthDate")); - assertEquals(CUSTOMERS.get(i).getMailingAddress(), customer.get("mailingAddress")); - assertEquals(CUSTOMERS.get(i).getMarried(), customer.get("married")); - assertEquals(CUSTOMERS.get(i).getNumberOfKids(), customer.get("numberOfKids")); - assertEquals(CUSTOMERS.get(i).getFavouriteQuote(), customer.get("favouriteQuote")); - assertEquals(CUSTOMERS.get(i).getEmail(), customer.get("email")); - assertEquals(CUSTOMERS.get(i).getLoyaltyPoints(), customer.get("loyaltyPoints")); - i++; - } - - assertEquals(CUSTOMERS.size() + 1, mapReader.getRowNumber()); - } - - /** - * Tests the read() method with processors, but only mapping a few columns. - */ - @Test - public void testPartialReadWithProcessors() throws IOException { - - assertArrayEquals(HEADER, mapReader.getHeader(true)); - - int i = 0; - Map customer; - while( (customer = mapReader.read(PARTIAL_HEADER, READ_PROCESSORS)) != null ) { - assertNull(customer.get("customerNo")); - assertEquals(CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); - assertEquals(CUSTOMERS.get(i).getLastName(), customer.get("lastName")); - assertNull(customer.get("birthDate")); - assertNull(customer.get("mailingAddress")); - assertNull(customer.get("married")); - assertNull(customer.get("numberOfKids")); - assertNull(customer.get("favouriteQuote")); - assertEquals(CUSTOMERS.get(i).getEmail(), customer.get("email")); - assertNull(customer.get("loyaltyPoints")); - i++; - } - - assertEquals(CUSTOMERS.size() + 1, mapReader.getRowNumber()); - } - - /** - * Tests the read() method using the tokenizer version of CsvMapReader (just to make sure it behaves exactly the - * same as the reader version). - */ - @Test - public void testReadUsingTokenizerReader() throws IOException { - - final String[] header = tokenizerMapReader.getHeader(true); - assertArrayEquals(HEADER, header); - - int i = 0; - Map customer; - while( (customer = tokenizerMapReader.read(HEADER)) != null ) { - assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get("customerNo")); - assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); - assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get("lastName")); - assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get("birthDate")); - assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get("mailingAddress")); - assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get("married")); - assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get("numberOfKids")); - assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get("favouriteQuote")); - assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get("email")); - assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get("loyaltyPoints")); - i++; - } - - assertEquals(STRING_CUSTOMERS.size() + 1, tokenizerMapReader.getRowNumber()); - } - - /** - * Tests the read() method, with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testReadWithNullNameMapping() throws IOException { - mapReader.read((String[]) null); - } - - /** - * Tests the read() method (with processors), with a null cell processor array. - */ - @Test(expected = NullPointerException.class) - public void testReadProcessorsWithNullProcessors() throws IOException { - mapReader.read(HEADER, null); - } - - /** - * Tests the read() method (with processors), with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testReadProcessorsWithNullNameMapping() throws IOException { - mapReader.read((String[]) null, READ_PROCESSORS); - } - - /** - * Tests the Reader constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullReader() { - new CsvMapReader((Reader) null, PREFS); - } - - /** - * Tests the Reader constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testReaderConstructorWithNullPreferences() { - new CsvMapReader(reader, null); - } - - /** - * Tests the Tokenizer constructor with a null Reader. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullReader() { - new CsvMapReader((Tokenizer) null, PREFS); - } - - /** - * Tests the Tokenizer constructor with a null preference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testTokenizerConstructorWithNullPreferences() { - new CsvMapReader(new Tokenizer(reader, PREFS), null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.supercsv.SuperCsvTestUtils.CSV_FILE; +import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.HEADER; +import static org.supercsv.SuperCsvTestUtils.PARTIAL_HEADER; +import static org.supercsv.SuperCsvTestUtils.READ_PROCESSORS; +import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.prefs.CsvPreference; + +/** + * Tests the CsvMapReader class. + * + * @author James Bassett + */ +public class CsvMapReaderTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private Reader reader; + + private CsvMapReader mapReader; + + private CsvMapReader tokenizerMapReader; + + /** + * Sets up the reader for the tests. + */ + @Before + public void setUp() { + reader = new StringReader(CSV_FILE); + mapReader = new CsvMapReader(reader, PREFS); + + final Tokenizer tokenizer = new Tokenizer(reader, PREFS); + tokenizerMapReader = new CsvMapReader(tokenizer, PREFS); + } + + /** + * Closes the readers after the test. + */ + @After + public void tearDown() throws IOException { + mapReader.close(); + tokenizerMapReader.close(); + } + + /** + * Tests the read() method. + */ + @Test + public void testRead() throws IOException { + + final String[] header = mapReader.getHeader(true); + assertArrayEquals(HEADER, header); + + int i = 0; + Map customer; + while( (customer = mapReader.read(header)) != null ) { + assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get("customerNo")); + assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); + assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get("lastName")); + assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get("birthDate")); + assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get("mailingAddress")); + assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get("married")); + assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get("numberOfKids")); + assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get("favouriteQuote")); + assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get("email")); + assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get("loyaltyPoints")); + i++; + } + + assertEquals(STRING_CUSTOMERS.size() + 1, mapReader.getRowNumber()); + } + + /** + * Tests the read() method, but only mapping a few columns. + */ + @Test + public void testPartialRead() throws IOException { + + assertArrayEquals(HEADER, mapReader.getHeader(true)); + + int i = 0; + Map customer; + while( (customer = mapReader.read(PARTIAL_HEADER)) != null ) { + assertNull(customer.get("customerNo")); + assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); + assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get("lastName")); + assertNull(customer.get("birthDate")); + assertNull(customer.get("mailingAddress")); + assertNull(customer.get("married")); + assertNull(customer.get("numberOfKids")); + assertNull(customer.get("favouriteQuote")); + assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get("email")); + assertNull(customer.get("loyaltyPoints")); + i++; + } + + assertEquals(STRING_CUSTOMERS.size() + 1, mapReader.getRowNumber()); + } + + /** + * Tests the read() method with processors. + */ + @Test + public void testReadWithProcessors() throws IOException { + + final String[] header = mapReader.getHeader(true); + assertArrayEquals(HEADER, header); + + int i = 0; + Map customer; + while( (customer = mapReader.read(header, READ_PROCESSORS)) != null ) { + assertEquals(CUSTOMERS.get(i).getCustomerNo(), customer.get("customerNo")); + assertEquals(CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); + assertEquals(CUSTOMERS.get(i).getLastName(), customer.get("lastName")); + assertEquals(CUSTOMERS.get(i).getBirthDate(), customer.get("birthDate")); + assertEquals(CUSTOMERS.get(i).getMailingAddress(), customer.get("mailingAddress")); + assertEquals(CUSTOMERS.get(i).getMarried(), customer.get("married")); + assertEquals(CUSTOMERS.get(i).getNumberOfKids(), customer.get("numberOfKids")); + assertEquals(CUSTOMERS.get(i).getFavouriteQuote(), customer.get("favouriteQuote")); + assertEquals(CUSTOMERS.get(i).getEmail(), customer.get("email")); + assertEquals(CUSTOMERS.get(i).getLoyaltyPoints(), customer.get("loyaltyPoints")); + i++; + } + + assertEquals(CUSTOMERS.size() + 1, mapReader.getRowNumber()); + } + + /** + * Tests the read() method with processors, but only mapping a few columns. + */ + @Test + public void testPartialReadWithProcessors() throws IOException { + + assertArrayEquals(HEADER, mapReader.getHeader(true)); + + int i = 0; + Map customer; + while( (customer = mapReader.read(PARTIAL_HEADER, READ_PROCESSORS)) != null ) { + assertNull(customer.get("customerNo")); + assertEquals(CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); + assertEquals(CUSTOMERS.get(i).getLastName(), customer.get("lastName")); + assertNull(customer.get("birthDate")); + assertNull(customer.get("mailingAddress")); + assertNull(customer.get("married")); + assertNull(customer.get("numberOfKids")); + assertNull(customer.get("favouriteQuote")); + assertEquals(CUSTOMERS.get(i).getEmail(), customer.get("email")); + assertNull(customer.get("loyaltyPoints")); + i++; + } + + assertEquals(CUSTOMERS.size() + 1, mapReader.getRowNumber()); + } + + /** + * Tests the read() method using the tokenizer version of CsvMapReader (just to make sure it behaves exactly the + * same as the reader version). + */ + @Test + public void testReadUsingTokenizerReader() throws IOException { + + final String[] header = tokenizerMapReader.getHeader(true); + assertArrayEquals(HEADER, header); + + int i = 0; + Map customer; + while( (customer = tokenizerMapReader.read(HEADER)) != null ) { + assertEquals(STRING_CUSTOMERS.get(i).getCustomerNo(), customer.get("customerNo")); + assertEquals(STRING_CUSTOMERS.get(i).getFirstName(), customer.get("firstName")); + assertEquals(STRING_CUSTOMERS.get(i).getLastName(), customer.get("lastName")); + assertEquals(STRING_CUSTOMERS.get(i).getBirthDate(), customer.get("birthDate")); + assertEquals(STRING_CUSTOMERS.get(i).getMailingAddress(), customer.get("mailingAddress")); + assertEquals(STRING_CUSTOMERS.get(i).getMarried(), customer.get("married")); + assertEquals(STRING_CUSTOMERS.get(i).getNumberOfKids(), customer.get("numberOfKids")); + assertEquals(STRING_CUSTOMERS.get(i).getFavouriteQuote(), customer.get("favouriteQuote")); + assertEquals(STRING_CUSTOMERS.get(i).getEmail(), customer.get("email")); + assertEquals(STRING_CUSTOMERS.get(i).getLoyaltyPoints(), customer.get("loyaltyPoints")); + i++; + } + + assertEquals(STRING_CUSTOMERS.size() + 1, tokenizerMapReader.getRowNumber()); + } + + /** + * Tests the read() method, with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testReadWithNullNameMapping() throws IOException { + mapReader.read((String[]) null); + } + + /** + * Tests the read() method (with processors), with a null cell processor array. + */ + @Test(expected = NullPointerException.class) + public void testReadProcessorsWithNullProcessors() throws IOException { + mapReader.read(HEADER, null); + } + + /** + * Tests the read() method (with processors), with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testReadProcessorsWithNullNameMapping() throws IOException { + mapReader.read((String[]) null, READ_PROCESSORS); + } + + /** + * Tests the Reader constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullReader() { + new CsvMapReader((Reader) null, PREFS); + } + + /** + * Tests the Reader constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testReaderConstructorWithNullPreferences() { + new CsvMapReader(reader, null); + } + + /** + * Tests the Tokenizer constructor with a null Reader. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullReader() { + new CsvMapReader((Tokenizer) null, PREFS); + } + + /** + * Tests the Tokenizer constructor with a null preference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testTokenizerConstructorWithNullPreferences() { + new CsvMapReader(new Tokenizer(reader, PREFS), null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/io/CsvMapWriterTest.java b/super-csv/src/test/java/org/supercsv/io/CsvMapWriterTest.java index aad82f69..5513dce0 100644 --- a/super-csv/src/test/java/org/supercsv/io/CsvMapWriterTest.java +++ b/super-csv/src/test/java/org/supercsv/io/CsvMapWriterTest.java @@ -1,174 +1,174 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertEquals; -import static org.supercsv.SuperCsvTestUtils.CSV_FILE; -import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.HEADER; -import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; -import static org.supercsv.SuperCsvTestUtils.WRITE_PROCESSORS; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.mock.CustomerBean; -import org.supercsv.mock.CustomerStringBean; -import org.supercsv.prefs.CsvPreference; -import org.supercsv.util.Util; - -/** - * Tests the CsvMapWriter class. - * - * @author James Bassett - */ -public class CsvMapWriterTest { - - private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; - - private Writer writer; - - private CsvMapWriter mapWriter; - - /** - * Sets up the writer for the tests. - */ - @Before - public void setUp() { - writer = new StringWriter(); - mapWriter = new CsvMapWriter(writer, PREFS); - } - - /** - * Closes the map writer after the test. - */ - @After - public void tearDown() throws IOException { - mapWriter.close(); - } - - /** - * Tests the constructor with a null writer. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWillNullWriter() { - new CsvMapWriter(null, PREFS); - } - - /** - * Tests the constructor with a null CsvPreference. - */ - @SuppressWarnings("resource") - @Test(expected = NullPointerException.class) - public void testConstructorWillNullPreference() { - new CsvMapWriter(writer, null); - } - - /** - * Tests the write() method. - * - * @throws IOException - */ - @Test - public void testWrite() throws IOException { - mapWriter.writeHeader(HEADER); - for( CustomerStringBean customer : STRING_CUSTOMERS ) { - Map customerMap = new HashMap(); - Util.filterListToMap( - customerMap, - HEADER, - Arrays.asList(new String[] { customer.getCustomerNo(), customer.getFirstName(), customer.getLastName(), - customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), - customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), - customer.getLoyaltyPoints() })); - mapWriter.write(customerMap, HEADER); - } - mapWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with processors. - */ - @Test - public void testWriteProcessors() throws IOException { - mapWriter.writeHeader(HEADER); - for( CustomerBean customer : CUSTOMERS ) { - Map customerMap = new HashMap(); - Util.filterListToMap( - customerMap, - HEADER, - Arrays.asList(new Object[] { customer.getCustomerNo(), customer.getFirstName(), customer.getLastName(), - customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), - customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), - customer.getLoyaltyPoints() })); - mapWriter.write(customerMap, HEADER, WRITE_PROCESSORS); - } - mapWriter.flush(); - assertEquals(CSV_FILE, writer.toString()); - } - - /** - * Tests the write() method with a null map. - */ - @Test(expected = NullPointerException.class) - public void testWriteWithNullMap() throws IOException { - mapWriter.write(null, HEADER); - } - - /** - * Tests the write() method with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testWriteWithNullNameMapping() throws IOException { - mapWriter.write(new HashMap(), (String[]) null); - } - - /** - * Tests the write() method (with processors) with a null map. - */ - @Test(expected = NullPointerException.class) - public void testWriteProcessorsWithNullMap() throws IOException { - mapWriter.write(null, HEADER, WRITE_PROCESSORS); - } - - /** - * Tests the write() method (with processors) with a null name mapping array. - */ - @Test(expected = NullPointerException.class) - public void testWriteProcessorsWithNullNameMapping() throws IOException { - mapWriter.write(new HashMap(), null, WRITE_PROCESSORS); - - } - - /** - * Tests the write() method (with processors) with a null cell processor array. - */ - @Test(expected = NullPointerException.class) - public void testWriteProcessorsWithNullProcessors() throws IOException { - mapWriter.write(new HashMap(), HEADER, null); - - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertEquals; +import static org.supercsv.SuperCsvTestUtils.CSV_FILE; +import static org.supercsv.SuperCsvTestUtils.CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.HEADER; +import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS; +import static org.supercsv.SuperCsvTestUtils.WRITE_PROCESSORS; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.mock.CustomerBean; +import org.supercsv.mock.CustomerStringBean; +import org.supercsv.prefs.CsvPreference; +import org.supercsv.util.Util; + +/** + * Tests the CsvMapWriter class. + * + * @author James Bassett + */ +public class CsvMapWriterTest { + + private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE; + + private Writer writer; + + private CsvMapWriter mapWriter; + + /** + * Sets up the writer for the tests. + */ + @Before + public void setUp() { + writer = new StringWriter(); + mapWriter = new CsvMapWriter(writer, PREFS); + } + + /** + * Closes the map writer after the test. + */ + @After + public void tearDown() throws IOException { + mapWriter.close(); + } + + /** + * Tests the constructor with a null writer. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWillNullWriter() { + new CsvMapWriter(null, PREFS); + } + + /** + * Tests the constructor with a null CsvPreference. + */ + @SuppressWarnings("resource") + @Test(expected = NullPointerException.class) + public void testConstructorWillNullPreference() { + new CsvMapWriter(writer, null); + } + + /** + * Tests the write() method. + * + * @throws IOException + */ + @Test + public void testWrite() throws IOException { + mapWriter.writeHeader(HEADER); + for( CustomerStringBean customer : STRING_CUSTOMERS ) { + Map customerMap = new HashMap(); + Util.filterListToMap( + customerMap, + HEADER, + Arrays.asList(new String[] { customer.getCustomerNo(), customer.getFirstName(), customer.getLastName(), + customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), + customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), + customer.getLoyaltyPoints() })); + mapWriter.write(customerMap, HEADER); + } + mapWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with processors. + */ + @Test + public void testWriteProcessors() throws IOException { + mapWriter.writeHeader(HEADER); + for( CustomerBean customer : CUSTOMERS ) { + Map customerMap = new HashMap(); + Util.filterListToMap( + customerMap, + HEADER, + Arrays.asList(new Object[] { customer.getCustomerNo(), customer.getFirstName(), customer.getLastName(), + customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(), + customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(), + customer.getLoyaltyPoints() })); + mapWriter.write(customerMap, HEADER, WRITE_PROCESSORS); + } + mapWriter.flush(); + assertEquals(CSV_FILE, writer.toString()); + } + + /** + * Tests the write() method with a null map. + */ + @Test(expected = NullPointerException.class) + public void testWriteWithNullMap() throws IOException { + mapWriter.write(null, HEADER); + } + + /** + * Tests the write() method with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testWriteWithNullNameMapping() throws IOException { + mapWriter.write(new HashMap(), (String[]) null); + } + + /** + * Tests the write() method (with processors) with a null map. + */ + @Test(expected = NullPointerException.class) + public void testWriteProcessorsWithNullMap() throws IOException { + mapWriter.write(null, HEADER, WRITE_PROCESSORS); + } + + /** + * Tests the write() method (with processors) with a null name mapping array. + */ + @Test(expected = NullPointerException.class) + public void testWriteProcessorsWithNullNameMapping() throws IOException { + mapWriter.write(new HashMap(), null, WRITE_PROCESSORS); + + } + + /** + * Tests the write() method (with processors) with a null cell processor array. + */ + @Test(expected = NullPointerException.class) + public void testWriteProcessorsWithNullProcessors() throws IOException { + mapWriter.write(new HashMap(), HEADER, null); + + } + +} diff --git a/super-csv/src/test/java/org/supercsv/io/TokenizerTest.java b/super-csv/src/test/java/org/supercsv/io/TokenizerTest.java index 01e40051..13153358 100644 --- a/super-csv/src/test/java/org/supercsv/io/TokenizerTest.java +++ b/super-csv/src/test/java/org/supercsv/io/TokenizerTest.java @@ -1,422 +1,422 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.io; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.supercsv.prefs.CsvPreference.EXCEL_PREFERENCE; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.prefs.CsvPreference; - -public class TokenizerTest { - - private static final CsvPreference NORMAL_PREFERENCE = EXCEL_PREFERENCE; - private static final CsvPreference SPACES_NEED_QUOTES_PREFERENCE = new CsvPreference.Builder(EXCEL_PREFERENCE) - .surroundingSpacesNeedQuotes(true).build(); - - private Tokenizer tokenizer; - private List columns; - - /** - * Sets up the columns List for the test. - * - * @throws Exception - */ - @Before - public void setUp() { - columns = new ArrayList(); - } - - /** - * Tidies up after the test. - */ - @After - public void tearDown() throws IOException { - if( tokenizer != null ) { - tokenizer.close(); - } - } - - /** - * Creates a Tokenizer with the input and preferences. - * - * @param input - * the input String - * @param preference - * the preferences - * @return the Tokenizer - */ - private static Tokenizer createTokenizer(String input, CsvPreference preference) { - final Reader r = input != null ? new StringReader(input) : null; - return new Tokenizer(r, preference); - } - - /** - * Tests the constructor with a null Reader (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructorWithNullReader() throws Exception { - createTokenizer(null, NORMAL_PREFERENCE); - } - - /** - * Tests the constructor with a null CsvPreference (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructorWithNullPreferences() throws Exception { - createTokenizer("", null); - } - - /** - * Tests the readColumns() method with null List (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testReadColumnsWithNullList() throws Exception { - tokenizer = createTokenizer("", NORMAL_PREFERENCE); - tokenizer.readColumns(null); - } - - /** - * Tests the getPreferences() method. - */ - @Test() - public void testGetPreferences() throws Exception { - tokenizer = createTokenizer("", NORMAL_PREFERENCE); - CsvPreference prefs = tokenizer.getPreferences(); - assertEquals(NORMAL_PREFERENCE.getDelimiterChar(), prefs.getDelimiterChar()); - assertEquals(NORMAL_PREFERENCE.getEndOfLineSymbols(), prefs.getEndOfLineSymbols()); - assertEquals(NORMAL_PREFERENCE.getQuoteChar(), prefs.getQuoteChar()); - assertEquals(NORMAL_PREFERENCE.isSurroundingSpacesNeedQuotes(), prefs.isSurroundingSpacesNeedQuotes()); - } - - /** - * Tests the readColumns() method with no data. - */ - @Test - public void testReadColumnsWithNoData() throws Exception { - final String input = ""; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.isEmpty()); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests that the readColumns() method skips over blank lines at the start of a file. - */ - @Test - public void testBlankLinesAtStart() throws Exception { - - final String input = "\n\nthis is the third line\n"; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 1); - assertEquals("this is the third line", columns.get(0)); - assertEquals(3, tokenizer.getLineNumber()); - assertEquals("this is the third line", tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method a quoted section has text surrounding it. This is not technically valid CSV, but - * the tokenizer is lenient enough to allow it (it will just unescape the quoted section). - */ - @Test - public void testQuotedFieldWithSurroundingText() throws Exception { - - final String input = "surrounding \"quoted\" text"; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 1); - assertEquals("surrounding quoted text", columns.get(0)); - assertEquals(1, tokenizer.getLineNumber()); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // same result when surrounding spaces require quotes - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 1); - assertEquals("surrounding quoted text", columns.get(0)); - assertEquals(1, tokenizer.getLineNumber()); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method when a quoted section with text after it. This is not technically valid CSV, but - * the tokenizer is lenient enough to allow it (it will just unescape the quoted section). - */ - @Test - public void testQuotedFieldWithTextAfter() throws Exception { - - // illegal char after quoted section - final String input = "\"quoted on 2 lines\nand afterward some\" text"; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertEquals(1, columns.size()); - assertEquals("quoted on 2 lines\nand afterward some text", columns.get(0)); - assertEquals(2, tokenizer.getLineNumber()); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // should have exactly the same result when surrounding spaces need quotes - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertEquals(1, columns.size()); - assertEquals("quoted on 2 lines\nand afterward some text", columns.get(0)); - assertEquals(2, tokenizer.getLineNumber()); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method when EOF is reached within quote scope. - */ - @Test - public void testQuotedFieldWithUnexpectedEOF() throws Exception { - - // EOF reached within quote scope - final String input = "\"quoted spanning\ntwo lines with EOF reached before another quote"; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - try { - tokenizer.readColumns(columns); - fail("should have thrown SuperCsvException"); - } - catch(SuperCsvException e) { - assertEquals("unexpected end of file while reading quoted column beginning on line 1 and ending on line 2", - e.getMessage()); - } - } - - /** - * Tests the readColumns() method with a leading space before the first quoted field. This is not technically valid - * CSV, but the tokenizer is lenient enough to allow it. The leading spaces will be trimmed off when surrounding - * spaces require quotes, otherwise they will be part of the field. - */ - @Test - public void testQuotedFirstFieldWithLeadingSpace() throws Exception { - - // leading spaces should be preserved - final String input = " \"quoted with leading spaces\",two"; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 2); - assertEquals(" quoted with leading spaces", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // same input when surrounding spaces require quotes (leading spaces trimmed) - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 2); - assertEquals("quoted with leading spaces", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method with a leading space before the last quoted field. This is not technically valid - * CSV, but the tokenizer is lenient enough to allow it. The leading spaces will be trimmed off when surrounding - * spaces require quotes, otherwise they will be part of the field. - */ - @Test - public void testQuotedLastFieldWithLeadingSpace() throws Exception { - - // last field has a leading space before quote (should be preserved) - final String input = "one,two, \"quoted with leading spaces\""; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals("one", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals(" quoted with leading spaces", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // leading space should be trimmed off - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals("one", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals("quoted with leading spaces", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method with a trailing space after the first quoted field. This is not technically valid - * CSV, but the tokenizer is lenient enough to allow it. The trailing spaces will be trimmed off when surrounding - * spaces require quotes, otherwise they will be part of the field. - */ - @Test - public void testQuotedFirstFieldWithTrailingSpace() throws Exception { - - // first field has a leading space before quote (should be preserved) - final String input = "\"quoted with trailing spaces\" ,two"; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 2); - assertEquals("quoted with trailing spaces ", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // trailing spaces should be trimmed - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 2); - assertEquals("quoted with trailing spaces", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method with a trailing space after the last quoted field. This is not technically valid - * CSV, but the tokenizer is lenient enough to allow it. The trailing spaces will be trimmed off when surrounding - * spaces require quotes, otherwise they will be part of the field. - */ - @Test - public void testQuotedLastFieldWithTrailingSpace() throws Exception { - - // last field has a leading space before quote (should be preserved) - final String input = "one,two,\"quoted with trailing spaces\" "; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals("one", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals("quoted with trailing spaces ", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // trailing spaces should be trimmed off - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals("one", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals("quoted with trailing spaces", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method with a variety of quoted spaces. - */ - @Test - public void testQuotedSpaces() throws Exception { - - final String input = "\" one \",\" two \",\" three \""; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals(" one ", columns.get(0)); - assertEquals(" two ", columns.get(1)); - assertEquals(" three ", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // same input when surrounding spaces require quotes (results should be identical) - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals(" one ", columns.get(0)); - assertEquals(" two ", columns.get(1)); - assertEquals(" three ", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method with a variety of unquoted spaces. - */ - @Test - public void testSpaces() throws Exception { - - final String input = " one , two , three "; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals(" one ", columns.get(0)); - assertEquals(" two ", columns.get(1)); - assertEquals(" three ", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // same input when surrounding spaces require quotes - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals("one", columns.get(0)); - assertEquals("two", columns.get(1)); - assertEquals("three", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method with a variety of spaces and tabs. - */ - @Test - public void testSpacesAndTabs() throws Exception { - - // tabs should never be trimmed - final String input = "\t, \tone\t , \ttwo\t , \tthree\t "; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 4); - assertEquals("\t", columns.get(0)); - assertEquals(" \tone\t ", columns.get(1)); - assertEquals(" \ttwo\t ", columns.get(2)); - assertEquals(" \tthree\t ", columns.get(3)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // same input when surrounding spaces require quotes - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 4); - assertEquals("\t", columns.get(0)); - assertEquals("\tone\t", columns.get(1)); - assertEquals("\ttwo\t", columns.get(2)); - assertEquals("\tthree\t", columns.get(3)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - - /** - * Tests the readColumns() method with spaces between words. - */ - @Test - public void testSpacesBetweenWords() throws Exception { - - final String input = " one partridge , two turtle doves , three french hens "; - tokenizer = createTokenizer(input, NORMAL_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals(" one partridge ", columns.get(0)); - assertEquals(" two turtle doves ", columns.get(1)); - assertEquals(" three french hens ", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - - // same input when surrounding spaces require quotes - tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); - tokenizer.readColumns(columns); - assertTrue(columns.size() == 3); - assertEquals("one partridge", columns.get(0)); - assertEquals("two turtle doves", columns.get(1)); - assertEquals("three french hens", columns.get(2)); - assertEquals(input, tokenizer.getUntokenizedRow()); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.io; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.supercsv.prefs.CsvPreference.EXCEL_PREFERENCE; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.prefs.CsvPreference; + +public class TokenizerTest { + + private static final CsvPreference NORMAL_PREFERENCE = EXCEL_PREFERENCE; + private static final CsvPreference SPACES_NEED_QUOTES_PREFERENCE = new CsvPreference.Builder(EXCEL_PREFERENCE) + .surroundingSpacesNeedQuotes(true).build(); + + private Tokenizer tokenizer; + private List columns; + + /** + * Sets up the columns List for the test. + * + * @throws Exception + */ + @Before + public void setUp() { + columns = new ArrayList(); + } + + /** + * Tidies up after the test. + */ + @After + public void tearDown() throws IOException { + if( tokenizer != null ) { + tokenizer.close(); + } + } + + /** + * Creates a Tokenizer with the input and preferences. + * + * @param input + * the input String + * @param preference + * the preferences + * @return the Tokenizer + */ + private static Tokenizer createTokenizer(String input, CsvPreference preference) { + final Reader r = input != null ? new StringReader(input) : null; + return new Tokenizer(r, preference); + } + + /** + * Tests the constructor with a null Reader (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructorWithNullReader() throws Exception { + createTokenizer(null, NORMAL_PREFERENCE); + } + + /** + * Tests the constructor with a null CsvPreference (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructorWithNullPreferences() throws Exception { + createTokenizer("", null); + } + + /** + * Tests the readColumns() method with null List (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testReadColumnsWithNullList() throws Exception { + tokenizer = createTokenizer("", NORMAL_PREFERENCE); + tokenizer.readColumns(null); + } + + /** + * Tests the getPreferences() method. + */ + @Test() + public void testGetPreferences() throws Exception { + tokenizer = createTokenizer("", NORMAL_PREFERENCE); + CsvPreference prefs = tokenizer.getPreferences(); + assertEquals(NORMAL_PREFERENCE.getDelimiterChar(), prefs.getDelimiterChar()); + assertEquals(NORMAL_PREFERENCE.getEndOfLineSymbols(), prefs.getEndOfLineSymbols()); + assertEquals(NORMAL_PREFERENCE.getQuoteChar(), prefs.getQuoteChar()); + assertEquals(NORMAL_PREFERENCE.isSurroundingSpacesNeedQuotes(), prefs.isSurroundingSpacesNeedQuotes()); + } + + /** + * Tests the readColumns() method with no data. + */ + @Test + public void testReadColumnsWithNoData() throws Exception { + final String input = ""; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.isEmpty()); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests that the readColumns() method skips over blank lines at the start of a file. + */ + @Test + public void testBlankLinesAtStart() throws Exception { + + final String input = "\n\nthis is the third line\n"; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 1); + assertEquals("this is the third line", columns.get(0)); + assertEquals(3, tokenizer.getLineNumber()); + assertEquals("this is the third line", tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method a quoted section has text surrounding it. This is not technically valid CSV, but + * the tokenizer is lenient enough to allow it (it will just unescape the quoted section). + */ + @Test + public void testQuotedFieldWithSurroundingText() throws Exception { + + final String input = "surrounding \"quoted\" text"; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 1); + assertEquals("surrounding quoted text", columns.get(0)); + assertEquals(1, tokenizer.getLineNumber()); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // same result when surrounding spaces require quotes + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 1); + assertEquals("surrounding quoted text", columns.get(0)); + assertEquals(1, tokenizer.getLineNumber()); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method when a quoted section with text after it. This is not technically valid CSV, but + * the tokenizer is lenient enough to allow it (it will just unescape the quoted section). + */ + @Test + public void testQuotedFieldWithTextAfter() throws Exception { + + // illegal char after quoted section + final String input = "\"quoted on 2 lines\nand afterward some\" text"; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertEquals(1, columns.size()); + assertEquals("quoted on 2 lines\nand afterward some text", columns.get(0)); + assertEquals(2, tokenizer.getLineNumber()); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // should have exactly the same result when surrounding spaces need quotes + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertEquals(1, columns.size()); + assertEquals("quoted on 2 lines\nand afterward some text", columns.get(0)); + assertEquals(2, tokenizer.getLineNumber()); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method when EOF is reached within quote scope. + */ + @Test + public void testQuotedFieldWithUnexpectedEOF() throws Exception { + + // EOF reached within quote scope + final String input = "\"quoted spanning\ntwo lines with EOF reached before another quote"; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + try { + tokenizer.readColumns(columns); + fail("should have thrown SuperCsvException"); + } + catch(SuperCsvException e) { + assertEquals("unexpected end of file while reading quoted column beginning on line 1 and ending on line 2", + e.getMessage()); + } + } + + /** + * Tests the readColumns() method with a leading space before the first quoted field. This is not technically valid + * CSV, but the tokenizer is lenient enough to allow it. The leading spaces will be trimmed off when surrounding + * spaces require quotes, otherwise they will be part of the field. + */ + @Test + public void testQuotedFirstFieldWithLeadingSpace() throws Exception { + + // leading spaces should be preserved + final String input = " \"quoted with leading spaces\",two"; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 2); + assertEquals(" quoted with leading spaces", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // same input when surrounding spaces require quotes (leading spaces trimmed) + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 2); + assertEquals("quoted with leading spaces", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method with a leading space before the last quoted field. This is not technically valid + * CSV, but the tokenizer is lenient enough to allow it. The leading spaces will be trimmed off when surrounding + * spaces require quotes, otherwise they will be part of the field. + */ + @Test + public void testQuotedLastFieldWithLeadingSpace() throws Exception { + + // last field has a leading space before quote (should be preserved) + final String input = "one,two, \"quoted with leading spaces\""; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals("one", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals(" quoted with leading spaces", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // leading space should be trimmed off + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals("one", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals("quoted with leading spaces", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method with a trailing space after the first quoted field. This is not technically valid + * CSV, but the tokenizer is lenient enough to allow it. The trailing spaces will be trimmed off when surrounding + * spaces require quotes, otherwise they will be part of the field. + */ + @Test + public void testQuotedFirstFieldWithTrailingSpace() throws Exception { + + // first field has a leading space before quote (should be preserved) + final String input = "\"quoted with trailing spaces\" ,two"; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 2); + assertEquals("quoted with trailing spaces ", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // trailing spaces should be trimmed + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 2); + assertEquals("quoted with trailing spaces", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method with a trailing space after the last quoted field. This is not technically valid + * CSV, but the tokenizer is lenient enough to allow it. The trailing spaces will be trimmed off when surrounding + * spaces require quotes, otherwise they will be part of the field. + */ + @Test + public void testQuotedLastFieldWithTrailingSpace() throws Exception { + + // last field has a leading space before quote (should be preserved) + final String input = "one,two,\"quoted with trailing spaces\" "; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals("one", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals("quoted with trailing spaces ", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // trailing spaces should be trimmed off + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals("one", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals("quoted with trailing spaces", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method with a variety of quoted spaces. + */ + @Test + public void testQuotedSpaces() throws Exception { + + final String input = "\" one \",\" two \",\" three \""; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals(" one ", columns.get(0)); + assertEquals(" two ", columns.get(1)); + assertEquals(" three ", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // same input when surrounding spaces require quotes (results should be identical) + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals(" one ", columns.get(0)); + assertEquals(" two ", columns.get(1)); + assertEquals(" three ", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method with a variety of unquoted spaces. + */ + @Test + public void testSpaces() throws Exception { + + final String input = " one , two , three "; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals(" one ", columns.get(0)); + assertEquals(" two ", columns.get(1)); + assertEquals(" three ", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // same input when surrounding spaces require quotes + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals("one", columns.get(0)); + assertEquals("two", columns.get(1)); + assertEquals("three", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method with a variety of spaces and tabs. + */ + @Test + public void testSpacesAndTabs() throws Exception { + + // tabs should never be trimmed + final String input = "\t, \tone\t , \ttwo\t , \tthree\t "; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 4); + assertEquals("\t", columns.get(0)); + assertEquals(" \tone\t ", columns.get(1)); + assertEquals(" \ttwo\t ", columns.get(2)); + assertEquals(" \tthree\t ", columns.get(3)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // same input when surrounding spaces require quotes + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 4); + assertEquals("\t", columns.get(0)); + assertEquals("\tone\t", columns.get(1)); + assertEquals("\ttwo\t", columns.get(2)); + assertEquals("\tthree\t", columns.get(3)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + + /** + * Tests the readColumns() method with spaces between words. + */ + @Test + public void testSpacesBetweenWords() throws Exception { + + final String input = " one partridge , two turtle doves , three french hens "; + tokenizer = createTokenizer(input, NORMAL_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals(" one partridge ", columns.get(0)); + assertEquals(" two turtle doves ", columns.get(1)); + assertEquals(" three french hens ", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + + // same input when surrounding spaces require quotes + tokenizer = createTokenizer(input, SPACES_NEED_QUOTES_PREFERENCE); + tokenizer.readColumns(columns); + assertTrue(columns.size() == 3); + assertEquals("one partridge", columns.get(0)); + assertEquals("two turtle doves", columns.get(1)); + assertEquals("three french hens", columns.get(2)); + assertEquals(input, tokenizer.getUntokenizedRow()); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/mock/Customer.java b/super-csv/src/test/java/org/supercsv/mock/Customer.java index 2ec3f377..933f737a 100644 --- a/super-csv/src/test/java/org/supercsv/mock/Customer.java +++ b/super-csv/src/test/java/org/supercsv/mock/Customer.java @@ -1,37 +1,37 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock; - -/** - * Interface for a customer (for bean reading/writing tests). - * - * @author James Bassett - */ -public interface Customer { - - public String getCustomerNo(); - - public void setCustomerNo(String customerNo); - - public long getLoyaltyPoints(); - - public void setLoyaltyPoints(long loyaltyPoints); - - public String getMailingAddress(); - - public void setMailingAddress(String mailingAddress); - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock; + +/** + * Interface for a customer (for bean reading/writing tests). + * + * @author James Bassett + */ +public interface Customer { + + public String getCustomerNo(); + + public void setCustomerNo(String customerNo); + + public long getLoyaltyPoints(); + + public void setLoyaltyPoints(long loyaltyPoints); + + public String getMailingAddress(); + + public void setMailingAddress(String mailingAddress); + +} diff --git a/super-csv/src/test/java/org/supercsv/mock/CustomerBean.java b/super-csv/src/test/java/org/supercsv/mock/CustomerBean.java index 39a33883..5a5318d6 100644 --- a/super-csv/src/test/java/org/supercsv/mock/CustomerBean.java +++ b/super-csv/src/test/java/org/supercsv/mock/CustomerBean.java @@ -1,158 +1,158 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock; - -import java.util.Date; - -/** - * Superclass bean to use when testing bean reading/writing. - * - * @author James Bassett - */ -public class CustomerBean extends PersonBean implements Customer { - - private String customerNo; - - private long loyaltyPoints; - - private String mailingAddress; - - /** - * Default Constructor. - */ - public CustomerBean() { - } - - /** - * Constructs a CustomerBean. - * - * @param customerNo - * @param firstName - * @param lastName - * @param birthDate - * @param mailingAddress - * @param married - * @param numberOfKids - * @param favouriteQuote - * @param email - * @param loyaltyPoints - */ - public CustomerBean(final String customerNo, final String firstName, final String lastName, final Date birthDate, - final String mailingAddress, final Boolean married, final Integer numberOfKids, final String favouriteQuote, - final String email, final long loyaltyPoints) { - super(firstName, lastName, birthDate, married, numberOfKids, favouriteQuote, email); - this.customerNo = customerNo; - this.loyaltyPoints = loyaltyPoints; - this.mailingAddress = mailingAddress; - } - - /** - * @return the customerNo - */ - public String getCustomerNo() { - return customerNo; - } - - /** - * @param customerNo - * the customerNo to set - */ - public void setCustomerNo(String customerNo) { - this.customerNo = customerNo; - } - - /** - * @return the loyaltyPoints - */ - public long getLoyaltyPoints() { - return loyaltyPoints; - } - - /** - * @param loyaltyPoints - * the loyaltyPoints to set - */ - public void setLoyaltyPoints(long loyaltyPoints) { - this.loyaltyPoints = loyaltyPoints; - } - - /** - * @return the mailingAddress - */ - public String getMailingAddress() { - return mailingAddress; - } - - /** - * @param mailingAddress - * the mailingAddress to set - */ - public void setMailingAddress(String mailingAddress) { - this.mailingAddress = mailingAddress; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((customerNo == null) ? 0 : customerNo.hashCode()); - result = prime * result + (int) (loyaltyPoints ^ (loyaltyPoints >>> 32)); - result = prime * result + ((mailingAddress == null) ? 0 : mailingAddress.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if( this == obj ) { - return true; - } - if( !super.equals(obj) ) { - return false; - } - if( !(obj instanceof CustomerBean) ) { - return false; - } - CustomerBean other = (CustomerBean) obj; - if( customerNo == null ) { - if( other.customerNo != null ) { - return false; - } - } else if( !customerNo.equals(other.customerNo) ) { - return false; - } - if( loyaltyPoints != other.loyaltyPoints ) { - return false; - } - if( mailingAddress == null ) { - if( other.mailingAddress != null ) { - return false; - } - } else if( !mailingAddress.equals(other.mailingAddress) ) { - return false; - } - return true; - } - - @Override - public String toString() { - return String - .format( - "CustomerBean [customerNo=%s, firstName=%s, lastName=%s, birthDate=%s, mailingAddress=%s, married=%s, numberOfKids=%s, favouriteQuote=%s, email=%s, loyaltyPoints=%s]", - customerNo, getFirstName(), getLastName(), getBirthDate(), mailingAddress, getMarried(), - getNumberOfKids(), getFavouriteQuote(), getEmail(), loyaltyPoints); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock; + +import java.util.Date; + +/** + * Superclass bean to use when testing bean reading/writing. + * + * @author James Bassett + */ +public class CustomerBean extends PersonBean implements Customer { + + private String customerNo; + + private long loyaltyPoints; + + private String mailingAddress; + + /** + * Default Constructor. + */ + public CustomerBean() { + } + + /** + * Constructs a CustomerBean. + * + * @param customerNo + * @param firstName + * @param lastName + * @param birthDate + * @param mailingAddress + * @param married + * @param numberOfKids + * @param favouriteQuote + * @param email + * @param loyaltyPoints + */ + public CustomerBean(final String customerNo, final String firstName, final String lastName, final Date birthDate, + final String mailingAddress, final Boolean married, final Integer numberOfKids, final String favouriteQuote, + final String email, final long loyaltyPoints) { + super(firstName, lastName, birthDate, married, numberOfKids, favouriteQuote, email); + this.customerNo = customerNo; + this.loyaltyPoints = loyaltyPoints; + this.mailingAddress = mailingAddress; + } + + /** + * @return the customerNo + */ + public String getCustomerNo() { + return customerNo; + } + + /** + * @param customerNo + * the customerNo to set + */ + public void setCustomerNo(String customerNo) { + this.customerNo = customerNo; + } + + /** + * @return the loyaltyPoints + */ + public long getLoyaltyPoints() { + return loyaltyPoints; + } + + /** + * @param loyaltyPoints + * the loyaltyPoints to set + */ + public void setLoyaltyPoints(long loyaltyPoints) { + this.loyaltyPoints = loyaltyPoints; + } + + /** + * @return the mailingAddress + */ + public String getMailingAddress() { + return mailingAddress; + } + + /** + * @param mailingAddress + * the mailingAddress to set + */ + public void setMailingAddress(String mailingAddress) { + this.mailingAddress = mailingAddress; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((customerNo == null) ? 0 : customerNo.hashCode()); + result = prime * result + (int) (loyaltyPoints ^ (loyaltyPoints >>> 32)); + result = prime * result + ((mailingAddress == null) ? 0 : mailingAddress.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if( this == obj ) { + return true; + } + if( !super.equals(obj) ) { + return false; + } + if( !(obj instanceof CustomerBean) ) { + return false; + } + CustomerBean other = (CustomerBean) obj; + if( customerNo == null ) { + if( other.customerNo != null ) { + return false; + } + } else if( !customerNo.equals(other.customerNo) ) { + return false; + } + if( loyaltyPoints != other.loyaltyPoints ) { + return false; + } + if( mailingAddress == null ) { + if( other.mailingAddress != null ) { + return false; + } + } else if( !mailingAddress.equals(other.mailingAddress) ) { + return false; + } + return true; + } + + @Override + public String toString() { + return String + .format( + "CustomerBean [customerNo=%s, firstName=%s, lastName=%s, birthDate=%s, mailingAddress=%s, married=%s, numberOfKids=%s, favouriteQuote=%s, email=%s, loyaltyPoints=%s]", + customerNo, getFirstName(), getLastName(), getBirthDate(), mailingAddress, getMarried(), + getNumberOfKids(), getFavouriteQuote(), getEmail(), loyaltyPoints); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/mock/CustomerStringBean.java b/super-csv/src/test/java/org/supercsv/mock/CustomerStringBean.java index b1ca6334..a4838aec 100644 --- a/super-csv/src/test/java/org/supercsv/mock/CustomerStringBean.java +++ b/super-csv/src/test/java/org/supercsv/mock/CustomerStringBean.java @@ -1,323 +1,323 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock; - -import java.text.SimpleDateFormat; - -/** - * Bean with String values only - for testing reading/writing without processors. - * - * @author James Bassett - */ -public class CustomerStringBean { - - private String customerNo; - private String firstName; - private String lastName; - private String birthDate; - private String mailingAddress; - private String married; - private String numberOfKids; - private String favouriteQuote; - private String email; - private String loyaltyPoints; - - /** - * Default Constructor. - */ - public CustomerStringBean() { - } - - /** - * Constructs a CustomerStringBean from a CustomerBean. - * - * @param customerBean - */ - public CustomerStringBean(final CustomerBean customerBean) { - this.customerNo = customerBean.getCustomerNo(); - this.firstName = customerBean.getFirstName(); - this.lastName = customerBean.getLastName(); - this.birthDate = new SimpleDateFormat("dd/MM/yyyy").format(customerBean.getBirthDate()); - this.mailingAddress = customerBean.getMailingAddress(); - if( customerBean.getMarried() != null ) { - this.married = customerBean.getMarried() ? "Y" : "N"; - } else { - this.married = null; - } - if( customerBean.getNumberOfKids() != null ) { - this.numberOfKids = customerBean.getNumberOfKids().toString(); - } else { - this.numberOfKids = null; - } - this.favouriteQuote = customerBean.getFavouriteQuote(); - this.email = customerBean.getEmail(); - this.loyaltyPoints = String.valueOf(customerBean.getLoyaltyPoints()); - - } - - /** - * @return the customerNo - */ - public String getCustomerNo() { - return customerNo; - } - - /** - * @param customerNo - * the customerNo to set - */ - public void setCustomerNo(String customerNo) { - this.customerNo = customerNo; - } - - /** - * @return the firstName - */ - public String getFirstName() { - return firstName; - } - - /** - * @param firstName - * the firstName to set - */ - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } - - /** - * @param lastName - * the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - * @return the birthDate - */ - public String getBirthDate() { - return birthDate; - } - - /** - * @param birthDate - * the birthDate to set - */ - public void setBirthDate(String birthDate) { - this.birthDate = birthDate; - } - - /** - * @return the mailingAddress - */ - public String getMailingAddress() { - return mailingAddress; - } - - /** - * @param mailingAddress - * the mailingAddress to set - */ - public void setMailingAddress(String mailingAddress) { - this.mailingAddress = mailingAddress; - } - - /** - * @return the married - */ - public String getMarried() { - return married; - } - - /** - * @param married - * the married to set - */ - public void setMarried(String married) { - this.married = married; - } - - /** - * @return the numberOfKids - */ - public String getNumberOfKids() { - return numberOfKids; - } - - /** - * @param numberOfKids - * the numberOfKids to set - */ - public void setNumberOfKids(String numberOfKids) { - this.numberOfKids = numberOfKids; - } - - /** - * @return the favouriteQuote - */ - public String getFavouriteQuote() { - return favouriteQuote; - } - - /** - * @param favouriteQuote - * the favouriteQuote to set - */ - public void setFavouriteQuote(String favouriteQuote) { - this.favouriteQuote = favouriteQuote; - } - - /** - * @return the email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the loyaltyPoints - */ - public String getLoyaltyPoints() { - return loyaltyPoints; - } - - /** - * @param loyaltyPoints - * the loyaltyPoints to set - */ - public void setLoyaltyPoints(String loyaltyPoints) { - this.loyaltyPoints = loyaltyPoints; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((birthDate == null) ? 0 : birthDate.hashCode()); - result = prime * result + ((customerNo == null) ? 0 : customerNo.hashCode()); - result = prime * result + ((email == null) ? 0 : email.hashCode()); - result = prime * result + ((favouriteQuote == null) ? 0 : favouriteQuote.hashCode()); - result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); - result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); - result = prime * result + ((loyaltyPoints == null) ? 0 : loyaltyPoints.hashCode()); - result = prime * result + ((mailingAddress == null) ? 0 : mailingAddress.hashCode()); - result = prime * result + ((married == null) ? 0 : married.hashCode()); - result = prime * result + ((numberOfKids == null) ? 0 : numberOfKids.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if( this == obj ) { - return true; - } - if( obj == null ) { - return false; - } - if( !(obj instanceof CustomerStringBean) ) { - return false; - } - CustomerStringBean other = (CustomerStringBean) obj; - if( birthDate == null ) { - if( other.birthDate != null ) { - return false; - } - } else if( !birthDate.equals(other.birthDate) ) { - return false; - } - if( customerNo == null ) { - if( other.customerNo != null ) { - return false; - } - } else if( !customerNo.equals(other.customerNo) ) { - return false; - } - if( email == null ) { - if( other.email != null ) { - return false; - } - } else if( !email.equals(other.email) ) { - return false; - } - if( favouriteQuote == null ) { - if( other.favouriteQuote != null ) { - return false; - } - } else if( !favouriteQuote.equals(other.favouriteQuote) ) { - return false; - } - if( firstName == null ) { - if( other.firstName != null ) { - return false; - } - } else if( !firstName.equals(other.firstName) ) { - return false; - } - if( lastName == null ) { - if( other.lastName != null ) { - return false; - } - } else if( !lastName.equals(other.lastName) ) { - return false; - } - if( loyaltyPoints == null ) { - if( other.loyaltyPoints != null ) { - return false; - } - } else if( !loyaltyPoints.equals(other.loyaltyPoints) ) { - return false; - } - if( mailingAddress == null ) { - if( other.mailingAddress != null ) { - return false; - } - } else if( !mailingAddress.equals(other.mailingAddress) ) { - return false; - } - if( married == null ) { - if( other.married != null ) { - return false; - } - } else if( !married.equals(other.married) ) { - return false; - } - if( numberOfKids == null ) { - if( other.numberOfKids != null ) { - return false; - } - } else if( !numberOfKids.equals(other.numberOfKids) ) { - return false; - } - return true; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock; + +import java.text.SimpleDateFormat; + +/** + * Bean with String values only - for testing reading/writing without processors. + * + * @author James Bassett + */ +public class CustomerStringBean { + + private String customerNo; + private String firstName; + private String lastName; + private String birthDate; + private String mailingAddress; + private String married; + private String numberOfKids; + private String favouriteQuote; + private String email; + private String loyaltyPoints; + + /** + * Default Constructor. + */ + public CustomerStringBean() { + } + + /** + * Constructs a CustomerStringBean from a CustomerBean. + * + * @param customerBean + */ + public CustomerStringBean(final CustomerBean customerBean) { + this.customerNo = customerBean.getCustomerNo(); + this.firstName = customerBean.getFirstName(); + this.lastName = customerBean.getLastName(); + this.birthDate = new SimpleDateFormat("dd/MM/yyyy").format(customerBean.getBirthDate()); + this.mailingAddress = customerBean.getMailingAddress(); + if( customerBean.getMarried() != null ) { + this.married = customerBean.getMarried() ? "Y" : "N"; + } else { + this.married = null; + } + if( customerBean.getNumberOfKids() != null ) { + this.numberOfKids = customerBean.getNumberOfKids().toString(); + } else { + this.numberOfKids = null; + } + this.favouriteQuote = customerBean.getFavouriteQuote(); + this.email = customerBean.getEmail(); + this.loyaltyPoints = String.valueOf(customerBean.getLoyaltyPoints()); + + } + + /** + * @return the customerNo + */ + public String getCustomerNo() { + return customerNo; + } + + /** + * @param customerNo + * the customerNo to set + */ + public void setCustomerNo(String customerNo) { + this.customerNo = customerNo; + } + + /** + * @return the firstName + */ + public String getFirstName() { + return firstName; + } + + /** + * @param firstName + * the firstName to set + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * @return the lastName + */ + public String getLastName() { + return lastName; + } + + /** + * @param lastName + * the lastName to set + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * @return the birthDate + */ + public String getBirthDate() { + return birthDate; + } + + /** + * @param birthDate + * the birthDate to set + */ + public void setBirthDate(String birthDate) { + this.birthDate = birthDate; + } + + /** + * @return the mailingAddress + */ + public String getMailingAddress() { + return mailingAddress; + } + + /** + * @param mailingAddress + * the mailingAddress to set + */ + public void setMailingAddress(String mailingAddress) { + this.mailingAddress = mailingAddress; + } + + /** + * @return the married + */ + public String getMarried() { + return married; + } + + /** + * @param married + * the married to set + */ + public void setMarried(String married) { + this.married = married; + } + + /** + * @return the numberOfKids + */ + public String getNumberOfKids() { + return numberOfKids; + } + + /** + * @param numberOfKids + * the numberOfKids to set + */ + public void setNumberOfKids(String numberOfKids) { + this.numberOfKids = numberOfKids; + } + + /** + * @return the favouriteQuote + */ + public String getFavouriteQuote() { + return favouriteQuote; + } + + /** + * @param favouriteQuote + * the favouriteQuote to set + */ + public void setFavouriteQuote(String favouriteQuote) { + this.favouriteQuote = favouriteQuote; + } + + /** + * @return the email + */ + public String getEmail() { + return email; + } + + /** + * @param email + * the email to set + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * @return the loyaltyPoints + */ + public String getLoyaltyPoints() { + return loyaltyPoints; + } + + /** + * @param loyaltyPoints + * the loyaltyPoints to set + */ + public void setLoyaltyPoints(String loyaltyPoints) { + this.loyaltyPoints = loyaltyPoints; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((birthDate == null) ? 0 : birthDate.hashCode()); + result = prime * result + ((customerNo == null) ? 0 : customerNo.hashCode()); + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((favouriteQuote == null) ? 0 : favouriteQuote.hashCode()); + result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); + result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); + result = prime * result + ((loyaltyPoints == null) ? 0 : loyaltyPoints.hashCode()); + result = prime * result + ((mailingAddress == null) ? 0 : mailingAddress.hashCode()); + result = prime * result + ((married == null) ? 0 : married.hashCode()); + result = prime * result + ((numberOfKids == null) ? 0 : numberOfKids.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if( this == obj ) { + return true; + } + if( obj == null ) { + return false; + } + if( !(obj instanceof CustomerStringBean) ) { + return false; + } + CustomerStringBean other = (CustomerStringBean) obj; + if( birthDate == null ) { + if( other.birthDate != null ) { + return false; + } + } else if( !birthDate.equals(other.birthDate) ) { + return false; + } + if( customerNo == null ) { + if( other.customerNo != null ) { + return false; + } + } else if( !customerNo.equals(other.customerNo) ) { + return false; + } + if( email == null ) { + if( other.email != null ) { + return false; + } + } else if( !email.equals(other.email) ) { + return false; + } + if( favouriteQuote == null ) { + if( other.favouriteQuote != null ) { + return false; + } + } else if( !favouriteQuote.equals(other.favouriteQuote) ) { + return false; + } + if( firstName == null ) { + if( other.firstName != null ) { + return false; + } + } else if( !firstName.equals(other.firstName) ) { + return false; + } + if( lastName == null ) { + if( other.lastName != null ) { + return false; + } + } else if( !lastName.equals(other.lastName) ) { + return false; + } + if( loyaltyPoints == null ) { + if( other.loyaltyPoints != null ) { + return false; + } + } else if( !loyaltyPoints.equals(other.loyaltyPoints) ) { + return false; + } + if( mailingAddress == null ) { + if( other.mailingAddress != null ) { + return false; + } + } else if( !mailingAddress.equals(other.mailingAddress) ) { + return false; + } + if( married == null ) { + if( other.married != null ) { + return false; + } + } else if( !married.equals(other.married) ) { + return false; + } + if( numberOfKids == null ) { + if( other.numberOfKids != null ) { + return false; + } + } else if( !numberOfKids.equals(other.numberOfKids) ) { + return false; + } + return true; + } + +} diff --git a/super-csv/src/test/java/org/supercsv/mock/IdentityTransform.java b/super-csv/src/test/java/org/supercsv/mock/IdentityTransform.java index f7e9084f..2d7d79ea 100644 --- a/super-csv/src/test/java/org/supercsv/mock/IdentityTransform.java +++ b/super-csv/src/test/java/org/supercsv/mock/IdentityTransform.java @@ -1,59 +1,59 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock; - -import org.supercsv.cellprocessor.CellProcessorAdaptor; -import org.supercsv.cellprocessor.ift.BoolCellProcessor; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.cellprocessor.ift.DateCellProcessor; -import org.supercsv.cellprocessor.ift.DoubleCellProcessor; -import org.supercsv.cellprocessor.ift.LongCellProcessor; -import org.supercsv.cellprocessor.ift.StringCellProcessor; -import org.supercsv.util.CsvContext; - -/** - * CellProcessor to use for unit tests that test chaining (it simply returns whatever is passed into it). - * - * @author James Bassett - */ -public class IdentityTransform extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, - DoubleCellProcessor, LongCellProcessor, StringCellProcessor { - - /** - * Constructs a new IdentityTransform processor, which simply returns whatever is passed into it. - */ - public IdentityTransform() { - super(); - } - - /** - * Constructs a new IdentityTransform processor which just calls the next processor in the chain. - * - * @param next - * the next processor in the chain - */ - public IdentityTransform(CellProcessor next) { - super(next); - } - - /** - * {@inheritDoc} - */ - public Object execute(Object value, CsvContext context) { - return next.execute(value, context); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock; + +import org.supercsv.cellprocessor.CellProcessorAdaptor; +import org.supercsv.cellprocessor.ift.BoolCellProcessor; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.cellprocessor.ift.DateCellProcessor; +import org.supercsv.cellprocessor.ift.DoubleCellProcessor; +import org.supercsv.cellprocessor.ift.LongCellProcessor; +import org.supercsv.cellprocessor.ift.StringCellProcessor; +import org.supercsv.util.CsvContext; + +/** + * CellProcessor to use for unit tests that test chaining (it simply returns whatever is passed into it). + * + * @author James Bassett + */ +public class IdentityTransform extends CellProcessorAdaptor implements BoolCellProcessor, DateCellProcessor, + DoubleCellProcessor, LongCellProcessor, StringCellProcessor { + + /** + * Constructs a new IdentityTransform processor, which simply returns whatever is passed into it. + */ + public IdentityTransform() { + super(); + } + + /** + * Constructs a new IdentityTransform processor which just calls the next processor in the chain. + * + * @param next + * the next processor in the chain + */ + public IdentityTransform(CellProcessor next) { + super(next); + } + + /** + * {@inheritDoc} + */ + public Object execute(Object value, CsvContext context) { + return next.execute(value, context); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/mock/PersonBean.java b/super-csv/src/test/java/org/supercsv/mock/PersonBean.java index a51c10c2..28f8c642 100644 --- a/super-csv/src/test/java/org/supercsv/mock/PersonBean.java +++ b/super-csv/src/test/java/org/supercsv/mock/PersonBean.java @@ -1,261 +1,261 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock; - -import java.util.Date; - -/** - * Bean to use when testing bean reading/writing. - * - * @author Kasper B. Graversen - * @author James Bassett - */ -public class PersonBean { - - private String firstName; - - private String lastName; - - private Date birthDate; - - private Boolean married; - - private Integer numberOfKids; - - private String favouriteQuote; - - private String email; - - /** - * Default constructor. - */ - public PersonBean() { - } - - /** - * Constructs a PersonBean. - * - * @param firstName - * @param lastName - * @param birthDate - * @param married - * @param numberOfKids - * @param favouriteQuote - * @param email - */ - public PersonBean(final String firstName, final String lastName, final Date birthDate, final Boolean married, - final Integer numberOfKids, final String favouriteQuote, final String email) { - this.firstName = firstName; - this.lastName = lastName; - this.birthDate = birthDate; - this.married = married; - this.numberOfKids = numberOfKids; - this.favouriteQuote = favouriteQuote; - this.email = email; - } - - /** - * @return the firstName - */ - public String getFirstName() { - return firstName; - } - - /** - * @param firstName - * the firstName to set - */ - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } - - /** - * @param lastName - * the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - * @return the birthDate - */ - public Date getBirthDate() { - return birthDate; - } - - /** - * @param birthDate - * the birthDate to set - */ - public void setBirthDate(Date birthDate) { - this.birthDate = birthDate; - } - - /** - * @return the married - */ - public Boolean getMarried() { - return married; - } - - /** - * @param married - * the married to set - */ - public void setMarried(Boolean married) { - this.married = married; - } - - /** - * @return the numberOfKids - */ - public Integer getNumberOfKids() { - return numberOfKids; - } - - /** - * @param numberOfKids - * the numberOfKids to set - */ - public void setNumberOfKids(Integer numberOfKids) { - this.numberOfKids = numberOfKids; - } - - /** - * @return the email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the favouriteQuote - */ - public String getFavouriteQuote() { - return favouriteQuote; - } - - /** - * @param favouriteQuote - * the favouriteQuote to set - */ - public void setFavouriteQuote(String favouriteQuote) { - this.favouriteQuote = favouriteQuote; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((birthDate == null) ? 0 : birthDate.hashCode()); - result = prime * result + ((email == null) ? 0 : email.hashCode()); - result = prime * result + ((favouriteQuote == null) ? 0 : favouriteQuote.hashCode()); - result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); - result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); - result = prime * result + ((married == null) ? 0 : married.hashCode()); - result = prime * result + ((numberOfKids == null) ? 0 : numberOfKids.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if( this == obj ) { - return true; - } - if( obj == null ) { - return false; - } - if( !(obj instanceof PersonBean) ) { - return false; - } - PersonBean other = (PersonBean) obj; - if( birthDate == null ) { - if( other.birthDate != null ) { - return false; - } - } else if( !birthDate.equals(other.birthDate) ) { - return false; - } - if( email == null ) { - if( other.email != null ) { - return false; - } - } else if( !email.equals(other.email) ) { - return false; - } - if( favouriteQuote == null ) { - if( other.favouriteQuote != null ) { - return false; - } - } else if( !favouriteQuote.equals(other.favouriteQuote) ) { - return false; - } - if( firstName == null ) { - if( other.firstName != null ) { - return false; - } - } else if( !firstName.equals(other.firstName) ) { - return false; - } - if( lastName == null ) { - if( other.lastName != null ) { - return false; - } - } else if( !lastName.equals(other.lastName) ) { - return false; - } - if( married == null ) { - if( other.married != null ) { - return false; - } - } else if( !married.equals(other.married) ) { - return false; - } - if( numberOfKids == null ) { - if( other.numberOfKids != null ) { - return false; - } - } else if( !numberOfKids.equals(other.numberOfKids) ) { - return false; - } - return true; - } - - @Override - public String toString() { - return String - .format( - "PersonBean [firstName=%s, lastName=%s, birthDate=%s, married=%s, numberOfKids=%s, favouriteQuote=%s, email=%s]", - firstName, lastName, birthDate, married, numberOfKids, favouriteQuote, email); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock; + +import java.util.Date; + +/** + * Bean to use when testing bean reading/writing. + * + * @author Kasper B. Graversen + * @author James Bassett + */ +public class PersonBean { + + private String firstName; + + private String lastName; + + private Date birthDate; + + private Boolean married; + + private Integer numberOfKids; + + private String favouriteQuote; + + private String email; + + /** + * Default constructor. + */ + public PersonBean() { + } + + /** + * Constructs a PersonBean. + * + * @param firstName + * @param lastName + * @param birthDate + * @param married + * @param numberOfKids + * @param favouriteQuote + * @param email + */ + public PersonBean(final String firstName, final String lastName, final Date birthDate, final Boolean married, + final Integer numberOfKids, final String favouriteQuote, final String email) { + this.firstName = firstName; + this.lastName = lastName; + this.birthDate = birthDate; + this.married = married; + this.numberOfKids = numberOfKids; + this.favouriteQuote = favouriteQuote; + this.email = email; + } + + /** + * @return the firstName + */ + public String getFirstName() { + return firstName; + } + + /** + * @param firstName + * the firstName to set + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * @return the lastName + */ + public String getLastName() { + return lastName; + } + + /** + * @param lastName + * the lastName to set + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * @return the birthDate + */ + public Date getBirthDate() { + return birthDate; + } + + /** + * @param birthDate + * the birthDate to set + */ + public void setBirthDate(Date birthDate) { + this.birthDate = birthDate; + } + + /** + * @return the married + */ + public Boolean getMarried() { + return married; + } + + /** + * @param married + * the married to set + */ + public void setMarried(Boolean married) { + this.married = married; + } + + /** + * @return the numberOfKids + */ + public Integer getNumberOfKids() { + return numberOfKids; + } + + /** + * @param numberOfKids + * the numberOfKids to set + */ + public void setNumberOfKids(Integer numberOfKids) { + this.numberOfKids = numberOfKids; + } + + /** + * @return the email + */ + public String getEmail() { + return email; + } + + /** + * @param email + * the email to set + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * @return the favouriteQuote + */ + public String getFavouriteQuote() { + return favouriteQuote; + } + + /** + * @param favouriteQuote + * the favouriteQuote to set + */ + public void setFavouriteQuote(String favouriteQuote) { + this.favouriteQuote = favouriteQuote; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((birthDate == null) ? 0 : birthDate.hashCode()); + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((favouriteQuote == null) ? 0 : favouriteQuote.hashCode()); + result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); + result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); + result = prime * result + ((married == null) ? 0 : married.hashCode()); + result = prime * result + ((numberOfKids == null) ? 0 : numberOfKids.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if( this == obj ) { + return true; + } + if( obj == null ) { + return false; + } + if( !(obj instanceof PersonBean) ) { + return false; + } + PersonBean other = (PersonBean) obj; + if( birthDate == null ) { + if( other.birthDate != null ) { + return false; + } + } else if( !birthDate.equals(other.birthDate) ) { + return false; + } + if( email == null ) { + if( other.email != null ) { + return false; + } + } else if( !email.equals(other.email) ) { + return false; + } + if( favouriteQuote == null ) { + if( other.favouriteQuote != null ) { + return false; + } + } else if( !favouriteQuote.equals(other.favouriteQuote) ) { + return false; + } + if( firstName == null ) { + if( other.firstName != null ) { + return false; + } + } else if( !firstName.equals(other.firstName) ) { + return false; + } + if( lastName == null ) { + if( other.lastName != null ) { + return false; + } + } else if( !lastName.equals(other.lastName) ) { + return false; + } + if( married == null ) { + if( other.married != null ) { + return false; + } + } else if( !married.equals(other.married) ) { + return false; + } + if( numberOfKids == null ) { + if( other.numberOfKids != null ) { + return false; + } + } else if( !numberOfKids.equals(other.numberOfKids) ) { + return false; + } + return true; + } + + @Override + public String toString() { + return String + .format( + "PersonBean [firstName=%s, lastName=%s, birthDate=%s, married=%s, numberOfKids=%s, favouriteQuote=%s, email=%s]", + firstName, lastName, birthDate, married, numberOfKids, favouriteQuote, email); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/mock/ReflectionBean.java b/super-csv/src/test/java/org/supercsv/mock/ReflectionBean.java index 5fb96fc0..01d95bae 100644 --- a/super-csv/src/test/java/org/supercsv/mock/ReflectionBean.java +++ b/super-csv/src/test/java/org/supercsv/mock/ReflectionBean.java @@ -1,196 +1,196 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.mock; - -/** - * A bean to use when testing reflection. - * - * @author James Bassett - */ -public class ReflectionBean { - - private boolean sailForTreasure; - private String name; - private Number favouriteNumber; - private Number overloaded; - private int primitiveInt; - private short primitiveShort; - private long primitiveLong; - private double primitiveDouble; - private float primitiveFloat; - private char primitiveChar; - private byte primitiveByte; - private Integer integerWrapper; - private Short shortWrapper; - private Long longWrapper; - private Double doubleWrapper; - private Float floatWrapper; - private Character charWrapper; - private Byte byteWrapper; - - public boolean getSailForTreasure() { - return sailForTreasure; - } - - public void setSailForTreasure(boolean sailForTreasure) { - this.sailForTreasure = sailForTreasure; - } - - public void setSailForTreasure(){ - throw new RuntimeException("this method isn't a setter and should never be invoked"); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Number getFavouriteNumber() { - return favouriteNumber; - } - - public void setFavouriteNumber(Number favouriteNumber) { - this.favouriteNumber = favouriteNumber; - } - - public Number getOverloaded() { - return overloaded; - } - - public void setOverloaded(Integer overloaded) { - throw new RuntimeException("this overloaded setter shouldn't be invoked!"); - } - - public void setOverloaded(Number overloaded) { - this.overloaded = overloaded; - } - - public int getPrimitiveInt() { - return primitiveInt; - } - - public void setPrimitiveInt(int primitiveInt) { - this.primitiveInt = primitiveInt; - } - - public short getPrimitiveShort() { - return primitiveShort; - } - - public void setPrimitiveShort(short primitiveShort) { - this.primitiveShort = primitiveShort; - } - - public long getPrimitiveLong() { - return primitiveLong; - } - - public void setPrimitiveLong(long primitiveLong) { - this.primitiveLong = primitiveLong; - } - - public double getPrimitiveDouble() { - return primitiveDouble; - } - - public void setPrimitiveDouble(double primitiveDouble) { - this.primitiveDouble = primitiveDouble; - } - - public float getPrimitiveFloat() { - return primitiveFloat; - } - - public void setPrimitiveFloat(float primitiveFloat) { - this.primitiveFloat = primitiveFloat; - } - - public char getPrimitiveChar() { - return primitiveChar; - } - - public void setPrimitiveChar(char primitiveChar) { - this.primitiveChar = primitiveChar; - } - - public byte getPrimitiveByte() { - return primitiveByte; - } - - public void setPrimitiveByte(byte primitiveByte) { - this.primitiveByte = primitiveByte; - } - - public Integer getIntegerWrapper() { - return integerWrapper; - } - - public void setIntegerWrapper(Integer integerWrapper) { - this.integerWrapper = integerWrapper; - } - - public Short getShortWrapper() { - return shortWrapper; - } - - public void setShortWrapper(Short shortWrapper) { - this.shortWrapper = shortWrapper; - } - - public Long getLongWrapper() { - return longWrapper; - } - - public void setLongWrapper(Long longWrapper) { - this.longWrapper = longWrapper; - } - - public Double getDoubleWrapper() { - return doubleWrapper; - } - - public void setDoubleWrapper(Double doubleWrapper) { - this.doubleWrapper = doubleWrapper; - } - - public Float getFloatWrapper() { - return floatWrapper; - } - - public void setFloatWrapper(Float floatWrapper) { - this.floatWrapper = floatWrapper; - } - - public Character getCharWrapper() { - return charWrapper; - } - - public void setCharWrapper(Character charWrapper) { - this.charWrapper = charWrapper; - } - - public Byte getByteWrapper() { - return byteWrapper; - } - - public void setByteWrapper(Byte byteWrapper) { - this.byteWrapper = byteWrapper; - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.mock; + +/** + * A bean to use when testing reflection. + * + * @author James Bassett + */ +public class ReflectionBean { + + private boolean sailForTreasure; + private String name; + private Number favouriteNumber; + private Number overloaded; + private int primitiveInt; + private short primitiveShort; + private long primitiveLong; + private double primitiveDouble; + private float primitiveFloat; + private char primitiveChar; + private byte primitiveByte; + private Integer integerWrapper; + private Short shortWrapper; + private Long longWrapper; + private Double doubleWrapper; + private Float floatWrapper; + private Character charWrapper; + private Byte byteWrapper; + + public boolean getSailForTreasure() { + return sailForTreasure; + } + + public void setSailForTreasure(boolean sailForTreasure) { + this.sailForTreasure = sailForTreasure; + } + + public void setSailForTreasure(){ + throw new RuntimeException("this method isn't a setter and should never be invoked"); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Number getFavouriteNumber() { + return favouriteNumber; + } + + public void setFavouriteNumber(Number favouriteNumber) { + this.favouriteNumber = favouriteNumber; + } + + public Number getOverloaded() { + return overloaded; + } + + public void setOverloaded(Integer overloaded) { + throw new RuntimeException("this overloaded setter shouldn't be invoked!"); + } + + public void setOverloaded(Number overloaded) { + this.overloaded = overloaded; + } + + public int getPrimitiveInt() { + return primitiveInt; + } + + public void setPrimitiveInt(int primitiveInt) { + this.primitiveInt = primitiveInt; + } + + public short getPrimitiveShort() { + return primitiveShort; + } + + public void setPrimitiveShort(short primitiveShort) { + this.primitiveShort = primitiveShort; + } + + public long getPrimitiveLong() { + return primitiveLong; + } + + public void setPrimitiveLong(long primitiveLong) { + this.primitiveLong = primitiveLong; + } + + public double getPrimitiveDouble() { + return primitiveDouble; + } + + public void setPrimitiveDouble(double primitiveDouble) { + this.primitiveDouble = primitiveDouble; + } + + public float getPrimitiveFloat() { + return primitiveFloat; + } + + public void setPrimitiveFloat(float primitiveFloat) { + this.primitiveFloat = primitiveFloat; + } + + public char getPrimitiveChar() { + return primitiveChar; + } + + public void setPrimitiveChar(char primitiveChar) { + this.primitiveChar = primitiveChar; + } + + public byte getPrimitiveByte() { + return primitiveByte; + } + + public void setPrimitiveByte(byte primitiveByte) { + this.primitiveByte = primitiveByte; + } + + public Integer getIntegerWrapper() { + return integerWrapper; + } + + public void setIntegerWrapper(Integer integerWrapper) { + this.integerWrapper = integerWrapper; + } + + public Short getShortWrapper() { + return shortWrapper; + } + + public void setShortWrapper(Short shortWrapper) { + this.shortWrapper = shortWrapper; + } + + public Long getLongWrapper() { + return longWrapper; + } + + public void setLongWrapper(Long longWrapper) { + this.longWrapper = longWrapper; + } + + public Double getDoubleWrapper() { + return doubleWrapper; + } + + public void setDoubleWrapper(Double doubleWrapper) { + this.doubleWrapper = doubleWrapper; + } + + public Float getFloatWrapper() { + return floatWrapper; + } + + public void setFloatWrapper(Float floatWrapper) { + this.floatWrapper = floatWrapper; + } + + public Character getCharWrapper() { + return charWrapper; + } + + public void setCharWrapper(Character charWrapper) { + this.charWrapper = charWrapper; + } + + public Byte getByteWrapper() { + return byteWrapper; + } + + public void setByteWrapper(Byte byteWrapper) { + this.byteWrapper = byteWrapper; + } + +} diff --git a/super-csv/src/test/java/org/supercsv/prefs/CsvPreferenceTest.java b/super-csv/src/test/java/org/supercsv/prefs/CsvPreferenceTest.java index ab9ea99d..025951b9 100644 --- a/super-csv/src/test/java/org/supercsv/prefs/CsvPreferenceTest.java +++ b/super-csv/src/test/java/org/supercsv/prefs/CsvPreferenceTest.java @@ -1,120 +1,120 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.prefs; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.supercsv.prefs.CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE; -import static org.supercsv.prefs.CsvPreference.EXCEL_PREFERENCE; -import static org.supercsv.prefs.CsvPreference.STANDARD_PREFERENCE; -import static org.supercsv.prefs.CsvPreference.TAB_PREFERENCE; - -import org.junit.Test; - -/** - * Tests the CsvPreference class. - * - * @author James Bassett - */ -public class CsvPreferenceTest { - - /** - * Tests the constant values. - */ - @Test - public void testConstants() { - assertEquals('"', STANDARD_PREFERENCE.getQuoteChar()); - assertEquals(',', STANDARD_PREFERENCE.getDelimiterChar()); - assertEquals("\r\n", STANDARD_PREFERENCE.getEndOfLineSymbols()); - - assertEquals('"', EXCEL_PREFERENCE.getQuoteChar()); - assertEquals(',', EXCEL_PREFERENCE.getDelimiterChar()); - assertEquals("\n", EXCEL_PREFERENCE.getEndOfLineSymbols()); - - assertEquals('"', EXCEL_NORTH_EUROPE_PREFERENCE.getQuoteChar()); - assertEquals(';', EXCEL_NORTH_EUROPE_PREFERENCE.getDelimiterChar()); - assertEquals("\n", EXCEL_NORTH_EUROPE_PREFERENCE.getEndOfLineSymbols()); - - assertEquals('"', TAB_PREFERENCE.getQuoteChar()); - assertEquals('\t', TAB_PREFERENCE.getDelimiterChar()); - assertEquals("\n", TAB_PREFERENCE.getEndOfLineSymbols()); - } - - /** - * Tests a custom CsvPreference with default optional values. - */ - @Test - public void testCustomPreferenceWithDefaults() { - final CsvPreference custom = new CsvPreference.Builder('"', ',', "\n").build(); - assertEquals('"', custom.getQuoteChar()); - assertEquals(',', custom.getDelimiterChar()); - assertEquals("\n", custom.getEndOfLineSymbols()); - assertFalse(custom.isSurroundingSpacesNeedQuotes()); - } - - /** - * Tests a custom CsvPreference with supplied optional values. - */ - @Test - public void testCustomPreference() { - final CsvPreference custom = new CsvPreference.Builder('"', ',', "\n").surroundingSpacesNeedQuotes(true).build(); - assertEquals('"', custom.getQuoteChar()); - assertEquals(',', custom.getDelimiterChar()); - assertEquals("\n", custom.getEndOfLineSymbols()); - assertTrue(custom.isSurroundingSpacesNeedQuotes()); - } - - /** - * Tests a custom CsvPreference based on an existing constant with default optional values. - */ - @Test - public void testCustomPreferenceBasedOnExistingWithDefaults() { - final CsvPreference custom = new CsvPreference.Builder(EXCEL_PREFERENCE).build(); - assertEquals(EXCEL_PREFERENCE.getQuoteChar(), custom.getQuoteChar()); - assertEquals(EXCEL_PREFERENCE.getDelimiterChar(), custom.getDelimiterChar()); - assertEquals(EXCEL_PREFERENCE.getEndOfLineSymbols(), custom.getEndOfLineSymbols()); - assertEquals(EXCEL_PREFERENCE.isSurroundingSpacesNeedQuotes(), custom.isSurroundingSpacesNeedQuotes()); - } - - /** - * Tests a custom CsvPreference based on an existing constant with supplied optional values. - */ - @Test - public void testCustomPreferenceBasedOnExisting() { - final CsvPreference custom = new CsvPreference.Builder(EXCEL_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); - assertEquals(EXCEL_PREFERENCE.getQuoteChar(), custom.getQuoteChar()); - assertEquals(EXCEL_PREFERENCE.getDelimiterChar(), custom.getDelimiterChar()); - assertEquals(EXCEL_PREFERENCE.getEndOfLineSymbols(), custom.getEndOfLineSymbols()); - assertTrue(custom.isSurroundingSpacesNeedQuotes()); - } - - /** - * Tests a custom CsvPreference with identical quote and delimiter chars (should throw an exception). - */ - @Test(expected = IllegalArgumentException.class) - public void testCustomPreferenceWithInvalidQuoteAndDelimeterChars() { - new CsvPreference.Builder('|', '|', "\n").build(); - } - - /** - * Tests construction with null end of line symbols (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructorWithNullEolSymbols() { - new CsvPreference.Builder('"', ',', null).build(); - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.prefs; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.supercsv.prefs.CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE; +import static org.supercsv.prefs.CsvPreference.EXCEL_PREFERENCE; +import static org.supercsv.prefs.CsvPreference.STANDARD_PREFERENCE; +import static org.supercsv.prefs.CsvPreference.TAB_PREFERENCE; + +import org.junit.Test; + +/** + * Tests the CsvPreference class. + * + * @author James Bassett + */ +public class CsvPreferenceTest { + + /** + * Tests the constant values. + */ + @Test + public void testConstants() { + assertEquals('"', STANDARD_PREFERENCE.getQuoteChar()); + assertEquals(',', STANDARD_PREFERENCE.getDelimiterChar()); + assertEquals("\r\n", STANDARD_PREFERENCE.getEndOfLineSymbols()); + + assertEquals('"', EXCEL_PREFERENCE.getQuoteChar()); + assertEquals(',', EXCEL_PREFERENCE.getDelimiterChar()); + assertEquals("\n", EXCEL_PREFERENCE.getEndOfLineSymbols()); + + assertEquals('"', EXCEL_NORTH_EUROPE_PREFERENCE.getQuoteChar()); + assertEquals(';', EXCEL_NORTH_EUROPE_PREFERENCE.getDelimiterChar()); + assertEquals("\n", EXCEL_NORTH_EUROPE_PREFERENCE.getEndOfLineSymbols()); + + assertEquals('"', TAB_PREFERENCE.getQuoteChar()); + assertEquals('\t', TAB_PREFERENCE.getDelimiterChar()); + assertEquals("\n", TAB_PREFERENCE.getEndOfLineSymbols()); + } + + /** + * Tests a custom CsvPreference with default optional values. + */ + @Test + public void testCustomPreferenceWithDefaults() { + final CsvPreference custom = new CsvPreference.Builder('"', ',', "\n").build(); + assertEquals('"', custom.getQuoteChar()); + assertEquals(',', custom.getDelimiterChar()); + assertEquals("\n", custom.getEndOfLineSymbols()); + assertFalse(custom.isSurroundingSpacesNeedQuotes()); + } + + /** + * Tests a custom CsvPreference with supplied optional values. + */ + @Test + public void testCustomPreference() { + final CsvPreference custom = new CsvPreference.Builder('"', ',', "\n").surroundingSpacesNeedQuotes(true).build(); + assertEquals('"', custom.getQuoteChar()); + assertEquals(',', custom.getDelimiterChar()); + assertEquals("\n", custom.getEndOfLineSymbols()); + assertTrue(custom.isSurroundingSpacesNeedQuotes()); + } + + /** + * Tests a custom CsvPreference based on an existing constant with default optional values. + */ + @Test + public void testCustomPreferenceBasedOnExistingWithDefaults() { + final CsvPreference custom = new CsvPreference.Builder(EXCEL_PREFERENCE).build(); + assertEquals(EXCEL_PREFERENCE.getQuoteChar(), custom.getQuoteChar()); + assertEquals(EXCEL_PREFERENCE.getDelimiterChar(), custom.getDelimiterChar()); + assertEquals(EXCEL_PREFERENCE.getEndOfLineSymbols(), custom.getEndOfLineSymbols()); + assertEquals(EXCEL_PREFERENCE.isSurroundingSpacesNeedQuotes(), custom.isSurroundingSpacesNeedQuotes()); + } + + /** + * Tests a custom CsvPreference based on an existing constant with supplied optional values. + */ + @Test + public void testCustomPreferenceBasedOnExisting() { + final CsvPreference custom = new CsvPreference.Builder(EXCEL_PREFERENCE).surroundingSpacesNeedQuotes(true).build(); + assertEquals(EXCEL_PREFERENCE.getQuoteChar(), custom.getQuoteChar()); + assertEquals(EXCEL_PREFERENCE.getDelimiterChar(), custom.getDelimiterChar()); + assertEquals(EXCEL_PREFERENCE.getEndOfLineSymbols(), custom.getEndOfLineSymbols()); + assertTrue(custom.isSurroundingSpacesNeedQuotes()); + } + + /** + * Tests a custom CsvPreference with identical quote and delimiter chars (should throw an exception). + */ + @Test(expected = IllegalArgumentException.class) + public void testCustomPreferenceWithInvalidQuoteAndDelimeterChars() { + new CsvPreference.Builder('|', '|', "\n").build(); + } + + /** + * Tests construction with null end of line symbols (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructorWithNullEolSymbols() { + new CsvPreference.Builder('"', ',', null).build(); + } +} diff --git a/super-csv/src/test/java/org/supercsv/util/BeanInterfaceProxyTest.java b/super-csv/src/test/java/org/supercsv/util/BeanInterfaceProxyTest.java index 58108f7a..96e3b172 100644 --- a/super-csv/src/test/java/org/supercsv/util/BeanInterfaceProxyTest.java +++ b/super-csv/src/test/java/org/supercsv/util/BeanInterfaceProxyTest.java @@ -1,155 +1,155 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.Before; -import org.junit.Test; - -/** - * Tests the BeanInterfaceProxy class. - * - * @author James Bassett - */ -public class BeanInterfaceProxyTest { - - private TestInterface testInterface; - - /** - * Creates the proxy for the test. - */ - @Before - public void setUp() { - testInterface = BeanInterfaceProxy.createProxy(TestInterface.class); - } - - /** - * Tests the proxy. - */ - @Test - public void testProxy() { - // no state saved yet - assertNull(testInterface.getValue()); - - // modify state - String value = "value"; - testInterface.setValue(value); - - // check state was saved - assertEquals(value, testInterface.getValue()); - - // modify state (to null) - testInterface.setValue(null); - - // check state was saved - assertNull(testInterface.getValue()); - } - - /** - * Tests the proxy with chained setters (the proxy allows for setters which return the modified object). - */ - @Test - public void testChainedSetters() { - // no state saved yet - assertNull(testInterface.getValue()); - - // modify state - String value = "value"; - String value2 = "value2"; - testInterface.setValue(value).setValue2(value2); - - // check state was saved - assertEquals(value, testInterface.getValue()); - assertEquals(value2, testInterface.getValue2()); - } - - /** - * Tests createProxy() with null. - */ - @Test(expected = NullPointerException.class) - public void testCreateProxyWithNull() { - BeanInterfaceProxy.createProxy(null); - } - - /** - * Tests invocation of a method that isn't a standard getter/setter. - */ - @Test(expected = IllegalArgumentException.class) - public void testNotGetterOrSetter() { - testInterface.isValueSet(); - } - - /** - * Tests invocation of a getter with a parameter (not a real getter). - */ - @Test(expected = IllegalArgumentException.class) - public void testGetterWithParam() { - testInterface.getWithParam("param"); - } - - /** - * Tests invocation of a method beginning with 'set' that takes many parameters (not a real setter). - */ - @Test(expected = IllegalArgumentException.class) - public void testMultiParamSetter() { - testInterface.setManyValues("value1", "value2"); - } - - /** - * Tests invocation of a setter without any parameters (not a real setter). - */ - @Test(expected = IllegalArgumentException.class) - public void testSetterWithNoParams() { - testInterface.setNothing(); - } - - /** - * Tests invocation of the getClass method, inherited from Object (doesn't call the - * InvocationHandler, but returns the proxy class!). - */ - @Test - public void testGetClass() { - assertNotNull(testInterface.getClass()); - - } - - /** - * An interface to use for testing. - */ - private interface TestInterface { - - public TestInterface setValue(String value); // proxy allows setters that returned the modified object - - public void setValue2(String value); - - public String getValue(); - - public String getValue2(); - - public String getWithParam(String value1); // getters with params not allowed - - public void setManyValues(String value1, String value2); // multi param setters not allowed - - public void setNothing(); // setters should have 1 param - - public boolean isValueSet(); // methods not starting with get/set are not allowed (yes, even boolean getters!) - - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; + +/** + * Tests the BeanInterfaceProxy class. + * + * @author James Bassett + */ +public class BeanInterfaceProxyTest { + + private TestInterface testInterface; + + /** + * Creates the proxy for the test. + */ + @Before + public void setUp() { + testInterface = BeanInterfaceProxy.createProxy(TestInterface.class); + } + + /** + * Tests the proxy. + */ + @Test + public void testProxy() { + // no state saved yet + assertNull(testInterface.getValue()); + + // modify state + String value = "value"; + testInterface.setValue(value); + + // check state was saved + assertEquals(value, testInterface.getValue()); + + // modify state (to null) + testInterface.setValue(null); + + // check state was saved + assertNull(testInterface.getValue()); + } + + /** + * Tests the proxy with chained setters (the proxy allows for setters which return the modified object). + */ + @Test + public void testChainedSetters() { + // no state saved yet + assertNull(testInterface.getValue()); + + // modify state + String value = "value"; + String value2 = "value2"; + testInterface.setValue(value).setValue2(value2); + + // check state was saved + assertEquals(value, testInterface.getValue()); + assertEquals(value2, testInterface.getValue2()); + } + + /** + * Tests createProxy() with null. + */ + @Test(expected = NullPointerException.class) + public void testCreateProxyWithNull() { + BeanInterfaceProxy.createProxy(null); + } + + /** + * Tests invocation of a method that isn't a standard getter/setter. + */ + @Test(expected = IllegalArgumentException.class) + public void testNotGetterOrSetter() { + testInterface.isValueSet(); + } + + /** + * Tests invocation of a getter with a parameter (not a real getter). + */ + @Test(expected = IllegalArgumentException.class) + public void testGetterWithParam() { + testInterface.getWithParam("param"); + } + + /** + * Tests invocation of a method beginning with 'set' that takes many parameters (not a real setter). + */ + @Test(expected = IllegalArgumentException.class) + public void testMultiParamSetter() { + testInterface.setManyValues("value1", "value2"); + } + + /** + * Tests invocation of a setter without any parameters (not a real setter). + */ + @Test(expected = IllegalArgumentException.class) + public void testSetterWithNoParams() { + testInterface.setNothing(); + } + + /** + * Tests invocation of the getClass method, inherited from Object (doesn't call the + * InvocationHandler, but returns the proxy class!). + */ + @Test + public void testGetClass() { + assertNotNull(testInterface.getClass()); + + } + + /** + * An interface to use for testing. + */ + private interface TestInterface { + + public TestInterface setValue(String value); // proxy allows setters that returned the modified object + + public void setValue2(String value); + + public String getValue(); + + public String getValue2(); + + public String getWithParam(String value1); // getters with params not allowed + + public void setManyValues(String value1, String value2); // multi param setters not allowed + + public void setNothing(); // setters should have 1 param + + public boolean isValueSet(); // methods not starting with get/set are not allowed (yes, even boolean getters!) + + } + +} diff --git a/super-csv/src/test/java/org/supercsv/util/CsvContextTest.java b/super-csv/src/test/java/org/supercsv/util/CsvContextTest.java index dee2781b..ffe467c9 100644 --- a/super-csv/src/test/java/org/supercsv/util/CsvContextTest.java +++ b/super-csv/src/test/java/org/supercsv/util/CsvContextTest.java @@ -1,132 +1,132 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - -import org.junit.Test; - -/** - * Tests the CsvContext class. - * - * @author James Bassett - */ -public class CsvContextTest { - - /** - * Tests the getters/setters. - */ - @Test - public void testGettersAndSetters() { - final CsvContext context = new CsvContext(0, 0, 0); - context.setLineNumber(1); - context.setRowNumber(2); - context.setColumnNumber(3); - final Object[] rowSource = new Object[] { "one", "two", "three" }; - context.setRowSource(Arrays.asList(rowSource)); - assertEquals(1, context.getLineNumber()); - assertEquals(2, context.getRowNumber()); - assertEquals(3, context.getColumnNumber()); - assertTrue(Arrays.equals(rowSource, context.getRowSource().toArray())); - - } - - /** - * Tests the hashCode() method. - */ - @Test - public void testHashCode() { - // two identical contexts with no line source - final CsvContext context1 = new CsvContext(1, 2, 3); - final CsvContext context2 = new CsvContext(1, 2, 3); - assertEquals(context1.hashCode(), context2.hashCode()); - - // two identical contexts with a line source - final CsvContext contextWithSource1 = new CsvContext(1, 2, 3); - contextWithSource1.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); - final CsvContext contextWithSource2 = new CsvContext(1, 2, 3); - contextWithSource2.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); - assertEquals(contextWithSource1.hashCode(), contextWithSource2.hashCode()); - } - - /** - * Tests the toString() method. - */ - @Test - public void testToString() { - - // no line source - final CsvContext context1 = new CsvContext(1, 2, 3); - assertEquals("{lineNo=1, rowNo=2, columnNo=3, rowSource=null}", context1.toString()); - - // with line source - final CsvContext context2 = new CsvContext(1, 2, 3); - context2.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); - assertEquals("{lineNo=1, rowNo=2, columnNo=3, rowSource=[one, two, three]}", context2.toString()); - - } - - /** - * Tests the equals() method. - */ - @Test - public void testEquals() { - - final CsvContext context = new CsvContext(1, 2, 3); - - final CsvContext contextWithSource = new CsvContext(1, 2, 3); - contextWithSource.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); - - // same object - assertTrue(context.equals(context)); - - // null - assertFalse(context.equals(null)); - - // different class - assertFalse(context.equals("A String, not a CsvContext!")); - - // different column - assertFalse(context.equals(new CsvContext(1, 2, 4))); - - // different row - assertFalse(context.equals(new CsvContext(1, 4, 3))); - - // different line no - assertFalse(context.equals(new CsvContext(4, 2, 3))); - - // only 1 context with line source - assertFalse(context.equals(contextWithSource)); - - // same column/line no, but different line sources - final CsvContext contextWithDifferentSource = new CsvContext(1, 2, 3); - contextWithDifferentSource.setRowSource(Arrays.asList(new Object[] { "four", "five", "six" })); - assertFalse(contextWithSource.equals(contextWithDifferentSource)); - - // same with no line source - assertTrue(context.equals(new CsvContext(1, 2, 3))); - - // same with line source - final CsvContext same = new CsvContext(1, 2, 3); - same.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); - assertTrue(contextWithSource.equals(same)); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; + +import org.junit.Test; + +/** + * Tests the CsvContext class. + * + * @author James Bassett + */ +public class CsvContextTest { + + /** + * Tests the getters/setters. + */ + @Test + public void testGettersAndSetters() { + final CsvContext context = new CsvContext(0, 0, 0); + context.setLineNumber(1); + context.setRowNumber(2); + context.setColumnNumber(3); + final Object[] rowSource = new Object[] { "one", "two", "three" }; + context.setRowSource(Arrays.asList(rowSource)); + assertEquals(1, context.getLineNumber()); + assertEquals(2, context.getRowNumber()); + assertEquals(3, context.getColumnNumber()); + assertTrue(Arrays.equals(rowSource, context.getRowSource().toArray())); + + } + + /** + * Tests the hashCode() method. + */ + @Test + public void testHashCode() { + // two identical contexts with no line source + final CsvContext context1 = new CsvContext(1, 2, 3); + final CsvContext context2 = new CsvContext(1, 2, 3); + assertEquals(context1.hashCode(), context2.hashCode()); + + // two identical contexts with a line source + final CsvContext contextWithSource1 = new CsvContext(1, 2, 3); + contextWithSource1.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); + final CsvContext contextWithSource2 = new CsvContext(1, 2, 3); + contextWithSource2.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); + assertEquals(contextWithSource1.hashCode(), contextWithSource2.hashCode()); + } + + /** + * Tests the toString() method. + */ + @Test + public void testToString() { + + // no line source + final CsvContext context1 = new CsvContext(1, 2, 3); + assertEquals("{lineNo=1, rowNo=2, columnNo=3, rowSource=null}", context1.toString()); + + // with line source + final CsvContext context2 = new CsvContext(1, 2, 3); + context2.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); + assertEquals("{lineNo=1, rowNo=2, columnNo=3, rowSource=[one, two, three]}", context2.toString()); + + } + + /** + * Tests the equals() method. + */ + @Test + public void testEquals() { + + final CsvContext context = new CsvContext(1, 2, 3); + + final CsvContext contextWithSource = new CsvContext(1, 2, 3); + contextWithSource.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); + + // same object + assertTrue(context.equals(context)); + + // null + assertFalse(context.equals(null)); + + // different class + assertFalse(context.equals("A String, not a CsvContext!")); + + // different column + assertFalse(context.equals(new CsvContext(1, 2, 4))); + + // different row + assertFalse(context.equals(new CsvContext(1, 4, 3))); + + // different line no + assertFalse(context.equals(new CsvContext(4, 2, 3))); + + // only 1 context with line source + assertFalse(context.equals(contextWithSource)); + + // same column/line no, but different line sources + final CsvContext contextWithDifferentSource = new CsvContext(1, 2, 3); + contextWithDifferentSource.setRowSource(Arrays.asList(new Object[] { "four", "five", "six" })); + assertFalse(contextWithSource.equals(contextWithDifferentSource)); + + // same with no line source + assertTrue(context.equals(new CsvContext(1, 2, 3))); + + // same with line source + final CsvContext same = new CsvContext(1, 2, 3); + same.setRowSource(Arrays.asList(new Object[] { "one", "two", "three" })); + assertTrue(contextWithSource.equals(same)); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/util/MethodCacheTest.java b/super-csv/src/test/java/org/supercsv/util/MethodCacheTest.java index 166c6c03..02d28d36 100644 --- a/super-csv/src/test/java/org/supercsv/util/MethodCacheTest.java +++ b/super-csv/src/test/java/org/supercsv/util/MethodCacheTest.java @@ -1,163 +1,163 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.mock.ReflectionBean; - -/** - * Tests the MethodCache class. - * - * @author James Bassett - */ -public class MethodCacheTest { - - private MethodCache cache; - - /** - * Sets up before the test. - */ - @Before - public void setUp() { - cache = new MethodCache(); - } - - /** - * Tidies up after the test. - */ - @After - public void tearDown() { - cache = null; - } - - /** - * Tests getGetMethod(). - */ - @Test - public void testGetGetMethod() throws Exception { - ReflectionBean bean = new ReflectionBean(); - - // first time - not cached - final long start = System.currentTimeMillis(); - final Method uncachedGetter = cache.getGetMethod(bean, "name"); - final long uncachedTime = System.currentTimeMillis() - start; - - // second time - cached - final long start2 = System.currentTimeMillis(); - final Method cachedGetter = cache.getGetMethod(bean, "name"); - final long cachedTime = System.currentTimeMillis() - start2; - - // retrieval from cache should be at least as fast as reflection - System.out.println(String.format("getGetMethod uncachedTime: %d, cachedTime: %d", uncachedTime, cachedTime)); - assertTrue(cachedTime <= uncachedTime); - - // the same getter method should be returned in both calls - assertEquals(uncachedGetter, cachedGetter); - - // test the uncached getter works - final String name1 = "uncached"; - bean.setName(name1); - assertEquals(name1, uncachedGetter.invoke(bean)); - - // test the cached getter works - final String name2 = "cached"; - bean.setName(name2); - assertEquals(name2, cachedGetter.invoke(bean)); - } - - /** - * Tests getSetMethod(). - */ - @Test - public void testGetSetMethod() throws Exception { - ReflectionBean bean = new ReflectionBean(); - - // first time - not cached - final long start = System.currentTimeMillis(); - final Method uncachedSetter = cache.getSetMethod(bean, "name", String.class); - final long uncachedTime = System.currentTimeMillis() - start; - - // second time - cached - final long start2 = System.currentTimeMillis(); - final Method cachedSetter = cache.getSetMethod(bean, "name", String.class); - final long cachedTime = System.currentTimeMillis() - start2; - - // retrieval from cache should be at least as fast as reflection - System.out.println(String.format("getSetMethod uncachedTime: %d, cachedTime: %d", uncachedTime, cachedTime)); - assertTrue(cachedTime <= uncachedTime); - - // the same setter method should be returned in both calls - assertEquals(uncachedSetter, cachedSetter); - - // test the uncached setter works - final String name1 = "uncached"; - uncachedSetter.invoke(bean, name1); - assertEquals(name1, bean.getName()); - - // test the cached setter works - final String name2 = "cached"; - cachedSetter.invoke(bean, name2); - assertEquals(name2, bean.getName()); - } - - /** - * Tests getGetMethod() with a null object (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testGetGetMethodWithNullObject() { - cache.getGetMethod(null, "name"); - } - - /** - * Tests getGetMethod() with a null field name (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testGetGetMethodWithNullFieldName() { - cache.getGetMethod(new ReflectionBean(), null); - } - - /** - * Tests getSetMethod() with a null object (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testGetSetMethodWithNullObject() { - cache.getSetMethod(null, "name", String.class); - } - - /** - * Tests getSetMethod() with a null field name (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testGetSetMethodWithNullFieldName() { - cache.getSetMethod(new ReflectionBean(), null, String.class); - } - - /** - * Tests getSetMethod() with a null argument type (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testGetSetMethodWithNullArgumentType() { - cache.getSetMethod(new ReflectionBean(), "name", null); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.mock.ReflectionBean; + +/** + * Tests the MethodCache class. + * + * @author James Bassett + */ +public class MethodCacheTest { + + private MethodCache cache; + + /** + * Sets up before the test. + */ + @Before + public void setUp() { + cache = new MethodCache(); + } + + /** + * Tidies up after the test. + */ + @After + public void tearDown() { + cache = null; + } + + /** + * Tests getGetMethod(). + */ + @Test + public void testGetGetMethod() throws Exception { + ReflectionBean bean = new ReflectionBean(); + + // first time - not cached + final long start = System.currentTimeMillis(); + final Method uncachedGetter = cache.getGetMethod(bean, "name"); + final long uncachedTime = System.currentTimeMillis() - start; + + // second time - cached + final long start2 = System.currentTimeMillis(); + final Method cachedGetter = cache.getGetMethod(bean, "name"); + final long cachedTime = System.currentTimeMillis() - start2; + + // retrieval from cache should be at least as fast as reflection + System.out.println(String.format("getGetMethod uncachedTime: %d, cachedTime: %d", uncachedTime, cachedTime)); + assertTrue(cachedTime <= uncachedTime); + + // the same getter method should be returned in both calls + assertEquals(uncachedGetter, cachedGetter); + + // test the uncached getter works + final String name1 = "uncached"; + bean.setName(name1); + assertEquals(name1, uncachedGetter.invoke(bean)); + + // test the cached getter works + final String name2 = "cached"; + bean.setName(name2); + assertEquals(name2, cachedGetter.invoke(bean)); + } + + /** + * Tests getSetMethod(). + */ + @Test + public void testGetSetMethod() throws Exception { + ReflectionBean bean = new ReflectionBean(); + + // first time - not cached + final long start = System.currentTimeMillis(); + final Method uncachedSetter = cache.getSetMethod(bean, "name", String.class); + final long uncachedTime = System.currentTimeMillis() - start; + + // second time - cached + final long start2 = System.currentTimeMillis(); + final Method cachedSetter = cache.getSetMethod(bean, "name", String.class); + final long cachedTime = System.currentTimeMillis() - start2; + + // retrieval from cache should be at least as fast as reflection + System.out.println(String.format("getSetMethod uncachedTime: %d, cachedTime: %d", uncachedTime, cachedTime)); + assertTrue(cachedTime <= uncachedTime); + + // the same setter method should be returned in both calls + assertEquals(uncachedSetter, cachedSetter); + + // test the uncached setter works + final String name1 = "uncached"; + uncachedSetter.invoke(bean, name1); + assertEquals(name1, bean.getName()); + + // test the cached setter works + final String name2 = "cached"; + cachedSetter.invoke(bean, name2); + assertEquals(name2, bean.getName()); + } + + /** + * Tests getGetMethod() with a null object (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testGetGetMethodWithNullObject() { + cache.getGetMethod(null, "name"); + } + + /** + * Tests getGetMethod() with a null field name (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testGetGetMethodWithNullFieldName() { + cache.getGetMethod(new ReflectionBean(), null); + } + + /** + * Tests getSetMethod() with a null object (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testGetSetMethodWithNullObject() { + cache.getSetMethod(null, "name", String.class); + } + + /** + * Tests getSetMethod() with a null field name (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testGetSetMethodWithNullFieldName() { + cache.getSetMethod(new ReflectionBean(), null, String.class); + } + + /** + * Tests getSetMethod() with a null argument type (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testGetSetMethodWithNullArgumentType() { + cache.getSetMethod(new ReflectionBean(), "name", null); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/util/ReflectionUtilsTest.java b/super-csv/src/test/java/org/supercsv/util/ReflectionUtilsTest.java index 1b75b548..1fc48dd7 100644 --- a/super-csv/src/test/java/org/supercsv/util/ReflectionUtilsTest.java +++ b/super-csv/src/test/java/org/supercsv/util/ReflectionUtilsTest.java @@ -1,287 +1,287 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.supercsv.util.ReflectionUtils.findGetter; -import static org.supercsv.util.ReflectionUtils.findSetter; - -import java.lang.reflect.Constructor; -import java.security.Permission; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.supercsv.exception.SuperCsvReflectionException; -import org.supercsv.mock.ReflectionBean; - -/** - * Test the ReflectionUtils class. - * - * @author James Bassett - */ -public class ReflectionUtilsTest { - - private static final double DOUBLE_ASSERT_DELTA = 1e-15; - - private ReflectionBean bean; - - /** - * Sets up before the test. - */ - @Before - public void setUp() { - bean = new ReflectionBean(); - } - - /** - * Tidies up after the test. - */ - @After - public void tearDown() { - bean = null; - } - - /** - * Sets the SecurityManager to a mock implementation which throws a SecurityException whenever checkMemberAccess() - * is called. clearSecurityManager() should be called immediately after the test to restore things back to normal. - * - * @param allowedCalls - * the number of calls to checkMemberAccess() that should be allowed before throwing the exception. - */ - private static void initSecurityManager(final int allowedCalls) { - System.setSecurityManager(new SecurityManager() { - - private int allowedCallsLeft = allowedCalls; - - @Override - public void checkMemberAccess(Class clazz, int which) { - if( allowedCallsLeft-- <= 0 ) { - throw new SecurityException("Computer says no!"); - } - - } - - @Override - public void checkPermission(Permission perm) { - // allow resetting the SecurityManager - } - }); - } - - /** - * Clears the SecurityManager. - */ - private static void clearSecurityManager() { - System.setSecurityManager(null); - } - - /** - * Tests the findGetter() method. - */ - @Test - public void testFindGetter() throws Exception { - String name = "Bob"; - bean.setName(name); - assertEquals(name, findGetter(bean, "name").invoke(bean)); - } - - /** - * Tests the findSetter() method. - */ - @Test - public void testFindSetter() throws Exception { - String name = "Bob"; - findSetter(bean, "name", String.class).invoke(bean, name); - assertEquals(name, bean.getName()); - } - - /** - * Tests the findSetter() method with a field type that is a subtype of the setter parameter type. - */ - @Test - public void testFindSetterWithSubtype() throws Exception { - findSetter(bean, "favouriteNumber", Integer.class).invoke(bean, Integer.valueOf(123)); - assertEquals(123, bean.getFavouriteNumber().intValue()); - } - - /** - * Tests the findSetter() method with a field type that's compatible with 2 setters (the exact match should always - * be used). - */ - @Test - public void testFindSetterWithTwoOptions() throws Exception { - findSetter(bean, "overloaded", Number.class).invoke(bean, Integer.valueOf(123)); - assertEquals(123, bean.getOverloaded().intValue()); - } - - /** - * Tests the findSetter() method with a field type that's compatible with 1 setter but has the same name as another - * method (which should be ignored). - */ - @Test - public void testFindSetterWithMethodOfSameName() throws Exception { - findSetter(bean, "sailForTreasure", Boolean.class).invoke(bean, Boolean.TRUE); - assertTrue(bean.getSailForTreasure()); - } - - /** - * Tests the findSetter() method by passing primitives and wrapper classes to setters that expect wrapper classes - * and primitives respectively (this tests the autoboxing logic). - */ - @Test - public void testAutoboxing() throws Exception { - - // first try setting a wrapper values onto the primitive setters - - findSetter(bean, "primitiveInt", Integer.class).invoke(bean, Integer.valueOf(1)); - assertEquals(1, bean.getPrimitiveInt()); - - findSetter(bean, "primitiveShort", Short.class).invoke(bean, Short.valueOf("2")); - assertEquals(Short.parseShort("2"), bean.getPrimitiveShort()); - - findSetter(bean, "primitiveLong", Long.class).invoke(bean, Long.valueOf("3")); - assertEquals(Long.parseLong("3"), bean.getPrimitiveLong()); - - findSetter(bean, "primitiveDouble", Double.class).invoke(bean, Double.valueOf("4.0")); - assertEquals(Double.parseDouble("4.0"), bean.getPrimitiveDouble(), DOUBLE_ASSERT_DELTA); - - findSetter(bean, "primitiveFloat", Float.class).invoke(bean, Float.valueOf("5.0")); - assertEquals(Float.parseFloat("5.0"), bean.getPrimitiveFloat(), DOUBLE_ASSERT_DELTA); - - findSetter(bean, "primitiveChar", Character.class).invoke(bean, Character.valueOf('a')); - assertEquals('a', bean.getPrimitiveChar()); - - findSetter(bean, "primitiveByte", Byte.class).invoke(bean, Byte.valueOf("123")); - assertEquals(Byte.parseByte("123"), bean.getPrimitiveByte()); - - // now try setting primitive values onto the wrapper setters - - findSetter(bean, "integerWrapper", int.class).invoke(bean, 1); - assertEquals(Integer.valueOf(1), bean.getIntegerWrapper()); - - findSetter(bean, "shortWrapper", short.class).invoke(bean, Short.parseShort("2")); - assertEquals(Short.valueOf("2"), bean.getShortWrapper()); - - findSetter(bean, "longWrapper", long.class).invoke(bean, Long.parseLong("3")); - assertEquals(Long.valueOf("3"), bean.getLongWrapper()); - - findSetter(bean, "doubleWrapper", double.class).invoke(bean, Double.parseDouble("4.0")); - assertEquals(Double.valueOf("4.0"), bean.getDoubleWrapper()); - - findSetter(bean, "floatWrapper", float.class).invoke(bean, Float.parseFloat("5.0")); - assertEquals(Float.valueOf("5.0"), bean.getFloatWrapper()); - - findSetter(bean, "charWrapper", char.class).invoke(bean, 'a'); - assertEquals(Character.valueOf('a'), bean.getCharWrapper()); - - findSetter(bean, "byteWrapper", byte.class).invoke(bean, Byte.parseByte("123")); - assertEquals(Byte.valueOf("123"), bean.getByteWrapper()); - - } - - /** - * Tests the findGetter() method with a null object (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFindGetterWithNullObject() { - findGetter(null, "name"); - } - - /** - * Tests the findGetter() method with a null field name (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFindGetterWithNullFieldName() { - findGetter(bean, null); - } - - /** - * Tests the findGetter() method with an invalid field name (should throw an exception). - */ - @Test(expected = SuperCsvReflectionException.class) - public void testFindGetterWithInvalidFieldName() { - findGetter(bean, "invalid"); - } - - /** - * Tests the findGetter() method when a SecurityException is thrown (should throw an exception). - */ - @Test(expected = SuperCsvReflectionException.class) - public void testFindGetterWithSecurityException() { - try { - initSecurityManager(0); - findGetter(bean, "name"); - } - finally { - clearSecurityManager(); - } - - } - - /** - * Tests the findSetter() method with a null object (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFindSetterWithNullObject() { - findSetter(null, "name", String.class); - } - - /** - * Tests the findSetter() method with a null field name (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFindSetterWithNullFieldName() { - findSetter(bean, null, String.class); - } - - /** - * Tests the findSetter() method with a null field type (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFindSetterWithNullFieldType() { - findSetter(bean, "name", null); - } - - /** - * Tests the findSetter() method with an invalid field name (should throw an exception). - */ - @Test(expected = SuperCsvReflectionException.class) - public void testFindSetterWithInvalidFieldName() { - findSetter(bean, "invalid", String.class); - } - - /** - * Tests the findSetter() method with an invalid field name with a primitive parameter type (should throw an - * exception after trying both primitive and wrapper method signatures). - */ - @Test(expected = SuperCsvReflectionException.class) - public void testFindSetterWithInvalidFieldNameAndPrimitiveType() { - findSetter(bean, "invalid", int.class); - } - - /** - * Tests the private constructor for test coverage (yes, this is stupid). - */ - @Test - public void testPrivateConstructor() throws Exception { - Constructor c = ReflectionUtils.class.getDeclaredConstructors()[0]; - c.setAccessible(true); - c.newInstance(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.supercsv.util.ReflectionUtils.findGetter; +import static org.supercsv.util.ReflectionUtils.findSetter; + +import java.lang.reflect.Constructor; +import java.security.Permission; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.supercsv.exception.SuperCsvReflectionException; +import org.supercsv.mock.ReflectionBean; + +/** + * Test the ReflectionUtils class. + * + * @author James Bassett + */ +public class ReflectionUtilsTest { + + private static final double DOUBLE_ASSERT_DELTA = 1e-15; + + private ReflectionBean bean; + + /** + * Sets up before the test. + */ + @Before + public void setUp() { + bean = new ReflectionBean(); + } + + /** + * Tidies up after the test. + */ + @After + public void tearDown() { + bean = null; + } + + /** + * Sets the SecurityManager to a mock implementation which throws a SecurityException whenever checkMemberAccess() + * is called. clearSecurityManager() should be called immediately after the test to restore things back to normal. + * + * @param allowedCalls + * the number of calls to checkMemberAccess() that should be allowed before throwing the exception. + */ + private static void initSecurityManager(final int allowedCalls) { + System.setSecurityManager(new SecurityManager() { + + private int allowedCallsLeft = allowedCalls; + + @Override + public void checkMemberAccess(Class clazz, int which) { + if( allowedCallsLeft-- <= 0 ) { + throw new SecurityException("Computer says no!"); + } + + } + + @Override + public void checkPermission(Permission perm) { + // allow resetting the SecurityManager + } + }); + } + + /** + * Clears the SecurityManager. + */ + private static void clearSecurityManager() { + System.setSecurityManager(null); + } + + /** + * Tests the findGetter() method. + */ + @Test + public void testFindGetter() throws Exception { + String name = "Bob"; + bean.setName(name); + assertEquals(name, findGetter(bean, "name").invoke(bean)); + } + + /** + * Tests the findSetter() method. + */ + @Test + public void testFindSetter() throws Exception { + String name = "Bob"; + findSetter(bean, "name", String.class).invoke(bean, name); + assertEquals(name, bean.getName()); + } + + /** + * Tests the findSetter() method with a field type that is a subtype of the setter parameter type. + */ + @Test + public void testFindSetterWithSubtype() throws Exception { + findSetter(bean, "favouriteNumber", Integer.class).invoke(bean, Integer.valueOf(123)); + assertEquals(123, bean.getFavouriteNumber().intValue()); + } + + /** + * Tests the findSetter() method with a field type that's compatible with 2 setters (the exact match should always + * be used). + */ + @Test + public void testFindSetterWithTwoOptions() throws Exception { + findSetter(bean, "overloaded", Number.class).invoke(bean, Integer.valueOf(123)); + assertEquals(123, bean.getOverloaded().intValue()); + } + + /** + * Tests the findSetter() method with a field type that's compatible with 1 setter but has the same name as another + * method (which should be ignored). + */ + @Test + public void testFindSetterWithMethodOfSameName() throws Exception { + findSetter(bean, "sailForTreasure", Boolean.class).invoke(bean, Boolean.TRUE); + assertTrue(bean.getSailForTreasure()); + } + + /** + * Tests the findSetter() method by passing primitives and wrapper classes to setters that expect wrapper classes + * and primitives respectively (this tests the autoboxing logic). + */ + @Test + public void testAutoboxing() throws Exception { + + // first try setting a wrapper values onto the primitive setters + + findSetter(bean, "primitiveInt", Integer.class).invoke(bean, Integer.valueOf(1)); + assertEquals(1, bean.getPrimitiveInt()); + + findSetter(bean, "primitiveShort", Short.class).invoke(bean, Short.valueOf("2")); + assertEquals(Short.parseShort("2"), bean.getPrimitiveShort()); + + findSetter(bean, "primitiveLong", Long.class).invoke(bean, Long.valueOf("3")); + assertEquals(Long.parseLong("3"), bean.getPrimitiveLong()); + + findSetter(bean, "primitiveDouble", Double.class).invoke(bean, Double.valueOf("4.0")); + assertEquals(Double.parseDouble("4.0"), bean.getPrimitiveDouble(), DOUBLE_ASSERT_DELTA); + + findSetter(bean, "primitiveFloat", Float.class).invoke(bean, Float.valueOf("5.0")); + assertEquals(Float.parseFloat("5.0"), bean.getPrimitiveFloat(), DOUBLE_ASSERT_DELTA); + + findSetter(bean, "primitiveChar", Character.class).invoke(bean, Character.valueOf('a')); + assertEquals('a', bean.getPrimitiveChar()); + + findSetter(bean, "primitiveByte", Byte.class).invoke(bean, Byte.valueOf("123")); + assertEquals(Byte.parseByte("123"), bean.getPrimitiveByte()); + + // now try setting primitive values onto the wrapper setters + + findSetter(bean, "integerWrapper", int.class).invoke(bean, 1); + assertEquals(Integer.valueOf(1), bean.getIntegerWrapper()); + + findSetter(bean, "shortWrapper", short.class).invoke(bean, Short.parseShort("2")); + assertEquals(Short.valueOf("2"), bean.getShortWrapper()); + + findSetter(bean, "longWrapper", long.class).invoke(bean, Long.parseLong("3")); + assertEquals(Long.valueOf("3"), bean.getLongWrapper()); + + findSetter(bean, "doubleWrapper", double.class).invoke(bean, Double.parseDouble("4.0")); + assertEquals(Double.valueOf("4.0"), bean.getDoubleWrapper()); + + findSetter(bean, "floatWrapper", float.class).invoke(bean, Float.parseFloat("5.0")); + assertEquals(Float.valueOf("5.0"), bean.getFloatWrapper()); + + findSetter(bean, "charWrapper", char.class).invoke(bean, 'a'); + assertEquals(Character.valueOf('a'), bean.getCharWrapper()); + + findSetter(bean, "byteWrapper", byte.class).invoke(bean, Byte.parseByte("123")); + assertEquals(Byte.valueOf("123"), bean.getByteWrapper()); + + } + + /** + * Tests the findGetter() method with a null object (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFindGetterWithNullObject() { + findGetter(null, "name"); + } + + /** + * Tests the findGetter() method with a null field name (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFindGetterWithNullFieldName() { + findGetter(bean, null); + } + + /** + * Tests the findGetter() method with an invalid field name (should throw an exception). + */ + @Test(expected = SuperCsvReflectionException.class) + public void testFindGetterWithInvalidFieldName() { + findGetter(bean, "invalid"); + } + + /** + * Tests the findGetter() method when a SecurityException is thrown (should throw an exception). + */ + @Test(expected = SuperCsvReflectionException.class) + public void testFindGetterWithSecurityException() { + try { + initSecurityManager(0); + findGetter(bean, "name"); + } + finally { + clearSecurityManager(); + } + + } + + /** + * Tests the findSetter() method with a null object (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFindSetterWithNullObject() { + findSetter(null, "name", String.class); + } + + /** + * Tests the findSetter() method with a null field name (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFindSetterWithNullFieldName() { + findSetter(bean, null, String.class); + } + + /** + * Tests the findSetter() method with a null field type (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFindSetterWithNullFieldType() { + findSetter(bean, "name", null); + } + + /** + * Tests the findSetter() method with an invalid field name (should throw an exception). + */ + @Test(expected = SuperCsvReflectionException.class) + public void testFindSetterWithInvalidFieldName() { + findSetter(bean, "invalid", String.class); + } + + /** + * Tests the findSetter() method with an invalid field name with a primitive parameter type (should throw an + * exception after trying both primitive and wrapper method signatures). + */ + @Test(expected = SuperCsvReflectionException.class) + public void testFindSetterWithInvalidFieldNameAndPrimitiveType() { + findSetter(bean, "invalid", int.class); + } + + /** + * Tests the private constructor for test coverage (yes, this is stupid). + */ + @Test + public void testPrivateConstructor() throws Exception { + Constructor c = ReflectionUtils.class.getDeclaredConstructors()[0]; + c.setAccessible(true); + c.newInstance(); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/util/ThreeDHashMapTest.java b/super-csv/src/test/java/org/supercsv/util/ThreeDHashMapTest.java index d9978a56..f74fa593 100644 --- a/super-csv/src/test/java/org/supercsv/util/ThreeDHashMapTest.java +++ b/super-csv/src/test/java/org/supercsv/util/ThreeDHashMapTest.java @@ -1,228 +1,228 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test the ThreeDHashMap class. - * - * @author James Bassett - */ -public class ThreeDHashMapTest { - - // 3D map of people's ages by country, city and name - private ThreeDHashMap personMap; - - /** - * Sets up the map for the test. - */ - @Before - public void setUp() { - personMap = new ThreeDHashMap(); - personMap.set("Australia", "Brisbane", "Jim", 26); - personMap.set("Australia", "Brisbane", "Jane", 57); - personMap.set("Australia", "Sydney", "Harry", 19); - personMap.set("New Zealand", "Auckland", "Sally", 34); - personMap.set("New Zealand", "Wellington", "John", 88); - personMap.set("United Kingdom", "London", "Elizabeth", 34); - personMap.set("India", "Mumbai", "Vernon", 27); - } - - /** - * Tests the containsKey() method (with 2 parameters). - */ - @Test - public void testContainsKeyWithTwoParams() { - - final String firstKey = "Australia"; - final String secondKey = "Sydney"; - - // both keys exist - assertTrue(personMap.containsKey(firstKey, secondKey)); - - // first key doesn't exist - assertFalse(personMap.containsKey("invalid", secondKey)); - - // second key doesn't exist - assertFalse(personMap.containsKey(firstKey, "invalid")); - - } - - /** - * Tests the containsKey() method (with 3 parameters). - */ - @Test - public void testContainsKeyWithThreeParams() { - - final String firstKey = "United Kingdom"; - final String secondKey = "London"; - final String thirdKey = "Elizabeth"; - - // both keys exist - assertTrue(personMap.containsKey(firstKey, secondKey, thirdKey)); - - // first key doesn't exist - assertFalse(personMap.containsKey("invalid", secondKey, thirdKey)); - - // second key doesn't exist - assertFalse(personMap.containsKey(firstKey, "invalid", thirdKey)); - - // third key doesn't exist - assertFalse(personMap.containsKey(firstKey, secondKey, "invalid")); - - } - - /** - * Tests the get() method (with 1 parameter). - */ - @Test - public void testGet() { - - // invalid key - assertNull(personMap.get("invalid")); - - assertEquals(2, personMap.get("Australia").size()); - assertEquals(2, personMap.get("New Zealand").size()); - assertEquals(1, personMap.get("United Kingdom").size()); - assertEquals(1, personMap.get("India").size()); - } - - /** - * Tests the getAs2d() method. - */ - @Test - public void testGetAs2d() { - - // invalid key (should be empty) - assertEquals(0, personMap.getAs2d("invalid").size()); - - assertEquals(2, personMap.getAs2d("Australia").size()); - assertEquals(2, personMap.getAs2d("New Zealand").size()); - assertEquals(1, personMap.getAs2d("United Kingdom").size()); - assertEquals(1, personMap.getAs2d("India").size()); - } - - /** - * Tests the get() method (with 2 parameters). - */ - @Test - public void testGetWithTwoParams() { - - // invalid first key - assertNull(personMap.get("United States", "New York")); - - // invalid second key - assertNull(personMap.get("India", "Chennai")); - - assertEquals(2, personMap.get("Australia", "Brisbane").size()); - assertEquals(1, personMap.get("Australia", "Sydney").size()); - assertEquals(1, personMap.get("New Zealand", "Auckland").size()); - assertEquals(1, personMap.get("New Zealand", "Wellington").size()); - assertEquals(1, personMap.get("United Kingdom", "London").size()); - assertEquals(1, personMap.get("India", "Mumbai").size()); - } - - /** - * Tests the get() method (with 3 parameters). - */ - @Test - public void testGetWithThreeParams() { - personMap.get(null, null, null); - - // invalid first key - assertNull(personMap.get("United States", "New York", "George")); - - // invalid second key - assertNull(personMap.get("India", "Chennai", "Raj")); - - // invalid third key - assertNull(personMap.get("India", "Mumbai", "Raj")); - - assertEquals(26, personMap.get("Australia", "Brisbane", "Jim").intValue()); - assertEquals(57, personMap.get("Australia", "Brisbane", "Jane").intValue()); - assertEquals(19, personMap.get("Australia", "Sydney", "Harry").intValue()); - assertEquals(34, personMap.get("New Zealand", "Auckland", "Sally").intValue()); - assertEquals(88, personMap.get("New Zealand", "Wellington", "John").intValue()); - assertEquals(34, personMap.get("United Kingdom", "London", "Elizabeth").intValue()); - assertEquals(27, personMap.get("India", "Mumbai", "Vernon").intValue()); - } - - /** - * Tests the size() method (with no parameters). - */ - @Test - public void testSize() { - assertEquals(4, personMap.size()); - } - - /** - * Tests the size() method (with 1 parameter). - */ - @Test - public void testSizeWithOneParam() { - - // invalid key - assertEquals(0, personMap.size("United States")); - - assertEquals(2, personMap.size("Australia")); - assertEquals(2, personMap.size("New Zealand")); - assertEquals(1, personMap.size("United Kingdom")); - assertEquals(1, personMap.size("India")); - } - - /** - * Tests the size() method (with 2 parameters). - */ - @Test - public void testSizeWithTwoParams() { - - // invalid first key - assertEquals(0, personMap.size("United States", "New York")); - - // invalid second key - assertEquals(0, personMap.size("India", "Chennai")); - - assertEquals(2, personMap.size("Australia", "Brisbane")); - assertEquals(1, personMap.size("Australia", "Sydney")); - assertEquals(1, personMap.size("New Zealand", "Auckland")); - assertEquals(1, personMap.size("New Zealand", "Wellington")); - assertEquals(1, personMap.size("United Kingdom", "London")); - assertEquals(1, personMap.size("India", "Mumbai")); - } - - /** - * Tests the keySet() method. - */ - @Test - public void keySet() { - final Set expectedKeys = new HashSet(Arrays.asList("Australia", "New Zealand", - "United Kingdom", "India")); - assertEquals(expectedKeys.size(), personMap.keySet().size()); - assertTrue(personMap.keySet().containsAll(expectedKeys)); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +/** + * Test the ThreeDHashMap class. + * + * @author James Bassett + */ +public class ThreeDHashMapTest { + + // 3D map of people's ages by country, city and name + private ThreeDHashMap personMap; + + /** + * Sets up the map for the test. + */ + @Before + public void setUp() { + personMap = new ThreeDHashMap(); + personMap.set("Australia", "Brisbane", "Jim", 26); + personMap.set("Australia", "Brisbane", "Jane", 57); + personMap.set("Australia", "Sydney", "Harry", 19); + personMap.set("New Zealand", "Auckland", "Sally", 34); + personMap.set("New Zealand", "Wellington", "John", 88); + personMap.set("United Kingdom", "London", "Elizabeth", 34); + personMap.set("India", "Mumbai", "Vernon", 27); + } + + /** + * Tests the containsKey() method (with 2 parameters). + */ + @Test + public void testContainsKeyWithTwoParams() { + + final String firstKey = "Australia"; + final String secondKey = "Sydney"; + + // both keys exist + assertTrue(personMap.containsKey(firstKey, secondKey)); + + // first key doesn't exist + assertFalse(personMap.containsKey("invalid", secondKey)); + + // second key doesn't exist + assertFalse(personMap.containsKey(firstKey, "invalid")); + + } + + /** + * Tests the containsKey() method (with 3 parameters). + */ + @Test + public void testContainsKeyWithThreeParams() { + + final String firstKey = "United Kingdom"; + final String secondKey = "London"; + final String thirdKey = "Elizabeth"; + + // both keys exist + assertTrue(personMap.containsKey(firstKey, secondKey, thirdKey)); + + // first key doesn't exist + assertFalse(personMap.containsKey("invalid", secondKey, thirdKey)); + + // second key doesn't exist + assertFalse(personMap.containsKey(firstKey, "invalid", thirdKey)); + + // third key doesn't exist + assertFalse(personMap.containsKey(firstKey, secondKey, "invalid")); + + } + + /** + * Tests the get() method (with 1 parameter). + */ + @Test + public void testGet() { + + // invalid key + assertNull(personMap.get("invalid")); + + assertEquals(2, personMap.get("Australia").size()); + assertEquals(2, personMap.get("New Zealand").size()); + assertEquals(1, personMap.get("United Kingdom").size()); + assertEquals(1, personMap.get("India").size()); + } + + /** + * Tests the getAs2d() method. + */ + @Test + public void testGetAs2d() { + + // invalid key (should be empty) + assertEquals(0, personMap.getAs2d("invalid").size()); + + assertEquals(2, personMap.getAs2d("Australia").size()); + assertEquals(2, personMap.getAs2d("New Zealand").size()); + assertEquals(1, personMap.getAs2d("United Kingdom").size()); + assertEquals(1, personMap.getAs2d("India").size()); + } + + /** + * Tests the get() method (with 2 parameters). + */ + @Test + public void testGetWithTwoParams() { + + // invalid first key + assertNull(personMap.get("United States", "New York")); + + // invalid second key + assertNull(personMap.get("India", "Chennai")); + + assertEquals(2, personMap.get("Australia", "Brisbane").size()); + assertEquals(1, personMap.get("Australia", "Sydney").size()); + assertEquals(1, personMap.get("New Zealand", "Auckland").size()); + assertEquals(1, personMap.get("New Zealand", "Wellington").size()); + assertEquals(1, personMap.get("United Kingdom", "London").size()); + assertEquals(1, personMap.get("India", "Mumbai").size()); + } + + /** + * Tests the get() method (with 3 parameters). + */ + @Test + public void testGetWithThreeParams() { + personMap.get(null, null, null); + + // invalid first key + assertNull(personMap.get("United States", "New York", "George")); + + // invalid second key + assertNull(personMap.get("India", "Chennai", "Raj")); + + // invalid third key + assertNull(personMap.get("India", "Mumbai", "Raj")); + + assertEquals(26, personMap.get("Australia", "Brisbane", "Jim").intValue()); + assertEquals(57, personMap.get("Australia", "Brisbane", "Jane").intValue()); + assertEquals(19, personMap.get("Australia", "Sydney", "Harry").intValue()); + assertEquals(34, personMap.get("New Zealand", "Auckland", "Sally").intValue()); + assertEquals(88, personMap.get("New Zealand", "Wellington", "John").intValue()); + assertEquals(34, personMap.get("United Kingdom", "London", "Elizabeth").intValue()); + assertEquals(27, personMap.get("India", "Mumbai", "Vernon").intValue()); + } + + /** + * Tests the size() method (with no parameters). + */ + @Test + public void testSize() { + assertEquals(4, personMap.size()); + } + + /** + * Tests the size() method (with 1 parameter). + */ + @Test + public void testSizeWithOneParam() { + + // invalid key + assertEquals(0, personMap.size("United States")); + + assertEquals(2, personMap.size("Australia")); + assertEquals(2, personMap.size("New Zealand")); + assertEquals(1, personMap.size("United Kingdom")); + assertEquals(1, personMap.size("India")); + } + + /** + * Tests the size() method (with 2 parameters). + */ + @Test + public void testSizeWithTwoParams() { + + // invalid first key + assertEquals(0, personMap.size("United States", "New York")); + + // invalid second key + assertEquals(0, personMap.size("India", "Chennai")); + + assertEquals(2, personMap.size("Australia", "Brisbane")); + assertEquals(1, personMap.size("Australia", "Sydney")); + assertEquals(1, personMap.size("New Zealand", "Auckland")); + assertEquals(1, personMap.size("New Zealand", "Wellington")); + assertEquals(1, personMap.size("United Kingdom", "London")); + assertEquals(1, personMap.size("India", "Mumbai")); + } + + /** + * Tests the keySet() method. + */ + @Test + public void keySet() { + final Set expectedKeys = new HashSet(Arrays.asList("Australia", "New Zealand", + "United Kingdom", "India")); + assertEquals(expectedKeys.size(), personMap.keySet().size()); + assertTrue(personMap.keySet().containsAll(expectedKeys)); + } + +} diff --git a/super-csv/src/test/java/org/supercsv/util/TwoDHashMapTest.java b/super-csv/src/test/java/org/supercsv/util/TwoDHashMapTest.java index 17e3488e..31fe8858 100644 --- a/super-csv/src/test/java/org/supercsv/util/TwoDHashMapTest.java +++ b/super-csv/src/test/java/org/supercsv/util/TwoDHashMapTest.java @@ -1,197 +1,197 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test the TwoDHashMap class. - * - * @author James Bassett - */ -public class TwoDHashMapTest { - - // 2D maps of typical orchestral instrument numbers by section and instrument name - private TwoDHashMap orchestraMap; - private TwoDHashMap orchestraMap2; - - /** - * Sets up the maps TwoDHashMaps for the test, using both constructors. - * - * @throws Exception - */ - @Before - public void setUp() { - orchestraMap = new TwoDHashMap(); - populateTwoDHashMap(orchestraMap); - - orchestraMap2 = new TwoDHashMap(new HashMap>()); - populateTwoDHashMap(orchestraMap2); - } - - /** - * Populates a TwoDHashMap with test data. - * - * @param map - * the map to populate - */ - private static void populateTwoDHashMap(TwoDHashMap map) { - map.set("Woodwind", "Piccolo", 1); - map.set("Woodwind", "Flute", 3); - map.set("Woodwind", "Oboe", 2); - map.set("Woodwind", "Cor Anglais", 1); - map.set("Woodwind", "Clarinet", 3); - map.set("Woodwind", "Bass Clarinet", 1); - map.set("Woodwind", "Soprano Saxophone", 1); - map.set("Woodwind", "Alto Saxophone", 1); - map.set("Woodwind", "Tenor Saxophone", 1); - map.set("Woodwind", "Baritone Saxophone", 1); - map.set("Woodwind", "Bassoon", 2); - map.set("Woodwind", "Contrabassoon", 1); - map.set("Brass", "Horn", 4); - map.set("Brass", "Trumpet", 3); - map.set("Brass", "Trombone", 4); - map.set("Brass", "Tuba", 1); - map.set("Percussion", "Timpani", 2); - map.set("Percussion", "Snare Drum", 1); - map.set("Percussion", "Tenor Drum", 1); - map.set("Percussion", "Bass Drum", 1); - map.set("Percussion", "Cymbals", 1); - map.set("Strings", "Harp", 1); - map.set("Strings", "Violin (I)", 16); - map.set("Strings", "Violin (II)", 16); - map.set("Strings", "Viola", 12); - map.set("Strings", "Cello", 10); - map.set("Strings", "Double Bass", 8); - } - - /** - * Tests the containsKey() method on both maps. - */ - @Test - public void testContainsKey() { - - final String key1 = "Woodwind"; - final String key2 = "Bassoon"; - - // both keys exist - assertTrue(orchestraMap.containsKey(key1, key2)); - assertTrue(orchestraMap2.containsKey(key1, key2)); - - // first key doesn't exist - assertFalse(orchestraMap.containsKey("invalid", key2)); - assertFalse(orchestraMap2.containsKey("invalid", key2)); - - // second key doesn't exist - assertFalse(orchestraMap.containsKey(key1, "invalid")); - assertFalse(orchestraMap2.containsKey(key1, "invalid")); - - } - - /** - * Tests the get() method on both maps. - */ - @Test - public void testGet() { - - final String key1 = "Percussion"; - final String key2 = "Timpani"; - final Integer expectedNo = 2; - - // both keys exist - assertEquals(expectedNo, orchestraMap.get(key1, key2)); - assertEquals(expectedNo, orchestraMap2.get(key1, key2)); - - // first key doesn't exist - assertNull(orchestraMap.get("invalid", key2)); - assertNull(orchestraMap2.get("invalid", key2)); - - // second key doesn't exist - assertNull(orchestraMap.get(key1, "invalid")); - assertNull(orchestraMap2.get(key1, "invalid")); - - } - - /** - * Tests the size() method on both maps. - */ - @Test - public void testSize() { - final int expectedSize = 4; - assertEquals(expectedSize, orchestraMap.size()); - assertEquals(expectedSize, orchestraMap2.size()); - } - - /** - * Tests the size() method (for the inner map) on both maps. - */ - @Test - public void testSizeWithParam() { - final int expectedWoodwinds = 12; - final int expectedBrass = 4; - final int expectedPercussion = 5; - final int expectedStrings = 6; - - // first key doesn't exist - assertEquals(0, orchestraMap.size("invalid")); - assertEquals(0, orchestraMap2.size("invalid")); - - assertEquals(expectedWoodwinds, orchestraMap.size("Woodwind")); - assertEquals(expectedWoodwinds, orchestraMap2.size("Woodwind")); - - assertEquals(expectedBrass, orchestraMap.size("Brass")); - assertEquals(expectedBrass, orchestraMap2.size("Brass")); - - assertEquals(expectedPercussion, orchestraMap.size("Percussion")); - assertEquals(expectedPercussion, orchestraMap2.size("Percussion")); - - assertEquals(expectedStrings, orchestraMap.size("Strings")); - assertEquals(expectedStrings, orchestraMap2.size("Strings")); - } - - /** - * Tests the keySet() method on both maps. - */ - @Test - public void keySet() { - final Set expectedKeys = new HashSet( - Arrays.asList("Woodwind", "Brass", "Percussion", "Strings")); - assertEquals(expectedKeys.size(), orchestraMap.keySet().size()); - assertEquals(expectedKeys.size(), orchestraMap2.keySet().size()); - assertTrue(orchestraMap.keySet().containsAll(expectedKeys)); - assertTrue(orchestraMap2.keySet().containsAll(expectedKeys)); - } - - /** - * Tests the constructor with a null argument (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testConstructorWithNull() { - new TwoDHashMap(null); - - } -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +/** + * Test the TwoDHashMap class. + * + * @author James Bassett + */ +public class TwoDHashMapTest { + + // 2D maps of typical orchestral instrument numbers by section and instrument name + private TwoDHashMap orchestraMap; + private TwoDHashMap orchestraMap2; + + /** + * Sets up the maps TwoDHashMaps for the test, using both constructors. + * + * @throws Exception + */ + @Before + public void setUp() { + orchestraMap = new TwoDHashMap(); + populateTwoDHashMap(orchestraMap); + + orchestraMap2 = new TwoDHashMap(new HashMap>()); + populateTwoDHashMap(orchestraMap2); + } + + /** + * Populates a TwoDHashMap with test data. + * + * @param map + * the map to populate + */ + private static void populateTwoDHashMap(TwoDHashMap map) { + map.set("Woodwind", "Piccolo", 1); + map.set("Woodwind", "Flute", 3); + map.set("Woodwind", "Oboe", 2); + map.set("Woodwind", "Cor Anglais", 1); + map.set("Woodwind", "Clarinet", 3); + map.set("Woodwind", "Bass Clarinet", 1); + map.set("Woodwind", "Soprano Saxophone", 1); + map.set("Woodwind", "Alto Saxophone", 1); + map.set("Woodwind", "Tenor Saxophone", 1); + map.set("Woodwind", "Baritone Saxophone", 1); + map.set("Woodwind", "Bassoon", 2); + map.set("Woodwind", "Contrabassoon", 1); + map.set("Brass", "Horn", 4); + map.set("Brass", "Trumpet", 3); + map.set("Brass", "Trombone", 4); + map.set("Brass", "Tuba", 1); + map.set("Percussion", "Timpani", 2); + map.set("Percussion", "Snare Drum", 1); + map.set("Percussion", "Tenor Drum", 1); + map.set("Percussion", "Bass Drum", 1); + map.set("Percussion", "Cymbals", 1); + map.set("Strings", "Harp", 1); + map.set("Strings", "Violin (I)", 16); + map.set("Strings", "Violin (II)", 16); + map.set("Strings", "Viola", 12); + map.set("Strings", "Cello", 10); + map.set("Strings", "Double Bass", 8); + } + + /** + * Tests the containsKey() method on both maps. + */ + @Test + public void testContainsKey() { + + final String key1 = "Woodwind"; + final String key2 = "Bassoon"; + + // both keys exist + assertTrue(orchestraMap.containsKey(key1, key2)); + assertTrue(orchestraMap2.containsKey(key1, key2)); + + // first key doesn't exist + assertFalse(orchestraMap.containsKey("invalid", key2)); + assertFalse(orchestraMap2.containsKey("invalid", key2)); + + // second key doesn't exist + assertFalse(orchestraMap.containsKey(key1, "invalid")); + assertFalse(orchestraMap2.containsKey(key1, "invalid")); + + } + + /** + * Tests the get() method on both maps. + */ + @Test + public void testGet() { + + final String key1 = "Percussion"; + final String key2 = "Timpani"; + final Integer expectedNo = 2; + + // both keys exist + assertEquals(expectedNo, orchestraMap.get(key1, key2)); + assertEquals(expectedNo, orchestraMap2.get(key1, key2)); + + // first key doesn't exist + assertNull(orchestraMap.get("invalid", key2)); + assertNull(orchestraMap2.get("invalid", key2)); + + // second key doesn't exist + assertNull(orchestraMap.get(key1, "invalid")); + assertNull(orchestraMap2.get(key1, "invalid")); + + } + + /** + * Tests the size() method on both maps. + */ + @Test + public void testSize() { + final int expectedSize = 4; + assertEquals(expectedSize, orchestraMap.size()); + assertEquals(expectedSize, orchestraMap2.size()); + } + + /** + * Tests the size() method (for the inner map) on both maps. + */ + @Test + public void testSizeWithParam() { + final int expectedWoodwinds = 12; + final int expectedBrass = 4; + final int expectedPercussion = 5; + final int expectedStrings = 6; + + // first key doesn't exist + assertEquals(0, orchestraMap.size("invalid")); + assertEquals(0, orchestraMap2.size("invalid")); + + assertEquals(expectedWoodwinds, orchestraMap.size("Woodwind")); + assertEquals(expectedWoodwinds, orchestraMap2.size("Woodwind")); + + assertEquals(expectedBrass, orchestraMap.size("Brass")); + assertEquals(expectedBrass, orchestraMap2.size("Brass")); + + assertEquals(expectedPercussion, orchestraMap.size("Percussion")); + assertEquals(expectedPercussion, orchestraMap2.size("Percussion")); + + assertEquals(expectedStrings, orchestraMap.size("Strings")); + assertEquals(expectedStrings, orchestraMap2.size("Strings")); + } + + /** + * Tests the keySet() method on both maps. + */ + @Test + public void keySet() { + final Set expectedKeys = new HashSet( + Arrays.asList("Woodwind", "Brass", "Percussion", "Strings")); + assertEquals(expectedKeys.size(), orchestraMap.keySet().size()); + assertEquals(expectedKeys.size(), orchestraMap2.keySet().size()); + assertTrue(orchestraMap.keySet().containsAll(expectedKeys)); + assertTrue(orchestraMap2.keySet().containsAll(expectedKeys)); + } + + /** + * Tests the constructor with a null argument (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testConstructorWithNull() { + new TwoDHashMap(null); + + } +} diff --git a/super-csv/src/test/java/org/supercsv/util/UtilTest.java b/super-csv/src/test/java/org/supercsv/util/UtilTest.java index 94fb26c4..d6bc158c 100644 --- a/super-csv/src/test/java/org/supercsv/util/UtilTest.java +++ b/super-csv/src/test/java/org/supercsv/util/UtilTest.java @@ -1,267 +1,267 @@ -/* - * Copyright 2007 Kasper B. Graversen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.supercsv.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.supercsv.cellprocessor.ParseInt; -import org.supercsv.cellprocessor.ift.CellProcessor; -import org.supercsv.exception.SuperCsvException; -import org.supercsv.mock.IdentityTransform; - -/** - * Test the Util class. - * - * @author James Bassett - */ -public class UtilTest { - - private static final String[] NAME_MAPPING = new String[] { "name", null, "city" }; - - private static final List LIST = Arrays.asList("Ezio", "25", "Venice"); - - private static final CellProcessor[] PROCESSORS = new CellProcessor[] { new IdentityTransform(), new ParseInt(), - null }; - - private static final int LINE_NO = 23; - - private static final int ROW_NO = 12; - - private static final Map MAP = new HashMap(); - static { - MAP.put("name", "Ezio"); - MAP.put("age", 25); - MAP.put("city", "Venice"); - } - - /** - * Tests the filterMapToList() method (the age attribute is not used). - */ - @Test - public void testFilterMapToList() { - List list = Util.filterMapToList(MAP, NAME_MAPPING); - assertTrue(list.size() == 3); - assertEquals("Ezio", list.get(0)); - assertNull(list.get(1)); - assertEquals("Venice", list.get(2)); - } - - /** - * Tests the filterMapToList() method with a null map (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFilterMapToListWithNullMap() { - Util.filterMapToList(null, NAME_MAPPING); - } - - /** - * Tests the filterMapToList() method with a null name mapping array (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFilterMapToListWithNullNameMapping() { - Util.filterMapToList(MAP, null); - } - - /** - * Tests the filterListToMap() method. - */ - @Test - public void testFilterListToMap() { - final Map map = new HashMap(); - Util.filterListToMap(map, NAME_MAPPING, LIST); - assertTrue(map.size() == 2); - assertEquals("Ezio", map.get("name")); - assertEquals("Venice", map.get("city")); - } - - /** - * Tests the filterListToMap() method with a null destination map (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFilterListToMapWithNullDestMap() { - Util.filterListToMap(null, NAME_MAPPING, LIST); - } - - /** - * Tests the filterListToMap() method with a null name mapping array (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFilterListToMapWithNullNameMapping() { - Util.filterListToMap(new HashMap(), null, LIST); - } - - /** - * Tests the filterListToMap() method with a null source list (should throw an exception). - */ - @Test(expected = NullPointerException.class) - public void testFilterListToMapWithNullSourceList() { - Util.filterListToMap(new HashMap(), NAME_MAPPING, null); - } - - /** - * Tests the filterListToMap() method with a name mapping array with too few elements (should throw an exception). - */ - @Test(expected = SuperCsvException.class) - public void testFilterListToMapWithSizeMismatch() { - Util.filterListToMap(new HashMap(), new String[] { "notEnoughColumns" }, LIST); - } - - /** - * Tests the filterListToMap() method with a name mapping array with duplicate elements (should throw an exception). - */ - @Test(expected = SuperCsvException.class) - public void testFilterListToMapWithDuplicateNameMapping() { - Util.filterListToMap(new HashMap(), new String[] { "name", "name", "city" }, LIST); - } - - /** - * Tests the executeCellProcessors() method. - */ - @Test - public void testExecuteCellProcessors() { - List destinationList = new ArrayList(); - Util.executeCellProcessors(destinationList, LIST, PROCESSORS, LINE_NO, ROW_NO); - assertTrue(destinationList.size() == 3); - assertEquals("Ezio", destinationList.get(0)); - assertEquals(Integer.valueOf(25), destinationList.get(1)); - assertEquals("Venice", destinationList.get(2)); - } - - /** - * Tests the executeCellProcessors() method with a null destination List (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testExecuteCellProcessorsWithNullDestination() { - Util.executeCellProcessors(null, LIST, PROCESSORS, LINE_NO, ROW_NO); - } - - /** - * Tests the executeCellProcessors() method with a null source List (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testExecuteCellProcessorsWithNullSource() { - Util.executeCellProcessors(new ArrayList(), null, PROCESSORS, LINE_NO, ROW_NO); - } - - /** - * Tests the executeCellProcessors() method with a processors array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testExecuteCellProcessorsWithNullProcessors() { - Util.executeCellProcessors(new ArrayList(), LIST, null, LINE_NO, ROW_NO); - } - - /** - * Tests the executeCellProcessors() method with a source List whose size doesn't match the number of CellProcessors - * (should throw an Exception). - */ - @Test(expected = SuperCsvException.class) - public void testExecuteCellProcessorsWithSizeMismatch() { - final List invalidSizeList = new ArrayList(); - Util.executeCellProcessors(new ArrayList(), invalidSizeList, PROCESSORS, LINE_NO, ROW_NO); - } - - /** - * Tests the filterMapToObjectArray() method. - */ - @Test - public void testFilterMapToObjectArray() { - final Object[] objectArray = Util.filterMapToObjectArray(MAP, NAME_MAPPING); - assertTrue(objectArray.length == 3); - assertEquals("Ezio", objectArray[0]); - assertNull(objectArray[1]); - assertEquals("Venice", objectArray[2]); - } - - /** - * Tests the filterMapToObjectArray() method with a null values Map (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testFilterMapToObjectArrayWithNullValues() { - Util.filterMapToObjectArray(null, NAME_MAPPING); - } - - /** - * Tests the filterMapToObjectArray() method with a null nameMapping array (should throw an Exception). - */ - @Test(expected = NullPointerException.class) - public void testFilterMapToObjectArrayWithNullNameMapping() { - Util.filterMapToObjectArray(MAP, null); - } - - /** - * Tests the objectArrayToStringArray() method. - */ - @Test - public void testObjectArrayToStringArray() { - final Object[] input = new Object[] { 1, null, "three" }; - final String[] output = Util.objectArrayToStringArray(input); - assertEquals(3, output.length); - assertEquals("1", output[0]); - assertNull(output[1]); - assertEquals("three", output[2]); - } - - /** - * Tests the objectArrayToStringArray() method with a null array. - */ - @Test - public void testObjectArrayToStringArrayWithNullArray() { - assertNull(Util.objectArrayToStringArray(null)); - } - - /** - * Tests the objectListToStringArray() method. - */ - @Test - public void testObjectListToStringArray() { - final List input = Arrays.asList(new Object[] { 1, null, "three" }); - final String[] output = Util.objectListToStringArray(input); - assertEquals(3, output.length); - assertEquals("1", output[0]); - assertNull(output[1]); - assertEquals("three", output[2]); - } - - /** - * Tests the objectListToStringArray() method with a null List. - */ - @Test - public void testObjectListToStringArrayWithNullList() { - assertNull(Util.objectListToStringArray(null)); - } - - /** - * Tests the private constructor for test coverage (yes, this is stupid). - */ - @Test - public void testPrivateConstructor() throws Exception { - Constructor c = Util.class.getDeclaredConstructors()[0]; - c.setAccessible(true); - c.newInstance(); - } - -} +/* + * Copyright 2007 Kasper B. Graversen + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.supercsv.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.supercsv.cellprocessor.ParseInt; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.exception.SuperCsvException; +import org.supercsv.mock.IdentityTransform; + +/** + * Test the Util class. + * + * @author James Bassett + */ +public class UtilTest { + + private static final String[] NAME_MAPPING = new String[] { "name", null, "city" }; + + private static final List LIST = Arrays.asList("Ezio", "25", "Venice"); + + private static final CellProcessor[] PROCESSORS = new CellProcessor[] { new IdentityTransform(), new ParseInt(), + null }; + + private static final int LINE_NO = 23; + + private static final int ROW_NO = 12; + + private static final Map MAP = new HashMap(); + static { + MAP.put("name", "Ezio"); + MAP.put("age", 25); + MAP.put("city", "Venice"); + } + + /** + * Tests the filterMapToList() method (the age attribute is not used). + */ + @Test + public void testFilterMapToList() { + List list = Util.filterMapToList(MAP, NAME_MAPPING); + assertTrue(list.size() == 3); + assertEquals("Ezio", list.get(0)); + assertNull(list.get(1)); + assertEquals("Venice", list.get(2)); + } + + /** + * Tests the filterMapToList() method with a null map (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFilterMapToListWithNullMap() { + Util.filterMapToList(null, NAME_MAPPING); + } + + /** + * Tests the filterMapToList() method with a null name mapping array (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFilterMapToListWithNullNameMapping() { + Util.filterMapToList(MAP, null); + } + + /** + * Tests the filterListToMap() method. + */ + @Test + public void testFilterListToMap() { + final Map map = new HashMap(); + Util.filterListToMap(map, NAME_MAPPING, LIST); + assertTrue(map.size() == 2); + assertEquals("Ezio", map.get("name")); + assertEquals("Venice", map.get("city")); + } + + /** + * Tests the filterListToMap() method with a null destination map (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFilterListToMapWithNullDestMap() { + Util.filterListToMap(null, NAME_MAPPING, LIST); + } + + /** + * Tests the filterListToMap() method with a null name mapping array (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFilterListToMapWithNullNameMapping() { + Util.filterListToMap(new HashMap(), null, LIST); + } + + /** + * Tests the filterListToMap() method with a null source list (should throw an exception). + */ + @Test(expected = NullPointerException.class) + public void testFilterListToMapWithNullSourceList() { + Util.filterListToMap(new HashMap(), NAME_MAPPING, null); + } + + /** + * Tests the filterListToMap() method with a name mapping array with too few elements (should throw an exception). + */ + @Test(expected = SuperCsvException.class) + public void testFilterListToMapWithSizeMismatch() { + Util.filterListToMap(new HashMap(), new String[] { "notEnoughColumns" }, LIST); + } + + /** + * Tests the filterListToMap() method with a name mapping array with duplicate elements (should throw an exception). + */ + @Test(expected = SuperCsvException.class) + public void testFilterListToMapWithDuplicateNameMapping() { + Util.filterListToMap(new HashMap(), new String[] { "name", "name", "city" }, LIST); + } + + /** + * Tests the executeCellProcessors() method. + */ + @Test + public void testExecuteCellProcessors() { + List destinationList = new ArrayList(); + Util.executeCellProcessors(destinationList, LIST, PROCESSORS, LINE_NO, ROW_NO); + assertTrue(destinationList.size() == 3); + assertEquals("Ezio", destinationList.get(0)); + assertEquals(Integer.valueOf(25), destinationList.get(1)); + assertEquals("Venice", destinationList.get(2)); + } + + /** + * Tests the executeCellProcessors() method with a null destination List (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testExecuteCellProcessorsWithNullDestination() { + Util.executeCellProcessors(null, LIST, PROCESSORS, LINE_NO, ROW_NO); + } + + /** + * Tests the executeCellProcessors() method with a null source List (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testExecuteCellProcessorsWithNullSource() { + Util.executeCellProcessors(new ArrayList(), null, PROCESSORS, LINE_NO, ROW_NO); + } + + /** + * Tests the executeCellProcessors() method with a processors array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testExecuteCellProcessorsWithNullProcessors() { + Util.executeCellProcessors(new ArrayList(), LIST, null, LINE_NO, ROW_NO); + } + + /** + * Tests the executeCellProcessors() method with a source List whose size doesn't match the number of CellProcessors + * (should throw an Exception). + */ + @Test(expected = SuperCsvException.class) + public void testExecuteCellProcessorsWithSizeMismatch() { + final List invalidSizeList = new ArrayList(); + Util.executeCellProcessors(new ArrayList(), invalidSizeList, PROCESSORS, LINE_NO, ROW_NO); + } + + /** + * Tests the filterMapToObjectArray() method. + */ + @Test + public void testFilterMapToObjectArray() { + final Object[] objectArray = Util.filterMapToObjectArray(MAP, NAME_MAPPING); + assertTrue(objectArray.length == 3); + assertEquals("Ezio", objectArray[0]); + assertNull(objectArray[1]); + assertEquals("Venice", objectArray[2]); + } + + /** + * Tests the filterMapToObjectArray() method with a null values Map (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testFilterMapToObjectArrayWithNullValues() { + Util.filterMapToObjectArray(null, NAME_MAPPING); + } + + /** + * Tests the filterMapToObjectArray() method with a null nameMapping array (should throw an Exception). + */ + @Test(expected = NullPointerException.class) + public void testFilterMapToObjectArrayWithNullNameMapping() { + Util.filterMapToObjectArray(MAP, null); + } + + /** + * Tests the objectArrayToStringArray() method. + */ + @Test + public void testObjectArrayToStringArray() { + final Object[] input = new Object[] { 1, null, "three" }; + final String[] output = Util.objectArrayToStringArray(input); + assertEquals(3, output.length); + assertEquals("1", output[0]); + assertNull(output[1]); + assertEquals("three", output[2]); + } + + /** + * Tests the objectArrayToStringArray() method with a null array. + */ + @Test + public void testObjectArrayToStringArrayWithNullArray() { + assertNull(Util.objectArrayToStringArray(null)); + } + + /** + * Tests the objectListToStringArray() method. + */ + @Test + public void testObjectListToStringArray() { + final List input = Arrays.asList(new Object[] { 1, null, "three" }); + final String[] output = Util.objectListToStringArray(input); + assertEquals(3, output.length); + assertEquals("1", output[0]); + assertNull(output[1]); + assertEquals("three", output[2]); + } + + /** + * Tests the objectListToStringArray() method with a null List. + */ + @Test + public void testObjectListToStringArrayWithNullList() { + assertNull(Util.objectListToStringArray(null)); + } + + /** + * Tests the private constructor for test coverage (yes, this is stupid). + */ + @Test + public void testPrivateConstructor() throws Exception { + Constructor c = Util.class.getDeclaredConstructors()[0]; + c.setAccessible(true); + c.newInstance(); + } + +} diff --git a/super-csv/src/test/resources/customers.csv b/super-csv/src/test/resources/customers.csv index b1a3f643..60a5ac53 100644 --- a/super-csv/src/test/resources/customers.csv +++ b/super-csv/src/test/resources/customers.csv @@ -1,13 +1,13 @@ -customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints -1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway -Mountain View, CA 94043 -United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 -2,Bob,Down,25/02/1919,"1601 Willow Rd. -Menlo Park, CA 94025 -United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 -3,Alice,Wunderland,08/08/1985,"One Microsoft Way -Redmond, WA 98052-6399 -United States",Y,0,"""Play it, Sam. Play ""As Time Goes By."""" - Casablanca",throughthelookingglass@yahoo.com,2255887799 -4,Bill,Jobs,10/07/1973,"2701 San Tomas Expressway -Santa Clara, CA 95050 +customerNo,firstName,lastName,birthDate,mailingAddress,married,numberOfKids,favouriteQuote,email,loyaltyPoints +1,John,Dunbar,13/06/1945,"1600 Amphitheatre Parkway +Mountain View, CA 94043 +United States",,,"""May the Force be with you."" - Star Wars",jdunbar@gmail.com,0 +2,Bob,Down,25/02/1919,"1601 Willow Rd. +Menlo Park, CA 94025 +United States",Y,0,"""Frankly, my dear, I don't give a damn."" - Gone With The Wind",bobdown@hotmail.com,123456 +3,Alice,Wunderland,08/08/1985,"One Microsoft Way +Redmond, WA 98052-6399 +United States",Y,0,"""Play it, Sam. Play ""As Time Goes By."""" - Casablanca",throughthelookingglass@yahoo.com,2255887799 +4,Bill,Jobs,10/07/1973,"2701 San Tomas Expressway +Santa Clara, CA 95050 United States",Y,3,"""You've got to ask yourself one question: ""Do I feel lucky?"" Well, do ya, punk?"" - Dirty Harry",billy34@hotmail.com,36 \ No newline at end of file diff --git a/supercsv_eclipse_cleanup.xml b/supercsv_eclipse_cleanup.xml index 421bb61e..17700ce3 100644 --- a/supercsv_eclipse_cleanup.xml +++ b/supercsv_eclipse_cleanup.xml @@ -1,51 +1,51 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/supercsv_eclipse_formatter.xml b/supercsv_eclipse_formatter.xml index eb0b1675..0ffec2e3 100644 --- a/supercsv_eclipse_formatter.xml +++ b/supercsv_eclipse_formatter.xml @@ -1,555 +1,555 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +