├── src
├── site
│ └── resources
│ │ └── css
│ │ └── site.css
├── test
│ ├── java
│ │ ├── integrationTest
│ │ │ ├── SR34
│ │ │ │ ├── NULSpecialChar2.log
│ │ │ │ ├── NULSpecialChar3.log
│ │ │ │ └── SR34Test.java
│ │ │ ├── issue3402853
│ │ │ │ ├── user.csv
│ │ │ │ ├── HeaderColumnNameMappingStrategyUserTest.java
│ │ │ │ └── MockUserBean.java
│ │ │ ├── issue2564366
│ │ │ │ ├── data.csv
│ │ │ │ └── DataReader.java
│ │ │ ├── issue2153020
│ │ │ │ ├── Sample.csv
│ │ │ │ └── DataReader.java
│ │ │ └── isClosed
│ │ │ │ └── isClosedTest.java
│ │ └── com
│ │ │ └── opencsv
│ │ │ ├── bean
│ │ │ ├── mocks
│ │ │ │ ├── UnbindableMockBean.java
│ │ │ │ ├── SimpleAnnotatedMockBeanPrivateFields.java
│ │ │ │ ├── SimpleAnnotatedMockBean.java
│ │ │ │ ├── Bug133Bean.java
│ │ │ │ ├── SimpleAnnotatedMockBeanAllModifierTypes.java
│ │ │ │ ├── SimplePartiallyAnnotatedMockBean.java
│ │ │ │ ├── GetterMissing.java
│ │ │ │ ├── ComplexDerivedClassForCustomAnnotation.java
│ │ │ │ ├── GetterPrivate.java
│ │ │ │ ├── TestCase34.java
│ │ │ │ ├── TestCase80.java
│ │ │ │ ├── BindCustomToWrongDataType.java
│ │ │ │ ├── ComplexClassForCustomAnnotation.java
│ │ │ │ ├── AnnotatedMockBean.java
│ │ │ │ ├── MinimalCsvBindBeanForWriting.java
│ │ │ │ ├── TestCases21And63.java
│ │ │ │ ├── MinimalCsvBindByNameBeanForWriting.java
│ │ │ │ ├── BindByNameUnknownTypeLegacy.java
│ │ │ │ ├── MinimalCsvBindByPositionBeanForWriting.java
│ │ │ │ ├── AnnotatedMockBeanFullDerived.java
│ │ │ │ ├── BindByNameUnknownType.java
│ │ │ │ ├── ConverterComplexClassForCustomAnnotation.java
│ │ │ │ ├── MockBean.java
│ │ │ │ └── CustomTestMapper.java
│ │ │ ├── customconverter
│ │ │ │ └── BadIntConverter.java
│ │ │ ├── CsvToBeanDoubleTest.java
│ │ │ ├── IterableCSVToBeanBuilderTest.java
│ │ │ ├── CsvToBeanFilterTest.java
│ │ │ ├── HeaderColumnNameTranslateMappingStrategyTest.java
│ │ │ └── HeaderColumnNameMappingStrategyTest.java
│ │ │ ├── CSVWriterExceptionThrower.java
│ │ │ ├── TestUtilitiesTest.java
│ │ │ ├── TestUtilities.java
│ │ │ ├── MockResultSetMetaDataBuilder.java
│ │ │ ├── CSVIteratorTest.java
│ │ │ ├── OpencsvTest.java
│ │ │ ├── MockClob.java
│ │ │ ├── RFC4180ParserBuilderTest.java
│ │ │ ├── stream
│ │ │ └── reader
│ │ │ │ └── LineReaderTest.java
│ │ │ ├── CSVReaderBuilderTest.java
│ │ │ └── CSVParserBuilderTest.java
│ ├── resources
│ │ ├── testinputcase51.csv
│ │ ├── testinputcase55.csv
│ │ ├── testinputcase60.csv
│ │ ├── testinputcase78.csv
│ │ ├── testinputcase7.csv
│ │ ├── testinputcase81.csv
│ │ ├── testinputcase82.csv
│ │ ├── testinputcase83.csv
│ │ ├── testinputcase11.csv
│ │ ├── testinputcase40.csv
│ │ ├── testinputcase16.csv
│ │ ├── testinputcase38.csv
│ │ ├── testinputcase41.csv
│ │ ├── testinputwriteposfullgood.csv
│ │ ├── testinputposfullgood.csv
│ │ ├── testinputwritecustomposfullgood.csv
│ │ ├── testinputfullgood.csv
│ │ ├── testinputderivedgood.csv
│ │ ├── testinputmaximumbuilder.csv
│ │ ├── AnnotationWritingTestPlan.csv
│ │ ├── testinputposcustomgood.csv
│ │ └── testinputcustomgood.csv
│ └── groovy
│ │ └── com
│ │ └── opencsv
│ │ ├── CSVParserBuilderSpec.groovy
│ │ └── CSVIteratorSpec.groovy
└── main
│ └── java
│ └── com
│ └── opencsv
│ ├── enums
│ ├── CSVReaderNullFieldIndicator.java
│ └── package-info.java
│ ├── stream
│ └── reader
│ │ ├── package-info.java
│ │ └── LineReader.java
│ ├── exceptions
│ ├── package-info.java
│ ├── CsvRuntimeException.java
│ ├── CsvException.java
│ ├── CsvBadConverterException.java
│ ├── CsvConstraintViolationException.java
│ ├── CsvRequiredFieldEmptyException.java
│ ├── CsvDataTypeMismatchException.java
│ └── CsvBeanIntrospectionException.java
│ ├── bean
│ ├── CsvBind.java
│ ├── package-info.java
│ ├── customconverter
│ │ ├── package-info.java
│ │ ├── ConvertGermanToBooleanRequired.java
│ │ ├── ConvertSplitOnWhitespace.java
│ │ └── ConvertGermanToBoolean.java
│ ├── CsvCustomBindByPosition.java
│ ├── CsvCustomBindByName.java
│ ├── CsvDate.java
│ ├── HeaderColumnNameTranslateMappingStrategy.java
│ ├── CsvToBeanFilter.java
│ ├── CsvBindByName.java
│ ├── CsvBindByPosition.java
│ ├── BeanField.java
│ ├── AbstractCSVToBean.java
│ ├── IterableCSVToBeanBuilder.java
│ ├── MappingStrategy.java
│ └── MappingUtils.java
│ ├── package-info.java
│ ├── CSVIterator.java
│ ├── ResultSetHelper.java
│ ├── RFC4180ParserBuilder.java
│ └── ICSVParser.java
├── lib
└── junit-4.7.jar
├── README.md
├── .gitignore
├── examples
├── addresses.csv
└── AddressExample.java
├── checkstyle-suppressions.xml
├── checkstyle.xml
└── pmd-ruleset.xml
/src/site/resources/css/site.css:
--------------------------------------------------------------------------------
1 | /* custom css stuff can go in here */
2 |
3 |
--------------------------------------------------------------------------------
/lib/junit-4.7.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cygri/opencsv/HEAD/lib/junit-4.7.jar
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | OpenCSV is a very simple csv (comma-separated values) parser library for Java.
--------------------------------------------------------------------------------
/src/test/java/integrationTest/SR34/NULSpecialChar2.log:
--------------------------------------------------------------------------------
1 | 10,"IBM","2015063","064230733910"," ","01 "
2 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/SR34/NULSpecialChar3.log:
--------------------------------------------------------------------------------
1 | 10,"IBM","2015063","064230733910"," ","01 "
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | myfile.csv
2 | target/
3 | build
4 | bin
5 | deploy
6 | .idea
7 | *.iml
8 | nbactions.xml
9 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/issue3402853/user.csv:
--------------------------------------------------------------------------------
1 | "id","email","profile_id","first_name","last_name"
2 | "475592","rbst218@yahoo.com","bc1er1163","\\\"CHia Sia Ta",""
3 | "12345","kazem.naderi@tt.com","bc234a","kazem","naderi"
--------------------------------------------------------------------------------
/examples/addresses.csv:
--------------------------------------------------------------------------------
1 | Joe Demo,"2 Demo Street,
2 | Demoville,
3 | Australia. 2615",joe@someaddress.com
4 | Jim Sample,"3 Sample Street, Sampleville, Australia. 2615",jim@sample.com
5 | Jack Example,"1 Example Street, Exampleville, Australia.
6 | 2615",jack@example.com
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/UnbindableMockBean.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | import com.opencsv.bean.CsvBind;
4 |
5 | import java.util.Date;
6 | import java.util.List;
7 |
8 | public class UnbindableMockBean {
9 | @CsvBind
10 | private List date;
11 | }
12 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/issue2564366/data.csv:
--------------------------------------------------------------------------------
1 | "CompanyName","CompanyNumber","ClientName","ClientFirstName","ClientLastName","ClientId","ClientGroupId","Logon","LogonPW","PublishKey","HiddenKey","PublishEncryptMode","LanFolderId","StaffId"
2 | "MLBInc","4","Art Walk","","Art Walk","",',"artwalk","artwalk","art1publishkey","art1workkey","1","012345678",""
3 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/CSVWriterExceptionThrower.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import java.io.IOException;
4 | import java.io.Writer;
5 |
6 | public class CSVWriterExceptionThrower extends CSVWriter {
7 | public CSVWriterExceptionThrower(Writer writer) {
8 | super(writer);
9 | }
10 |
11 | @Override
12 | public void flush() throws IOException {
13 | throw new IOException("Exception thrown from Mock test flush method");
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcase51.csv:
--------------------------------------------------------------------------------
1 | test string;true;false;1;;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;Dec 13, 2018;13. Dez 2018;19780115T063209;19780115T063209
--------------------------------------------------------------------------------
/src/test/resources/testinputcase55.csv:
--------------------------------------------------------------------------------
1 | test string;true;false;mismatchedtype;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;Dec 13, 2018;13. Dez 2018;19780115T063209;19780115T063209
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/SimpleAnnotatedMockBeanPrivateFields.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | import com.opencsv.bean.CsvBind;
4 |
5 | public class SimpleAnnotatedMockBeanPrivateFields {
6 | @CsvBind
7 | private String privateField1;
8 | @CsvBind
9 | private String privateField2;
10 |
11 | public String getPrivateField1() {
12 | return privateField1;
13 | }
14 |
15 | public String getPrivateField2() {
16 | return privateField2;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcase60.csv:
--------------------------------------------------------------------------------
1 | long test string;wahr;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;falsch;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.badtype.string3
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/enums/CSVReaderNullFieldIndicator.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.enums;
2 |
3 | /**
4 | * Enumeration used to tell the CSVParser what to consider null.
5 | *
6 | * - EMPTY_SEPARATORS - two sequential separators are null.
7 | * - EMPTY_QUOTES - two sequential quotes are null
8 | * - BOTH - both are null
9 | * - NEITHER - default. Both are considered empty string.
10 | *
11 | */
12 | public enum CSVReaderNullFieldIndicator {
13 | EMPTY_SEPARATORS,
14 | EMPTY_QUOTES,
15 | BOTH,
16 | NEITHER;
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/SimpleAnnotatedMockBean.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | import com.opencsv.bean.CsvBind;
4 |
5 | public class SimpleAnnotatedMockBean {
6 | @CsvBind
7 | private String name;
8 | @CsvBind
9 | private String orderNumber;
10 | @CsvBind(required = true)
11 | private int num;
12 |
13 | public String getName() {
14 | return name;
15 | }
16 |
17 | public String getOrderNumber() {
18 | return orderNumber;
19 | }
20 |
21 | public int getNum() {
22 | return num;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/TestUtilitiesTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | public class TestUtilitiesTest {
8 |
9 | @Test
10 | public void displayStringArray() {
11 | String[] stringArray = new String[3];
12 |
13 | stringArray[0] = "a";
14 | stringArray[1] = "b";
15 | stringArray[2] = "c";
16 |
17 | assertEquals("Header\nNumber of elements:\t3\nelement 0:\ta\nelement 1:\tb\nelement 2:\tc\n",
18 | TestUtilities.displayStringArray("Header", stringArray));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/issue2153020/Sample.csv:
--------------------------------------------------------------------------------
1 | Presentation Catalog,Presentation Table,Presentation Column,Business Model,Derived logical table,Derived logical column,Expression,Logical Table,Logical Column,Logical Table Source,Expression,Initialization Block,Variable,Database,Physical Catalog,Physical Schema,Physical Table,Alias,Physical Column
2 | Accounts Payable Quickstart,Accounts Payable Measures,Transaction Number,NF DWH Quickstart,,,,CAP Accounts Payable Overview,Transaction Number,CAP_ACCNTS_PAYABLE_OVERVIEW,QSDB."".QS_DWH.CAP_ACCNTS_PAYABLE_OVERVIEW.TRANSACTION_NUMBER,,,QSDB,,QS_DWH,CAP_ACCNTS_PAYABLE_OVERVIEW,,TRANSACTION_NUMBER
3 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/Bug133Bean.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | public class Bug133Bean {
4 | private String one;
5 |
6 | private Integer two;
7 |
8 | private String three;
9 |
10 | public Bug133Bean() {
11 | }
12 |
13 | public String getOne() {
14 | return one;
15 | }
16 |
17 | public void setOne(String one) {
18 | this.one = one;
19 | }
20 |
21 | public Integer getTwo() {
22 | return two;
23 | }
24 |
25 | public void setTwo(Integer two) {
26 | this.two = two;
27 | }
28 |
29 | public String getThree() {
30 | return three;
31 | }
32 |
33 | public void setThree(String three) {
34 | this.three = three;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/enums/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Enumerations relevant to opencsv's internal operations.
3 | */
4 | package com.opencsv.enums;
5 | /*
6 | * Copyright 2016 Andrew Rucker Jones.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | */
20 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/SimpleAnnotatedMockBeanAllModifierTypes.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | import com.opencsv.bean.CsvBind;
4 |
5 | public class SimpleAnnotatedMockBeanAllModifierTypes {
6 | @CsvBind
7 | public String publicField;
8 | @CsvBind
9 | private String privateField;
10 | @CsvBind
11 | protected String protectedField;
12 | @CsvBind
13 | String packagePrivateField;
14 |
15 | public String getPublicField() {
16 | return publicField;
17 | }
18 |
19 | public String getPrivateField() {
20 | return privateField;
21 | }
22 |
23 | public String getProtectedField() {
24 | return protectedField;
25 | }
26 |
27 | public String getPackagePrivateField() {
28 | return packagePrivateField;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/stream/reader/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Collection of classes for customizing reading lines.
3 | */
4 | package com.opencsv.stream.reader;
5 | /*
6 | * Copyright 2016 Andrew Rucker Jones.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | */
20 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This package contains all of the exceptions specific to opencsv.
3 | */
4 | package com.opencsv.exceptions;
5 | /*
6 | * Copyright 2016 Andrew Rucker Jones.
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | */
20 |
--------------------------------------------------------------------------------
/checkstyle-suppressions.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcase78.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16;float5
2 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01
--------------------------------------------------------------------------------
/src/test/resources/testinputcase7.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16
2 | test string;true;false;1;;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;Dec 13, 2018;13. Dez 2018;19780115T063209;19780115T063209
--------------------------------------------------------------------------------
/src/test/resources/testinputcase81.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16;float5
2 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;unparsable;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01
3 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcase82.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16;float5
2 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;unparsable;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01
3 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcase83.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16;float5
2 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;unparsable;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01
3 |
--------------------------------------------------------------------------------
/src/test/groovy/com/opencsv/CSVParserBuilderSpec.groovy:
--------------------------------------------------------------------------------
1 | package com.opencsv
2 |
3 | import spock.lang.Specification
4 |
5 | class CSVParserBuilderSpec extends Specification {
6 | def 'builder creates a CSVParser by default'() {
7 | given:
8 | CSVParserBuilder builder = new CSVParserBuilder()
9 |
10 | when:
11 | ICSVParser parser = builder.build()
12 |
13 | then:
14 | parser instanceof CSVParser
15 | }
16 |
17 |
18 | def 'default RFC4180Parser has proper values'() {
19 | given:
20 | CSVParserBuilder builder = new CSVParserBuilder()
21 |
22 | when:
23 | CSVParser parser = builder.build()
24 |
25 | then:
26 | parser.getQuotechar() == ICSVParser.DEFAULT_QUOTE_CHARACTER;
27 | parser.getSeparator() == ICSVParser.DEFAULT_SEPARATOR;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/issue2153020/DataReader.java:
--------------------------------------------------------------------------------
1 | package integrationTest.issue2153020;
2 |
3 | import com.opencsv.CSVReader;
4 |
5 | import java.io.FileReader;
6 | import java.io.IOException;
7 |
8 | public class DataReader {
9 | private static final String ADDRESS_FILE = "test/integrationTest/issue2153020/Sample.csv";
10 |
11 | public static void main(String[] args) throws IOException {
12 |
13 | CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
14 | String[] nextLine;
15 | while ((nextLine = reader.readNext()) != null) {
16 | int numLines = nextLine.length;
17 | System.out.println("Number of Data Items: " + numLines);
18 | for (int i = 0; i < numLines; i++) {
19 | System.out.println(" nextLine[" + i + "]: " + nextLine[i]);
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcase11.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16
2 | test string;true;false;mismatchedtype;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;Dec 13, 2018;13. Dez 2018;19780115T063209;19780115T063209
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/SimplePartiallyAnnotatedMockBean.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | import com.opencsv.bean.CsvBind;
4 |
5 | public class SimplePartiallyAnnotatedMockBean {
6 | @CsvBind
7 | private String name;
8 | private String orderNumber;
9 | @CsvBind
10 | private int num;
11 |
12 | public String getName() {
13 | return name;
14 | }
15 |
16 | public String getOrderNumber() {
17 | return orderNumber;
18 | }
19 |
20 | public int getNum() {
21 | return num;
22 | }
23 |
24 | public void setName(String name) {
25 | this.name = name;
26 | }
27 |
28 | public void setOrderNumber(String orderNumber) {
29 | this.orderNumber = orderNumber;
30 | }
31 |
32 | public void setNum(int num) {
33 | this.num = num;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/CsvBind.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | /**
9 | * Annotation for fields to mark if they are required or not.
10 | *
11 | * @deprecated This annotation was replaced in version 3.8 by the more flexible
12 | * {@link com.opencsv.bean.CsvBindByName}, {@link com.opencsv.bean.CsvBindByPosition},
13 | * {@link com.opencsv.bean.CsvCustomBindByName}, and {@link com.opencsv.bean.CsvCustomBindByPosition}.
14 | */
15 | @Deprecated
16 | @Retention(RetentionPolicy.RUNTIME)
17 | @Target(ElementType.FIELD)
18 | public @interface CsvBind {
19 | /**
20 | * @return If the field is required to contain information.
21 | */
22 | boolean required() default false;
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * A bean binding interface for use with opencsv.
3 | *
4 | * @see opencsv.sourceforge.net
5 | */
6 | package com.opencsv.bean;
7 | /*
8 | * Copyright 2016 Andrew Rucker Jones.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License");
11 | * you may not use this file except in compliance with the License.
12 | * You may obtain a copy of the License at
13 | *
14 | * http://www.apache.org/licenses/LICENSE-2.0
15 | *
16 | * Unless required by applicable law or agreed to in writing, software
17 | * distributed under the License is distributed on an "AS IS" BASIS,
18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 | * See the License for the specific language governing permissions and
20 | * limitations under the License.
21 | */
22 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * A very simple CSV parser for Java released under a commercial-friendly license.
3 | *
4 | * @see opencsv.sourceforge.net
5 | */
6 | package com.opencsv;
7 | /*
8 | * Copyright 2016 Andrew Rucker Jones.
9 | *
10 | * Licensed under the Apache License, Version 2.0 (the "License");
11 | * you may not use this file except in compliance with the License.
12 | * You may obtain a copy of the License at
13 | *
14 | * http://www.apache.org/licenses/LICENSE-2.0
15 | *
16 | * Unless required by applicable law or agreed to in writing, software
17 | * distributed under the License is distributed on an "AS IS" BASIS,
18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 | * See the License for the specific language governing permissions and
20 | * limitations under the License.
21 | */
22 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcase40.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;bool2;bool3;string2;complex1;complex2;complex3
2 | long test string;;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;falsch;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.derived.string3
--------------------------------------------------------------------------------
/src/test/resources/testinputcase16.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;bool2;bool3;string2;complex1;complex2;complex3
2 | long test string;wahr;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;falsch;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.badtype.string3
--------------------------------------------------------------------------------
/src/test/resources/testinputcase38.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;bool2;bool3;string2;complex1;complex2;complex3
2 | long test string;wahr;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;invalidstring;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.derived.string3
--------------------------------------------------------------------------------
/src/test/resources/testinputcase41.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;bool2;bool3;string2;complex1;complex2;complex3
2 | long test string;invaliddatum;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;falsch;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.derived.string3
--------------------------------------------------------------------------------
/src/test/resources/testinputwriteposfullgood.csv:
--------------------------------------------------------------------------------
1 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.1;1.000,2;2000.3;3000,4;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01
2 | test string;;;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.1;1.000,2;2000.3;3000,4;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T163209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;2.02
3 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/TestUtilities.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | public class TestUtilities {
4 | public static String displayStringArray(String header, String[] stringArray) {
5 | StringBuffer sb = new StringBuffer();
6 | sb.append(header);
7 | appendNewLine(sb);
8 | sb.append("Number of elements:");
9 | appendTab(sb);
10 | sb.append(stringArray.length);
11 | appendNewLine(sb);
12 |
13 | for (int i = 0; i < stringArray.length; i++) {
14 | sb.append("element ");
15 | sb.append(i);
16 | sb.append(':');
17 | appendTab(sb);
18 | sb.append(stringArray[i]);
19 | appendNewLine(sb);
20 | }
21 | return sb.toString();
22 | }
23 |
24 | private static void appendTab(StringBuffer sb) {
25 | sb.append('\t');
26 | }
27 |
28 | private static void appendNewLine(StringBuffer sb) {
29 | sb.append('\n');
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/resources/testinputposfullgood.csv:
--------------------------------------------------------------------------------
1 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01
2 | test string;;;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T163209;;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;2.02
3 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/GetterMissing.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByName;
19 |
20 | /**
21 | * For test case 19 (writing).
22 | * @author Andrew Rucker Jones
23 | */
24 | public class GetterMissing {
25 | @CsvBindByName
26 | private int test = 123;
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/customconverter/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Custom converters that are generally useful are collected here.
3 | * Anyone can write any custom converter they wish to, of course, but if a
4 | * custom converter seems that it would be of widespread use, it should be
5 | * provided here.
6 | */
7 | package com.opencsv.bean.customconverter;
8 | /*
9 | * Copyright 2016 Andrew Rucker Jones.
10 | *
11 | * Licensed under the Apache License, Version 2.0 (the "License");
12 | * you may not use this file except in compliance with the License.
13 | * You may obtain a copy of the License at
14 | *
15 | * http://www.apache.org/licenses/LICENSE-2.0
16 | *
17 | * Unless required by applicable law or agreed to in writing, software
18 | * distributed under the License is distributed on an "AS IS" BASIS,
19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 | * See the License for the specific language governing permissions and
21 | * limitations under the License.
22 | */
23 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/ComplexDerivedClassForCustomAnnotation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | /**
19 | * This is to test assignability to a variable of a base class.
20 | *
21 | * @author Andrew Rucker Jones
22 | */
23 | public class ComplexDerivedClassForCustomAnnotation extends ComplexClassForCustomAnnotation {
24 | public float f;
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/GetterPrivate.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByName;
19 |
20 | /**
21 | * For test case 20 (writing).
22 | * @author Andrew Rucker Jones
23 | */
24 | public class GetterPrivate {
25 | @CsvBindByName
26 | private int test = 123;
27 | private int getTest() {return test;}
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/TestCase34.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByName;
19 | import com.opencsv.bean.CsvDate;
20 |
21 | /**
22 | * Class for annotation test case 34.
23 | *
24 | * @author Andrew Rucker Jones
25 | */
26 | public class TestCase34 {
27 | @CsvBindByName
28 | @CsvDate
29 | String isnotdate;
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/resources/testinputwritecustomposfullgood.csv:
--------------------------------------------------------------------------------
1 | long test string;wahr;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;falsch;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.derived.string3
2 | long test string;ja;nein;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;nein;ja;really;4.d.long,long.string4;5.e.long,long.derived.string5;6.f.long,long.string6
3 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/CsvRuntimeException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.exceptions;
17 |
18 | /**
19 | * The base class for all unchecked exceptions in opencsv.
20 | * @author Andrew Rucker Jones
21 | */
22 | public class CsvRuntimeException extends RuntimeException {
23 |
24 | /** Nullary constructor. Does nothing. */
25 | public CsvRuntimeException() {}
26 |
27 | /**
28 | * Constructor with a message.
29 | * @param message A human-readable error message
30 | */
31 | public CsvRuntimeException(String message) {super(message);}
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/customconverter/BadIntConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.customconverter;
17 |
18 | import com.opencsv.bean.AbstractBeanField;
19 |
20 | /**
21 | * The sole purpose of this converter is to throw an exception on instantiation.
22 | * @author Andrew Rucker Jones
23 | */
24 | public class BadIntConverter extends AbstractBeanField {
25 |
26 | private BadIntConverter() {
27 | // Throws an exception because access is private
28 | }
29 |
30 | @Override
31 | public Object convert(String value) {
32 | return null;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/TestCase80.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvCustomBindByName;
19 | import com.opencsv.bean.CsvCustomBindByPosition;
20 | import com.opencsv.bean.customconverter.BadIntConverter;
21 |
22 | /**
23 | * Tests what happens when a bad converter is passed in.
24 | * @author Andrew Rucker Jones
25 | */
26 | public class TestCase80 {
27 | @CsvCustomBindByName(converter = BadIntConverter.class, column = "test")
28 | @CsvCustomBindByPosition(converter = BadIntConverter.class, position = 1)
29 | public int test;
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/isClosed/isClosedTest.java:
--------------------------------------------------------------------------------
1 | package integrationTest.isClosed;
2 |
3 | import com.opencsv.CSVReader;
4 | import org.junit.Test;
5 |
6 | import java.io.IOException;
7 | import java.io.Reader;
8 | import java.io.StringReader;
9 | import java.util.List;
10 |
11 | import static org.junit.Assert.assertEquals;
12 |
13 | /**
14 | * I created this class to test out all the issues that is being seen with the isClosed
15 | * that was introduced in the CSVReader for version 3.
16 | * Created by scott on 7/28/15.
17 | */
18 | public class isClosedTest {
19 |
20 | private static final String ONE_ROW = "col\tcol\tcol\tcol\tcol\tcol\tcol\r\n"; // 10byte
21 | private static final int ROWS = 10001;
22 |
23 | @Test
24 | public void issue115StandardReadFailsAfterALargeNumberOfReads() throws IOException {
25 | StringBuilder all = new StringBuilder();
26 | for (int i = 0; i < ROWS; i++) {
27 | all.append(ONE_ROW);
28 | }
29 |
30 | Reader reader = new StringReader(all.toString());
31 | CSVReader csvr = new CSVReader(reader, '\t');
32 | List rows = csvr.readAll();
33 | csvr.close();
34 |
35 | assertEquals(ROWS, rows.size());
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/BindCustomToWrongDataType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvCustomBindByName;
19 | import com.opencsv.bean.customconverter.ConvertGermanToBoolean;
20 |
21 | /**
22 | * For test case 29 (writing).
23 | * @author Andrew Rucker Jones
24 | */
25 | public class BindCustomToWrongDataType {
26 | @CsvCustomBindByName(converter=ConvertGermanToBoolean.class)
27 | private String wrongType;
28 | public void setWrongType(String wrongType) {this.wrongType = wrongType;}
29 | public String getWrongType() {return wrongType;}
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/issue2564366/DataReader.java:
--------------------------------------------------------------------------------
1 | package integrationTest.issue2564366;
2 |
3 | import com.opencsv.CSVReader;
4 |
5 | import java.io.FileReader;
6 | import java.io.IOException;
7 |
8 | public class DataReader {
9 | private static final String ADDRESS_FILE = "test/integrationTest/issue2564366/data.csv";
10 |
11 | public static void main(String[] args) throws IOException {
12 |
13 | CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
14 | String[] nextLine;
15 | while ((nextLine = reader.readNext()) != null) {
16 | System.out.println("CompanyName: [" + nextLine[0] + "]\nCompanyNumber: [" + nextLine[1] + "]\nClientName: [" + nextLine[2] + "]");
17 | System.out.println("ClientFirstName: [" + nextLine[3] + "]\nClientLastName: [" + nextLine[4] + "]\nClientId: [" + nextLine[5] + "]");
18 | System.out.println("ClientGroupId: [" + nextLine[6] + "]\nLogon: [" + nextLine[7] + "]\nLogonPW: [" + nextLine[8] + "]");
19 | System.out.println("PublishKey: [" + nextLine[9] + "]\nHiddenKey: [" + nextLine[10] + "]\nPublishEncryptMode: [" + nextLine[11] + "]");
20 | System.out.println("LanFolderId: [" + nextLine[12] + "]\nStaffId: [" + nextLine[13] + "]\n");
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/resources/testinputfullgood.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16;float5
2 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01
3 | +test string;;;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T163209;;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;2.02
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/ComplexClassForCustomAnnotation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | /**
19 | * The members of this class are not annotated, but the entire class is
20 | * intended to be annotated in a containing class.
21 | *
22 | * @author Andrew Rucker Jones
23 | */
24 | public class ComplexClassForCustomAnnotation {
25 | public int i;
26 | public char c;
27 | public String s;
28 |
29 | public int getI() {return i;} public void setI(int i) {this.i = i;}
30 | public char getC() {return c;} public void setC(char c) {this.c = c;}
31 | public String getS() {return s;} public void setS(String s) {this.s = s;}
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/resources/testinputderivedgood.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;date13;date14;date15;date16;float5;int in subclass
2 | test string;true;false;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;1.01;7
3 | +test string;;;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T163209;;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;01/15/1978;13. Dez 2018;19780115T063209;19780115T063209;2.02;8
--------------------------------------------------------------------------------
/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/AnnotatedMockBean.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | import com.opencsv.bean.CsvBind;
4 |
5 | public class AnnotatedMockBean {
6 | @CsvBind
7 | private long familyId;
8 | @CsvBind
9 | private String familyName;
10 | @CsvBind
11 | private byte familySize;
12 | @CsvBind
13 | private double averageAge;
14 | @CsvBind
15 | private float averageIncome;
16 | @CsvBind
17 | private int numberOfPets;
18 | @CsvBind
19 | private short numberOfBedrooms;
20 | @CsvBind
21 | private char zipcodePrefix;
22 | @CsvBind
23 | private boolean hasBeenContacted;
24 |
25 | public long getFamilyId() {
26 | return familyId;
27 | }
28 |
29 | public String getFamilyName() {
30 | return familyName;
31 | }
32 |
33 | public byte getFamilySize() {
34 | return familySize;
35 | }
36 |
37 | public double getAverageAge() {
38 | return averageAge;
39 | }
40 |
41 | public float getAverageIncome() {
42 | return averageIncome;
43 | }
44 |
45 | public int getNumberOfPets() {
46 | return numberOfPets;
47 | }
48 |
49 | public short getNumberOfBedrooms() {
50 | return numberOfBedrooms;
51 | }
52 |
53 | public char getZipcodePrefix() {
54 | return zipcodePrefix;
55 | }
56 |
57 | public boolean isHasBeenContacted() {
58 | return hasBeenContacted;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/MinimalCsvBindBeanForWriting.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBind;
19 |
20 | /**
21 | *
22 | * @author Andrew Rucker Jones
23 | */
24 | public class MinimalCsvBindBeanForWriting {
25 |
26 | @CsvBind
27 | private int b;
28 |
29 | @CsvBind
30 | private int c;
31 |
32 | @CsvBind
33 | private int a;
34 |
35 | public int getB() {
36 | return b;
37 | }
38 |
39 | public void setB(int b) {
40 | this.b = b;
41 | }
42 |
43 | public int getC() {
44 | return c;
45 | }
46 |
47 | public void setC(int c) {
48 | this.c = c;
49 | }
50 |
51 | public int getA() {
52 | return a;
53 | }
54 |
55 | public void setA(int a) {
56 | this.a = a;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/pmd-ruleset.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | This ruleset checks code for violations
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | 2
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/TestCases21And63.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByName;
19 | import com.opencsv.bean.CsvBindByPosition;
20 |
21 | import java.util.List;
22 |
23 | /**
24 | * For annotation test cases 21 and 63.
25 | * Would love to do this an an inner class, but that won't work without
26 | * further refactoring. An inner class does not have a nullary constructor,
27 | * and can't be made to have one. A good, brief explanation can be found at
28 | *
29 | * The Coder's Breakfast.
30 | *
31 | * @author Andrew Rucker Jones
32 | */
33 | public class TestCases21And63 {
34 | @CsvBindByName
35 | @CsvBindByPosition(position = 0)
36 | public List list;
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/MockResultSetMetaDataBuilder.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import java.sql.ResultSetMetaData;
4 | import java.sql.SQLException;
5 | import java.sql.Types;
6 |
7 | import static org.mockito.Mockito.mock;
8 | import static org.mockito.Mockito.when;
9 |
10 | public class MockResultSetMetaDataBuilder {
11 |
12 | public static ResultSetMetaData buildMetaData(String[] columnNames) throws SQLException {
13 |
14 | ResultSetMetaData metaData = mock(ResultSetMetaData.class);
15 |
16 | when(metaData.getColumnCount()).thenReturn(columnNames.length);
17 | for (int i = 0; i < columnNames.length; i++) {
18 | when(metaData.getColumnName(i + 1)).thenReturn(columnNames[i]);
19 | when(metaData.getColumnLabel(i + 1)).thenReturn(columnNames[i]);
20 | when(metaData.getColumnType(i + 1)).thenReturn(Types.VARCHAR);
21 | }
22 |
23 | return metaData;
24 | }
25 |
26 | public static ResultSetMetaData buildMetaData(String[] columnNames, int[] columnTypes) throws SQLException {
27 |
28 | ResultSetMetaData metaData = mock(ResultSetMetaData.class);
29 |
30 | when(metaData.getColumnCount()).thenReturn(columnNames.length);
31 | for (int i = 0; i < columnNames.length; i++) {
32 | when(metaData.getColumnName(i + 1)).thenReturn(columnNames[i]);
33 | when(metaData.getColumnLabel(i + 1)).thenReturn(columnNames[i]);
34 | when(metaData.getColumnType(i + 1)).thenReturn(columnTypes[i]);
35 | }
36 |
37 | return metaData;
38 | }
39 | }
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/MinimalCsvBindByNameBeanForWriting.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByName;
19 |
20 | /**
21 | *
22 | * @author Andrew Rucker Jones
23 | */
24 | public class MinimalCsvBindByNameBeanForWriting {
25 |
26 | @CsvBindByName(column = "findb")
27 | private int b;
28 |
29 | @CsvBindByName
30 | private int c;
31 |
32 | @CsvBindByName(column = "finda")
33 | private int a;
34 |
35 | public int getB() {
36 | return b;
37 | }
38 |
39 | public void setB(int b) {
40 | this.b = b;
41 | }
42 |
43 | public int getC() {
44 | return c;
45 | }
46 |
47 | public void setC(int c) {
48 | this.c = c;
49 | }
50 |
51 | public int getA() {
52 | return a;
53 | }
54 |
55 | public void setA(int a) {
56 | this.a = a;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/BindByNameUnknownTypeLegacy.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBind;
19 |
20 | /**
21 | * For test case 23 (writing).
22 | * @author Andrew Rucker Jones
23 | */
24 | public class BindByNameUnknownTypeLegacy {
25 | public static final String TOSTRING = "This is just a test of unknown datatypes.";
26 |
27 | @CsvBind
28 | private final BindByNameUnknownTypeInnerClass test =
29 | new BindByNameUnknownTypeInnerClass(TOSTRING);
30 | public BindByNameUnknownTypeInnerClass getTest() {return test;}
31 |
32 | private class BindByNameUnknownTypeInnerClass {
33 | private final String s;
34 | public BindByNameUnknownTypeInnerClass(String s) {
35 | this.s = s;
36 | }
37 |
38 | @Override
39 | public String toString() {
40 | return s;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/MinimalCsvBindByPositionBeanForWriting.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByPosition;
19 |
20 | /**
21 | *
22 | * @author Andrew Rucker Jones
23 | */
24 | public class MinimalCsvBindByPositionBeanForWriting {
25 |
26 | @CsvBindByPosition(position = 1)
27 | private int b;
28 |
29 | @CsvBindByPosition(position = 2)
30 | private int c;
31 |
32 | @CsvBindByPosition(position = 3)
33 | private int a;
34 |
35 | public int getB() {
36 | return b;
37 | }
38 |
39 | public void setB(int b) {
40 | this.b = b;
41 | }
42 |
43 | public int getC() {
44 | return c;
45 | }
46 |
47 | public void setC(int c) {
48 | this.c = c;
49 | }
50 |
51 | public int getA() {
52 | return a;
53 | }
54 |
55 | public void setA(int a) {
56 | this.a = a;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/CSVIteratorTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | import java.io.IOException;
7 | import java.util.NoSuchElementException;
8 |
9 | import static org.junit.Assert.*;
10 | import static org.mockito.Mockito.mock;
11 | import static org.mockito.Mockito.when;
12 |
13 | public class CSVIteratorTest {
14 | private static final String[] STRINGS = {"test1", "test2"};
15 | private CSVIterator iterator;
16 | private CSVReader mockReader;
17 |
18 | @Before
19 | public void setUp() throws IOException {
20 | mockReader = mock(CSVReader.class);
21 | when(mockReader.readNext()).thenReturn(STRINGS);
22 | iterator = new CSVIterator(mockReader);
23 | }
24 |
25 | @Test(expected = NoSuchElementException.class)
26 | public void readerExceptionCausesRunTimeException() throws IOException {
27 | when(mockReader.readNext()).thenThrow(new IOException("reader threw test exception"));
28 | iterator.next();
29 | }
30 |
31 | @Test(expected = UnsupportedOperationException.class)
32 | public void removethrowsUnsupportedOperationException() {
33 | iterator.remove();
34 | }
35 |
36 | @Test
37 | public void initialReadReturnsStrings() {
38 | assertArrayEquals(STRINGS, iterator.next());
39 | }
40 |
41 | @Test
42 | public void hasNextWorks() throws IOException {
43 | when(mockReader.readNext()).thenReturn(null);
44 | assertTrue(iterator.hasNext()); // initial read from constructor
45 | iterator.next();
46 | assertFalse(iterator.hasNext());
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/AnnotatedMockBeanFullDerived.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByName;
19 |
20 | /**
21 | * A derived class with one additional field to test mapping with inheritance.
22 | * @author Andrew Rucker Jones
23 | */
24 | public class AnnotatedMockBeanFullDerived extends AnnotatedMockBeanFull {
25 |
26 | /**
27 | * Field for annotation tests.
28 | * Used for the following test cases, reading:
31 | * Used for the following test cases, writing:
32 | * - 33
33 | * - 34
34 | *
35 | */
36 | @CsvBindByName(required = true, column = "int in subclass")
37 | private int intInSubclass;
38 |
39 | public int getIntInSubclass() {
40 | return intInSubclass;
41 | }
42 |
43 | public void setIntInSubclass(int intInSubclass) {
44 | this.intInSubclass = intInSubclass;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/BindByNameUnknownType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.CsvBindByName;
19 | import com.opencsv.bean.CsvBindByPosition;
20 |
21 | /**
22 | * For test cases 21 und 22 (writing).
23 | * @author Andrew Rucker Jones
24 | */
25 | public class BindByNameUnknownType {
26 | public static final String TOSTRING = "This is just a test of unknown datatypes.";
27 |
28 | @CsvBindByName
29 | @CsvBindByPosition(position = 0)
30 | private final BindByNameUnknownTypeInnerClass test =
31 | new BindByNameUnknownTypeInnerClass(TOSTRING);
32 | public BindByNameUnknownTypeInnerClass getTest() {return test;}
33 |
34 | private class BindByNameUnknownTypeInnerClass {
35 | private final String s;
36 | public BindByNameUnknownTypeInnerClass(String s) {
37 | this.s = s;
38 | }
39 |
40 | @Override
41 | public String toString() {
42 | return s;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/CSVIterator.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import java.io.IOException;
4 | import java.util.Iterator;
5 | import java.util.NoSuchElementException;
6 |
7 | /**
8 | * Provides an Iterator over the data found in opencsv.
9 | */
10 | public class CSVIterator implements Iterator {
11 | private final CSVReader reader;
12 | private String[] nextLine;
13 |
14 | /**
15 | * @param reader Reader for the CSV data.
16 | * @throws IOException If unable to read data from the reader.
17 | */
18 | public CSVIterator(CSVReader reader) throws IOException {
19 | this.reader = reader;
20 | nextLine = reader.readNext();
21 | }
22 |
23 | /**
24 | * Returns true if the iteration has more elements.
25 | * In other words, returns true if {@link #next()} would return an element
26 | * rather than throwing an exception.
27 | *
28 | * @return True if the CSVIterator has more elements.
29 | */
30 | @Override
31 | public boolean hasNext() {
32 | return nextLine != null;
33 | }
34 |
35 | /**
36 | *
37 | * Returns the next element in the iterator.
38 | *
39 | * @return The next element of the iterator.
40 | */
41 | @Override
42 | public String[] next() {
43 | String[] temp = nextLine;
44 | try {
45 | nextLine = reader.readNext();
46 | } catch (IOException e) {
47 | throw new NoSuchElementException();
48 | }
49 | return temp;
50 | }
51 |
52 | /**
53 | * This method is not supported by opencsv and will throw an
54 | * {@link java.lang.UnsupportedOperationException} if called.
55 | */
56 | @Override
57 | public void remove() {
58 | throw new UnsupportedOperationException("This is a read only iterator.");
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/stream/reader/LineReader.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.stream.reader;
2 |
3 | import com.opencsv.ICSVParser;
4 |
5 | import java.io.BufferedReader;
6 | import java.io.IOException;
7 |
8 | /**
9 | * This class was created for
10 | * issue #106
11 | * where carriage returns were being removed.
12 | * This class allows the user to determine if they wish to keep or
13 | * remove them from the data being read.
14 | *
15 | * @author scott
16 | * @since 2/19/15
17 | */
18 |
19 | public class LineReader {
20 | private final BufferedReader reader;
21 | private final boolean keepCarriageReturns;
22 |
23 | /**
24 | * LineReader constructor.
25 | *
26 | * @param reader Reader that data will be read from.
27 | * @param keepCarriageReturns True if carriage returns should remain in the data, false to remove them.
28 | */
29 | public LineReader(BufferedReader reader, boolean keepCarriageReturns) {
30 | this.reader = reader;
31 | this.keepCarriageReturns = keepCarriageReturns;
32 | }
33 |
34 | /**
35 | * Reads the next line from the Reader.
36 | *
37 | * @return Line read from reader.
38 | * @throws IOException On error from BufferedReader
39 | */
40 | public String readLine() throws IOException {
41 | return keepCarriageReturns ? readUntilNewline() : reader.readLine();
42 | }
43 |
44 | private String readUntilNewline() throws IOException {
45 | StringBuilder sb = new StringBuilder(ICSVParser.INITIAL_READ_SIZE);
46 | for (int c = reader.read(); c > -1 && c != '\n'; c = reader.read()) {
47 | sb.append((char) c);
48 | }
49 |
50 | return sb.length() > 0 ? sb.toString() : null;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/test/resources/testinputmaximumbuilder.csv:
--------------------------------------------------------------------------------
1 | MÜÜÜÜÜÜÜÜLL
2 | string1#bool1#boolPrimitive#byte1#byte2#byte3#byte4#double1#double2#double3#double4#float1#float2#float3#float4#integer1#integer2#integer3#integer4#long1#long2#long3#long4#short1#short2#short3#short4#char1#char2#bigdecimal1#bigdecimal2#biginteger1#biginteger2#date1#date2#date3#date4#date5#date6#date7#date8#date9#date10#date11#date12#date13#date14#date15#date16#float5
3 | filtermebaby###1#2#3#4#123,101.101#123.202,202#123303.303#123404,404#123101.101#123202,202#123303.303#123404,404#5000#6.000#7000#8000#9000#10000#11000#12000#13000#14000#15000#16000#a#b#123101.101#123102,102#101#102#19780115T063209#19780115T163209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#01/15/1978#13. Dez 2018#19780115T063209#19780115T063209#2.02
4 | !test string of everything?!!#!true!#false#1#2#3#4#123,101.101#123.202,202#123303.303#123404,404#123101.101#123202,202#123303.303#123404,404#5000#6.000#7000#8000#9000#10000#11000#12000#13000#14000#15000#16000#a#b#123101.101#123102,102#101#102#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#01/15/1978#13. Dez 2018#19780115T063209#19780115T063209#1.01
5 | should throw an exception because 1.1 is not a byte#true#false#1.1#2#3#4#123,101.101#123.202,202#123303.303#123404,404#123101.101#123202,202#123303.303#123404,404#5000#6.000#7000#8000#9000#10000#11000#12000#13000#14000#15000#16000#a#b#123101.101#123102,102#101#102#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#19780115T063209#01/15/1978#13. Dez 2018#19780115T063209#19780115T063209#1.01
6 |
--------------------------------------------------------------------------------
/examples/AddressExample.java:
--------------------------------------------------------------------------------
1 | import com.opencsv.CSVReader;
2 | import com.opencsv.CSVWriter;
3 |
4 | import java.io.FileReader;
5 | import java.io.IOException;
6 | import java.io.StringWriter;
7 | import java.util.List;
8 |
9 | /**
10 | * Copyright 2005 Bytecode Pty Ltd.
11 | *
12 | * Licensed under the Apache License, Version 2.0 (the "License");
13 | * you may not use this file except in compliance with the License.
14 | * You may obtain a copy of the License at
15 | *
16 | * http://www.apache.org/licenses/LICENSE-2.0
17 | *
18 | * Unless required by applicable law or agreed to in writing, software
19 | * distributed under the License is distributed on an "AS IS" BASIS,
20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 | * See the License for the specific language governing permissions and
22 | * limitations under the License.
23 | */
24 | public class AddressExample {
25 |
26 | private static final String ADDRESS_FILE = "examples/addresses.csv";
27 |
28 | public static void main(String[] args) throws IOException {
29 |
30 | CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
31 | String[] nextLine;
32 | while ((nextLine = reader.readNext()) != null) {
33 | System.out.println("Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
34 | }
35 |
36 | // Try writing it back out as CSV to the console
37 | CSVReader reader2 = new CSVReader(new FileReader(ADDRESS_FILE));
38 | List allElements = reader2.readAll();
39 | StringWriter sw = new StringWriter();
40 | CSVWriter writer = new CSVWriter(sw);
41 | writer.writeAll(allElements);
42 |
43 | System.out.println("\n\nGenerated CSV File:\n\n");
44 | System.out.println(sw.toString());
45 |
46 |
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/test/groovy/com/opencsv/CSVIteratorSpec.groovy:
--------------------------------------------------------------------------------
1 | package com.opencsv
2 |
3 | import spock.lang.Specification
4 |
5 | class CSVIteratorSpec extends Specification {
6 |
7 | def 'reader exception should cause runtime exception'() {
8 | given:
9 | CSVReader reader = Mock(CSVReader)
10 | CSVIterator iterator = new CSVIterator(reader)
11 |
12 | and:
13 | def exceptionMsg = 'reader threw test exception'
14 | reader.readNext() >> {
15 | throw new IOException(exceptionMsg)
16 | }
17 |
18 | when:
19 | iterator.next()
20 |
21 | then:
22 | thrown(NoSuchElementException)
23 | }
24 |
25 | def 'call to remove() results in UnsupportedOperationException thrown'() {
26 | given:
27 | CSVIterator iterator = new CSVIterator(Mock(CSVReader))
28 |
29 | when:
30 | iterator.remove()
31 |
32 | then:
33 | thrown(UnsupportedOperationException)
34 | }
35 |
36 | def 'initial read should return string array'() {
37 | given:
38 | def output = ['test1', 'test2'] as String[]
39 |
40 | CSVReader reader = Mock(CSVReader) {
41 | readNext() >> output
42 | }
43 | CSVIterator iterator = new CSVIterator(reader)
44 |
45 | when:
46 | def read = iterator.next()
47 |
48 | then:
49 | read.toList() == output.toList()
50 | }
51 |
52 | def 'call to hasNext() returns correct results'() {
53 | given:
54 | CSVReader reader = Mock(CSVReader) {
55 | readNext() >>> [['a'], null]
56 | }
57 |
58 | and:
59 | CSVIterator iterator = new CSVIterator(reader)
60 |
61 | when:
62 | def hasNext = iterator.hasNext()
63 |
64 | then:
65 | hasNext
66 |
67 | when:
68 | iterator.next()
69 | hasNext = iterator.hasNext()
70 |
71 | then:
72 | !hasNext
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/CsvCustomBindByPosition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean;
17 |
18 | import java.lang.annotation.*;
19 |
20 | /**
21 | * Allows us to specify a class that will perform the translation from source
22 | * to destination.
23 | * For special needs, we can implement a class that takes the source field from
24 | * the CSV and translates it into a form of our choice.
25 | *
26 | * @author Andrew Rucker Jones
27 | * @since 3.8
28 | */
29 | @Documented
30 | @Retention(RetentionPolicy.RUNTIME)
31 | @Target(ElementType.FIELD)
32 | public @interface CsvCustomBindByPosition {
33 |
34 | /**
35 | * The class that takes care of the conversion.
36 | * Every custom converter must be descended from
37 | * {@link com.opencsv.bean.AbstractBeanField} and override the method
38 | * {@link com.opencsv.bean.AbstractBeanField#convert(java.lang.String)}.
39 | *
40 | * @return The implementation that can convert to the type of this field.
41 | */
42 | Class extends AbstractBeanField> converter();
43 |
44 | /**
45 | * The column position in the input that is used to fill the annotated
46 | * field.
47 | *
48 | * @return The position of the column in the CSV file from which this field
49 | * should be taken. This column number is zero-based.
50 | */
51 | int position();
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/CsvCustomBindByName.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean;
17 |
18 | import java.lang.annotation.*;
19 |
20 | /**
21 | * Allows us to specify a class that will perform the translation from source
22 | * to destination.
23 | * For special needs, we can implement a class that takes the source field from
24 | * the CSV and translates it into a form of our choice. The source column name
25 | * may also be specified.
26 | *
27 | * @author Andrew Rucker Jones
28 | * @since 3.8
29 | */
30 | @Documented
31 | @Retention(RetentionPolicy.RUNTIME)
32 | @Target(ElementType.FIELD)
33 | public @interface CsvCustomBindByName {
34 |
35 | /**
36 | * The class that takes care of the conversion.
37 | * Every custom converter must be descended from
38 | * {@link com.opencsv.bean.AbstractBeanField} and override the method
39 | * {@link com.opencsv.bean.AbstractBeanField#convert(java.lang.String)}.
40 | *
41 | * @return The implementation that can convert to the type of this field.
42 | */
43 | Class extends AbstractBeanField> converter();
44 |
45 | /**
46 | * If not specified, the name of the column must be identical to the name
47 | * of the field.
48 | *
49 | * @return The name of the column in the CSV file from which this field
50 | * should be taken.
51 | */
52 | String column() default "";
53 | }
54 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/CsvToBeanDoubleTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | import com.opencsv.CSVReader;
4 | import com.opencsv.bean.mocks.MockBean;
5 | import org.junit.Test;
6 |
7 | import java.io.StringReader;
8 | import java.util.List;
9 |
10 | import static org.junit.Assert.assertEquals;
11 | import static org.junit.Assert.assertTrue;
12 |
13 | /**
14 | * This test was created based on an question posted on stack overflow
15 | * on how to handle formatted doubles.
16 | * Created by scott on 11/15/15.
17 | */
18 | public class CsvToBeanDoubleTest {
19 |
20 | private static final double DOUBLE_NUMBER = 10023000000000d;
21 |
22 | private static final String TEST_STRING = "name,orderNumber,doubleNum\n" +
23 | "kyle,abc123456,10023000000000\n" +
24 | "jimmy,def098765,1.0023E+13 ";
25 |
26 | private CSVReader createReader() {
27 | return createReader(TEST_STRING);
28 | }
29 |
30 | private CSVReader createReader(String testString) {
31 | StringReader reader = new StringReader(testString);
32 | return new CSVReader(reader);
33 | }
34 |
35 | private MockBean createMockBean(String name, String orderNumber, double num) {
36 | MockBean mockBean = new MockBean();
37 | mockBean.setName(name);
38 | mockBean.setOrderNumber(orderNumber);
39 | mockBean.setDoubleNum(num);
40 | return mockBean;
41 | }
42 |
43 | @Test
44 | public void parseBeanWithNoAnnotations() {
45 | HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy();
46 | strategy.setType(MockBean.class);
47 | CsvToBean bean = new CsvToBean();
48 |
49 | List beanList = bean.parse(strategy, createReader());
50 | assertEquals(2, beanList.size());
51 | assertTrue(beanList.contains(createMockBean("kyle", "abc123456", DOUBLE_NUMBER)));
52 | assertTrue(beanList.contains(createMockBean("jimmy", "def098765", DOUBLE_NUMBER)));
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/CsvException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.exceptions;
17 |
18 | /**
19 | * This is the base class for all exceptions for opencsv.
20 | *
21 | * @author Andrew Rucker Jones
22 | * @since 3.8
23 | */
24 | public class CsvException extends Exception {
25 |
26 | private long lineNumber;
27 |
28 | /**
29 | * Default constructor, in case no parameters are required.
30 | */
31 | public CsvException() {
32 | lineNumber = -1;
33 | }
34 |
35 | /**
36 | * Constructor that allows a human-readable message.
37 | *
38 | * @param message The error text
39 | */
40 | public CsvException(String message) {
41 | super(message);
42 | lineNumber = -1;
43 | }
44 |
45 | /**
46 | * @return The line number that caused the error. This should be the
47 | * one-based number of the line that caused the error, not including the
48 | * header line, if present.
49 | */
50 | public long getLineNumber() {
51 | return lineNumber;
52 | }
53 |
54 | /**
55 | * @param lineNumber The line number that caused the error. This should be the
56 | * one-based number of the line that caused the error, not including the
57 | * header line, if present.
58 | */
59 | public void setLineNumber(long lineNumber) {
60 | this.lineNumber = lineNumber;
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/issue3402853/HeaderColumnNameMappingStrategyUserTest.java:
--------------------------------------------------------------------------------
1 | package integrationTest.issue3402853;
2 |
3 | /*
4 | Copyright 2007 Kyle Miller.
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | */
18 |
19 | import com.opencsv.CSVReader;
20 | import com.opencsv.bean.CsvToBean;
21 | import com.opencsv.bean.HeaderColumnNameMappingStrategy;
22 | import org.junit.Test;
23 |
24 | import java.io.FileNotFoundException;
25 | import java.io.FileReader;
26 | import java.util.List;
27 |
28 | import static org.junit.Assert.assertEquals;
29 | import static org.junit.Assert.assertNotNull;
30 |
31 | public class HeaderColumnNameMappingStrategyUserTest {
32 |
33 | private static final String USER_FILE = "src/test/java/integrationTest/issue3402853/user.csv";
34 |
35 | private List createTestParseResult() throws FileNotFoundException {
36 | CSVReader reader = new CSVReader(new FileReader(USER_FILE));
37 | HeaderColumnNameMappingStrategy strat = new HeaderColumnNameMappingStrategy();
38 | strat.setType(MockUserBean.class);
39 | CsvToBean csv = new CsvToBean();
40 | return csv.parse(strat, reader);
41 | }
42 |
43 | @Test
44 | public void testParse() throws FileNotFoundException {
45 | List list = createTestParseResult();
46 | assertNotNull(list);
47 | assertEquals(2, list.size());
48 | MockUserBean bean = list.get(0);
49 | assertEquals("rbst218@yahoo.com", bean.getEmail());
50 | assertEquals("\\\"CHia Sia Ta", bean.getFirst_Name());
51 | assertEquals("", bean.getLast_Name());
52 | assertEquals("bc1er1163", bean.getProfile_Id());
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/OpencsvTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 | /*
3 | Copyright 2005 Bytecode Pty Ltd.
4 |
5 | Licensed under the Apache License, Version 2.0 (the "License");
6 | you may not use this file except in compliance with the License.
7 | You may obtain a copy of the License at
8 |
9 | http://www.apache.org/licenses/LICENSE-2.0
10 |
11 | Unless required by applicable law or agreed to in writing, software
12 | distributed under the License is distributed on an "AS IS" BASIS,
13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | See the License for the specific language governing permissions and
15 | limitations under the License.
16 | */
17 |
18 | import org.junit.Before;
19 | import org.junit.Test;
20 |
21 | import java.io.File;
22 | import java.io.FileReader;
23 | import java.io.FileWriter;
24 | import java.io.IOException;
25 |
26 | import static org.junit.Assert.assertTrue;
27 |
28 | public class OpencsvTest {
29 |
30 | private File tempFile = null;
31 |
32 | @Before
33 | public void setUp() throws IOException {
34 | tempFile = File.createTempFile("csvWriterTest", ".csv");
35 | tempFile.deleteOnExit();
36 | }
37 |
38 | /**
39 | * Test the full cycle of write-read
40 | * @throws IOException But not really
41 | */
42 | @Test
43 | public void testWriteRead() throws IOException {
44 | final String[][] data = new String[][]{{"hello, a test", "one nested \" test"}, {"\"\"", "test", null, "8"}};
45 |
46 | CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
47 | for (String[] aData : data) {
48 | writer.writeNext(aData);
49 | }
50 | writer.close();
51 |
52 | CSVReader reader = new CSVReader(new FileReader(tempFile));
53 |
54 | String[] line;
55 | for (int row = 0; (line = reader.readNext()) != null; row++) {
56 | assertTrue(line.length == data[row].length);
57 |
58 | for (int col = 0; col < line.length; col++) {
59 | if (data[row][col] == null) {
60 | assertTrue(line[col].equals(""));
61 | } else {
62 | assertTrue(line[col].equals(data[row][col]));
63 | }
64 | }
65 | }
66 | reader.close();
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/CsvDate.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean;
17 |
18 | import java.lang.annotation.*;
19 |
20 | /**
21 | * This annotation indicates that the destination field is an expression of time.
22 | * Conversion to the following types is supported:
23 | * - {@link java.util.Date}
24 | * - {@link java.util.Calendar} (a {@link java.util.GregorianCalendar} is returned)
25 | * - {@link java.util.GregorianCalendar}
26 | * - {@link javax.xml.datatype.XMLGregorianCalendar}
27 | * - {@link java.sql.Date}
28 | * - {@link java.sql.Time}
29 | * - {@link java.sql.Timestamp}
30 | *
31 | * This annotation must be used with either {@link com.opencsv.bean.CsvBindByName}
32 | * or {@link com.opencsv.bean.CsvBindByPosition}, otherwise it is ignored.
33 | *
34 | * @author Andrew Rucker Jones
35 | * @since 3.8
36 | */
37 | @Documented
38 | @Retention(RetentionPolicy.RUNTIME)
39 | @Target(ElementType.FIELD)
40 | public @interface CsvDate {
41 |
42 | /**
43 | * A time format string.
44 | * This must be a string understood by
45 | * {@link java.time.format.DateTimeFormatter#ofPattern(java.lang.String)}.
46 | * The default value conforms with
47 | * ISO 8601 and is
48 | * {@code "yyyyMMdd'T'HHmmss"}. Locale information, if specified, is gleaned
49 | * from one of the other CSV-related annotations and is used for conversion.
50 | *
51 | * @return The format string for parsing input
52 | */
53 | String value() default "yyyyMMdd'T'HHmmss";
54 | }
55 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/MockClob.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 | /*
3 | Copyright 2005 Bytecode Pty Ltd.
4 |
5 | Licensed under the Apache License, Version 2.0 (the "License");
6 | you may not use this file except in compliance with the License.
7 | You may obtain a copy of the License at
8 |
9 | http://www.apache.org/licenses/LICENSE-2.0
10 |
11 | Unless required by applicable law or agreed to in writing, software
12 | distributed under the License is distributed on an "AS IS" BASIS,
13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | See the License for the specific language governing permissions and
15 | limitations under the License.
16 | */
17 |
18 | import java.io.*;
19 | import java.sql.Clob;
20 | import java.sql.SQLException;
21 |
22 | public class MockClob implements Clob {
23 |
24 | private String clobValue;
25 |
26 | public MockClob(String value) {
27 | clobValue = value;
28 | }
29 |
30 | public long length() throws SQLException {
31 | return 0;
32 | }
33 |
34 | public String getSubString(long l, int i) throws SQLException {
35 | return null;
36 | }
37 |
38 | public Reader getCharacterStream() throws SQLException {
39 | return new StringReader(clobValue);
40 | }
41 |
42 | public InputStream getAsciiStream() throws SQLException {
43 | return null;
44 | }
45 |
46 | public long position(String s, long l) throws SQLException {
47 | return 0;
48 | }
49 |
50 | public long position(Clob clob, long l) throws SQLException {
51 | return 0;
52 | }
53 |
54 | public int setString(long l, String s) throws SQLException {
55 | return 0;
56 | }
57 |
58 | public int setString(long l, String s, int i, int i1) throws SQLException {
59 | return 0;
60 | }
61 |
62 | public OutputStream setAsciiStream(long l) throws SQLException {
63 | return null;
64 | }
65 |
66 | public Writer setCharacterStream(long l) throws SQLException {
67 | return null;
68 | }
69 |
70 | public void truncate(long l) throws SQLException {
71 |
72 | }
73 |
74 | public void free() throws SQLException {
75 |
76 | }
77 |
78 | public Reader getCharacterStream(long l, long l1) throws SQLException {
79 | return null;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/RFC4180ParserBuilderTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 |
4 | import com.opencsv.enums.CSVReaderNullFieldIndicator;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 |
8 | import static org.junit.Assert.assertEquals;
9 |
10 | public class RFC4180ParserBuilderTest {
11 |
12 | private RFC4180ParserBuilder builder;
13 |
14 | @Before
15 | public void setUp() throws Exception {
16 | builder = new RFC4180ParserBuilder();
17 | }
18 |
19 | @Test
20 | public void testDefaultBuilder() {
21 | assertEquals(
22 | ICSVParser.DEFAULT_SEPARATOR,
23 | builder.getSeparator());
24 | assertEquals(
25 | ICSVParser.DEFAULT_QUOTE_CHARACTER,
26 | builder.getQuoteChar());
27 | assertEquals(
28 | ICSVParser.DEFAULT_ESCAPE_CHARACTER,
29 | builder.getEscapeChar());
30 | assertEquals(
31 | ICSVParser.DEFAULT_STRICT_QUOTES,
32 | builder.isStrictQuotes());
33 | assertEquals(
34 | ICSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
35 | builder.isIgnoreLeadingWhiteSpace());
36 | assertEquals(
37 | ICSVParser.DEFAULT_IGNORE_QUOTATIONS,
38 | builder.isIgnoreQuotations());
39 | assertEquals(CSVReaderNullFieldIndicator.NEITHER, builder.nullFieldIndicator());
40 |
41 | ICSVParser parser = builder.build();
42 | assertEquals(
43 | ICSVParser.DEFAULT_SEPARATOR,
44 | parser.getSeparator());
45 | assertEquals(
46 | ICSVParser.DEFAULT_QUOTE_CHARACTER,
47 | parser.getQuotechar());
48 | }
49 |
50 | @Test
51 | public void testWithSeparator() {
52 | final char expected = '1';
53 | builder.withSeparator(expected);
54 | assertEquals(expected, builder.getSeparator());
55 | assertEquals(expected, builder.build().getSeparator());
56 | }
57 |
58 | @Test
59 | public void testWithQuoteChar() {
60 | final char expected = '2';
61 | builder.withQuoteChar(expected);
62 | assertEquals(expected, builder.getQuoteChar());
63 | assertEquals(expected, builder.build().getQuotechar());
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/stream/reader/LineReaderTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.stream.reader;
2 |
3 | import org.junit.Test;
4 |
5 | import java.io.BufferedReader;
6 | import java.io.IOException;
7 | import java.io.StringReader;
8 |
9 | import static org.junit.Assert.assertEquals;
10 |
11 | public class LineReaderTest {
12 | private static final String ORIGINAL = "This is the original string\r\n";
13 | private static final String WITH_CR = "This is the original string\r";
14 | private static final String NO_CR = "This is the original string";
15 | private static final String EMPTY_STRING = "";
16 | private static final String NULL_STRING = null;
17 |
18 | private LineReader createLineReaderforString(String s, boolean keepCR) {
19 | StringReader sr = new StringReader(s);
20 | return new LineReader(new BufferedReader(sr), keepCR);
21 | }
22 |
23 | @Test
24 | public void lineReaderWillKeepCR() throws IOException {
25 | LineReader keepCRReader = createLineReaderforString(ORIGINAL, true);
26 | assertEquals(WITH_CR, keepCRReader.readLine());
27 | }
28 |
29 | @Test
30 | public void lineReaderWillRemoveCR() throws IOException {
31 | LineReader noCRReader = createLineReaderforString(ORIGINAL, false);
32 | assertEquals(NO_CR, noCRReader.readLine());
33 | }
34 |
35 | @Test
36 | public void lineReaderKeepingCRWillHandleStringWithNoLinefeed() throws IOException {
37 | LineReader reader = createLineReaderforString(NO_CR, true);
38 | assertEquals(NO_CR, reader.readLine());
39 | }
40 |
41 | @Test
42 | public void lineReaderNoCRWillHandleStringWithNoLinefeed() throws IOException {
43 | LineReader reader = createLineReaderforString(NO_CR, false);
44 | assertEquals(NO_CR, reader.readLine());
45 | }
46 |
47 | @Test
48 | public void lineReaderKeepingCRWillHandleEmptyString() throws IOException {
49 | LineReader reader = createLineReaderforString(EMPTY_STRING, true);
50 | assertEquals(NULL_STRING, reader.readLine());
51 | }
52 |
53 | @Test
54 | public void lineReaderNoCRWillHandleEmptyString() throws IOException {
55 | LineReader reader = createLineReaderforString(EMPTY_STRING, false);
56 | assertEquals(NULL_STRING, reader.readLine());
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /*
7 | * Copyright 2007,2010 Kyle Miller.
8 | *
9 | * Licensed under the Apache License, Version 2.0 (the "License");
10 | * you may not use this file except in compliance with the License.
11 | * You may obtain a copy of the License at
12 | *
13 | * http://www.apache.org/licenses/LICENSE-2.0
14 | *
15 | * Unless required by applicable law or agreed to in writing, software
16 | * distributed under the License is distributed on an "AS IS" BASIS,
17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 | * See the License for the specific language governing permissions and
19 | * limitations under the License.
20 | */
21 |
22 | /**
23 | * Expands on HeaderColumnNameMappingStrategy by allowing the user to pass in a
24 | * map of column names to bean names.
25 | * This way the fields in the bean do not have to match the fields in the CSV
26 | * file. This is only for when the user passes in the header names
27 | * programmatically, and not for annotated beans.
28 | *
29 | * @param Class to be mapped.
30 | */
31 | public class HeaderColumnNameTranslateMappingStrategy extends HeaderColumnNameMappingStrategy {
32 | private final Map columnMapping;
33 |
34 | /**
35 | * Default constructor.
36 | */
37 | public HeaderColumnNameTranslateMappingStrategy() {
38 | columnMapping = new HashMap();
39 | }
40 |
41 | @Override
42 | public String getColumnName(int col) {
43 | return col < header.length ? columnMapping.get(header[col].toUpperCase()) : null;
44 | }
45 |
46 | /**
47 | * Retrieves the column mappings of the strategy.
48 | * @return The column mappings of the strategy.
49 | */
50 | public Map getColumnMapping() {
51 | return columnMapping;
52 | }
53 |
54 | /**
55 | * Sets the column mapping to those passed in.
56 | * @param columnMapping Source column mapping.
57 | */
58 | public void setColumnMapping(Map columnMapping) {
59 | this.columnMapping.clear();
60 | for (Map.Entry entry : columnMapping.entrySet()) {
61 | this.columnMapping.put(entry.getKey().toUpperCase(), entry.getValue());
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/CsvBadConverterException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.exceptions;
17 |
18 | /**
19 | * This exception indicates that the custom converter provided did not behave as
20 | * expected in some way.
21 | * Typically this means it could not be instantiated.
22 | *
23 | * @author Andrew Rucker Jones
24 | * @since 3.8
25 | */
26 | public class CsvBadConverterException extends CsvRuntimeException {
27 | private final Class converterClass;
28 |
29 | /**
30 | * Default constructor, in case no further information is necessary or
31 | * available.
32 | */
33 | public CsvBadConverterException() {
34 | converterClass = null;
35 | }
36 |
37 | /**
38 | * Constructor for specifying the class of the offending converter.
39 | *
40 | * @param converterClass The class of the converter that misbehaved
41 | */
42 | public CsvBadConverterException(Class converterClass) {
43 | this.converterClass = converterClass;
44 | }
45 |
46 | /**
47 | * Constructor with a simple text.
48 | *
49 | * @param message Human-readable error text
50 | */
51 | public CsvBadConverterException(String message) {
52 | super(message);
53 | converterClass = null;
54 | }
55 |
56 | /**
57 | * Constructor for setting the class of the converter and an error message.
58 | *
59 | * @param converterClass Class of the converter that misbehaved
60 | * @param message Human-readable error text
61 | */
62 | public CsvBadConverterException(Class converterClass, String message) {
63 | super(message);
64 | this.converterClass = converterClass;
65 | }
66 |
67 | /**
68 | * @return The class of the provided custom converter
69 | */
70 | public Class getConverterClass() {
71 | return converterClass;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/customconverter/ConvertGermanToBooleanRequired.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.customconverter;
17 |
18 | import com.opencsv.exceptions.CsvDataTypeMismatchException;
19 | import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
20 |
21 | /**
22 | * This is the same as {@link com.opencsv.bean.customconverter.ConvertGermanToBoolean},
23 | * except that it throws {@link com.opencsv.exceptions.CsvRequiredFieldEmptyException}
24 | * if the input is empty.
25 | *
26 | * @param Type of the bean to be manipulated
27 | *
28 | * @author Andrew Rucker Jones
29 | * @since 3.8
30 | */
31 | public class ConvertGermanToBooleanRequired extends ConvertGermanToBoolean {
32 |
33 | /**
34 | * Silence code style checker by adding a useless constructor.
35 | */
36 | public ConvertGermanToBooleanRequired() {
37 | }
38 |
39 | /**
40 | * @throws CsvRequiredFieldEmptyException If the input is empty
41 | */
42 | // The rest of the JavaDoc is automatically inherited from the base class.
43 | @Override
44 | protected Object convert(String value)
45 | throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
46 | Object o = super.convert(value);
47 | if (o == null) {
48 | throw new CsvRequiredFieldEmptyException();
49 | }
50 | return o;
51 | }
52 |
53 | /**
54 | * @throws CsvRequiredFieldEmptyException If value is null, because this
55 | * converter requires a value
56 | */
57 | // The rest of the JavaDoc is automatically inherited from the base class.
58 | @Override
59 | protected String convertToWrite(Object value)
60 | throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
61 | if(value == null) {
62 | throw new CsvRequiredFieldEmptyException();
63 | }
64 | return super.convertToWrite(value);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/ConverterComplexClassForCustomAnnotation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.AbstractBeanField;
19 | import com.opencsv.exceptions.CsvConstraintViolationException;
20 | import com.opencsv.exceptions.CsvDataTypeMismatchException;
21 | import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
22 |
23 | /**
24 | * This class converts to {@link com.opencsv.bean.mocks.ComplexClassForCustomAnnotation}.
25 | *
26 | * @author Andrew Rucker Jones
27 | */
28 | public class ConverterComplexClassForCustomAnnotation extends AbstractBeanField {
29 |
30 | @Override
31 | protected Object convert(String value) throws CsvDataTypeMismatchException,
32 | CsvRequiredFieldEmptyException, CsvConstraintViolationException {
33 | ComplexClassForCustomAnnotation o;
34 | String[] sa = value.split("\\.", 3);
35 | if (sa[2].contains("derived")) {
36 | o = new ComplexDerivedClassForCustomAnnotation();
37 | ((ComplexDerivedClassForCustomAnnotation) o).f = (float) 1.0;
38 | } else if (sa[2].contains("badtype")) {
39 | return "Mismatched data type";
40 | } else {
41 | o = new ComplexClassForCustomAnnotation();
42 | }
43 | o.i = Integer.valueOf(sa[0]);
44 | o.c = sa[1].charAt(0);
45 | o.s = sa[2];
46 | return o;
47 | }
48 |
49 | @Override
50 | protected String convertToWrite(Object o) throws CsvDataTypeMismatchException {
51 | if(!(o instanceof ComplexClassForCustomAnnotation)) {
52 | throw new CsvDataTypeMismatchException();
53 | }
54 | ComplexClassForCustomAnnotation c = (ComplexClassForCustomAnnotation)o;
55 | StringBuilder sb = new StringBuilder();
56 | sb.append(c.i).append('.');
57 | sb.append(c.c).append('.');
58 | sb.append(c.s);
59 | return sb.toString();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/issue3402853/MockUserBean.java:
--------------------------------------------------------------------------------
1 | package integrationTest.issue3402853;
2 |
3 | import org.apache.commons.lang3.StringUtils;
4 |
5 | public class MockUserBean {
6 | public static final String DEFAULT_BLANK_FIELD = "";
7 | private String first_name = DEFAULT_BLANK_FIELD;
8 | private String last_name = DEFAULT_BLANK_FIELD;
9 | private String profile_id = "";
10 | private String email = "";
11 | private String secondary_email = "";
12 |
13 | public String getProfile_Id() {
14 | return profile_id;
15 | }
16 |
17 | public void setProfile_Id(String userId) {
18 | this.profile_id = userId;
19 | }
20 |
21 | public String getEmail() {
22 | return email;
23 | }
24 |
25 | public void setEmail(String email) {
26 | this.email = email;
27 | }
28 |
29 | public String getFirst_Name() {
30 | return first_name;
31 | }
32 |
33 | public void setFirst_Name(String firstName) {
34 | this.first_name = firstName;
35 | }
36 |
37 | public String getLast_Name() {
38 | return last_name;
39 | }
40 |
41 | public void setLast_Name(String lastName) {
42 | this.last_name = lastName;
43 | }
44 |
45 | @Override
46 | public String toString() {
47 | String userId = StringUtils.isEmpty(getProfile_Id()) ? "" : getProfile_Id().trim();
48 | String firstname = StringUtils.isEmpty(getFirst_Name()) ? "" : getFirst_Name().trim();
49 | String lastname = StringUtils.isEmpty(getLast_Name()) ? "" : getLast_Name().trim();
50 | String email = StringUtils.isEmpty(getEmail()) ? "" : getEmail().trim();
51 | StringBuilder value = new StringBuilder();
52 | value.append(",user id:").append(userId);
53 | value.append(",email:").append(email);
54 | value.append(",first name:").append(firstname);
55 | value.append(",last name:").append(lastname);
56 |
57 | return value.toString();
58 | }
59 |
60 | public boolean equals(Object obj) {
61 | if ((null == obj) || !(obj instanceof MockUserBean)) {
62 | return false;
63 | }
64 |
65 | return this == obj || (obj).toString().equalsIgnoreCase(this.toString());
66 | }
67 |
68 | public int hashCode() {
69 | return toString().hashCode();
70 | }
71 |
72 | public boolean isFirstNameEmpty() {
73 | return isNameEmpty(getFirst_Name());
74 | }
75 |
76 | public boolean isLastNameEmpty() {
77 | return isNameEmpty(getLast_Name());
78 | }
79 |
80 | private boolean isNameEmpty(String name) {
81 | return name == null || name.length() == 0 || DEFAULT_BLANK_FIELD.equals(name);
82 |
83 | }
84 |
85 | public String getSecondary_Email() {
86 | return secondary_email;
87 | }
88 |
89 | public void setSecondary_Email(String secondaryEmail) {
90 | this.secondary_email = secondaryEmail;
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/CsvToBeanFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Mark Rogers.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.opencsv.bean;
18 |
19 | /**
20 | * Here's an example showing how to use {@link CsvToBean} with a column
21 | * name mapping and line filtering. It assumes that there is a class named
22 | * Feature defined with setters setName(String) and
23 | * setState(String). The FEATURE_NAME and STATE columns in the
24 | * CSV file will be used. Any additional columns will be ignored. The filter
25 | * will eliminate any lines where the STATE value is "production".
26 | *
27 | *
28 | * {@code
29 | * private class StateFilter implements CsvToBeanFilter {
30 | *
31 | * private final MappingStrategy strategy;
32 | *
33 | * public NonProductionFilter(MappingStrategy strategy) {
34 | * this.strategy = strategy;
35 | * }
36 | *
37 | * public boolean allowLine(String[] line) {
38 | * int index = strategy.getColumnIndex("STATE");
39 | * String value = line[index];
40 | * boolean result = !"production".equals(value);
41 | * return result;
42 | * }
43 | *
44 | * }
45 | *
46 | * public List parseCsv(InputStreamReader streamReader) {
47 | * HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy();
48 | * Map columnMap = new HashMap();
49 | * columnMap.put("FEATURE_NAME", "name");
50 | * columnMap.put("STATE", "state");
51 | * strategy.setColumnMapping(columnMap);
52 | * strategy.setType(Feature.class);
53 | * CSVReader reader = new CSVReader(streamReader);
54 | * CsvToBeanFilter filter = new StateFilter(strategy);
55 | * return new CsvToBean().parse(strategy, reader, filter);
56 | * }
57 | * }
58 | *
59 | */
60 | public interface CsvToBeanFilter {
61 |
62 | /**
63 | * Determines if a line from the CSV file will be included in the
64 | * output of {@link CsvToBean}. If the CSV file has a header row, it
65 | * may be useful for implementations to call
66 | * {@link MappingStrategy#getColumnIndex} to identify the correct column
67 | * indices to examine.
68 | *
69 | * @param line A line of data from the CSV file
70 | * @return True if the line is to be included in the output. Otherwise,
71 | * false.
72 | */
73 | boolean allowLine(String[] line);
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/ResultSetHelper.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 | /*
3 | Copyright 2005 Bytecode Pty Ltd.
4 |
5 | Licensed under the Apache License, Version 2.0 (the "License");
6 | you may not use this file except in compliance with the License.
7 | You may obtain a copy of the License at
8 |
9 | http://www.apache.org/licenses/LICENSE-2.0
10 |
11 | Unless required by applicable law or agreed to in writing, software
12 | distributed under the License is distributed on an "AS IS" BASIS,
13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | See the License for the specific language governing permissions and
15 | limitations under the License.
16 | */
17 |
18 | import java.io.IOException;
19 | import java.sql.ResultSet;
20 | import java.sql.SQLException;
21 |
22 | /**
23 | * Interface for the ResultSetHelperService.
24 | * Allows the user to define their own ResultSetHelper for use in the CSVWriter.
25 | */
26 | public interface ResultSetHelper {
27 | /**
28 | * Returns the column names from the ResultSet.
29 | *
30 | * @param rs ResultSet
31 | * @return String array containing the column names.
32 | * @throws SQLException Thrown by the ResultSet.
33 | */
34 | String[] getColumnNames(ResultSet rs) throws SQLException;
35 |
36 | /**
37 | * Returns the column values from the result set.
38 | * @param rs The ResultSet containing the values.
39 | * @return String array containing the values.
40 | * @throws SQLException Thrown by the ResultSet.
41 | * @throws IOException Thrown by the ResultSet.
42 | */
43 | String[] getColumnValues(ResultSet rs) throws SQLException, IOException;
44 |
45 | /**
46 | * Returns the column values from the result set with the values trimmed if desired.
47 | * @param rs The ResultSet containing the values.
48 | * @param trim Values should have white spaces trimmed.
49 | * @return String array containing the values.
50 | * @throws SQLException Thrown by the ResultSet.
51 | * @throws IOException Thrown by the ResultSet.
52 | */
53 | String[] getColumnValues(ResultSet rs, boolean trim) throws SQLException, IOException;
54 |
55 | /**
56 | * Returns the column values from the result set with the values trimmed if desired.
57 | * Also format the date and time columns based on the format strings passed in.
58 | * @param rs The ResultSet containing the values.
59 | * @param trim Values should have white spaces trimmed.
60 | * @param dateFormatString Format string for dates.
61 | * @param timeFormatString Format string for timestamps.
62 | * @return String array containing the values.
63 | * @throws SQLException Thrown by the ResultSet.
64 | * @throws IOException Thrown by the ResultSet.
65 | */
66 | String[] getColumnValues(ResultSet rs, boolean trim, String dateFormatString, String timeFormatString)
67 | throws SQLException, IOException;
68 | }
69 |
--------------------------------------------------------------------------------
/src/test/resources/AnnotationWritingTestPlan.csv:
--------------------------------------------------------------------------------
1 | Test case,Test,Expected behavior,Status
1,Writing every primitive data type,Data are written correctly,pass
2,Writing every wrapped primitive data type,Data are written correctly,pass
3,"Writing String, BigDecimal and BigInteger",Data are written correctly,pass
4,Writing with ConvertGermanToBoolean,Data are written correctly,pass
5,Writing with ConvertGermanToBooleanRequired,Data are written correctly,pass
6,Writing with ConvertSplitOnWhitespace,Data are written correctly,pass
7,Writing all locale-sensitive data without locales,Data are written correctly,pass
8,Writing all locale-sensitive data with locales,Data are written correctly,pass
9,Writing a date type without an explicit format string,Data are written correctly,pass
10,Writing a date type with an explicit format string,Data are written correctly,pass
11,Writing a single bean,Data are written correctly,pass
12,Writing multiple beans at once,Data are written correctly,pass
13,Writing a mixture of single beans and multiple beans,Data are written correctly,pass
14,Writing with @CsvBindByPosition and @CsvCustomBindByPosition,Data are written correctly,pass
15,"Writing with @CsvBindByName, @CsvCustomBindByName and @CsvBind",Data are written correctly,pass
16,Writing with no annotations,Data are written correctly,pass
17,Writing with mixed @CsvBindByName and @CsvBindByPosition annotation types,"Data are written correctly, ColumnPositionMappingStrategy is used",pass
18,Write using a specified mapping strategy,Data are written correctly,pass
19,Writing when getter is missing,CsvBeanIntrospectionException,pass
20,Writing when getter is private,CsvBeanIntrospectionException,pass
21,Writing with @CsvBindByName attached to unknown type,Data are written with toString(),pass
22,Writing with @CsvBindByPosition attached to unknown type,Data are written with toString(),pass
23,Writing with @CsvBind attached to unsupported type,Data are written with toString() using header name mapping,pass
24,Writing a required wrapped primitive field that is null,CsvRequiredFieldEmptyException,pass
25,Writing an optional wrapped primitive field that is null,Data are written correctly,pass
26,Writing a required date field that is null,CsvRequiredFieldEmptyException,pass
27,Writing an optional date field that is null,Data are written correctly,pass
28,Writing an empty field with ConvertGermanToBooleanRequired,CsvRequiredFieldEmptyException,pass
29,Writing bad data with exceptions captured,getCapturedExceptions() returns exceptions,pass
30,Writing bad data without exceptions captured,Exceptions get thrown,pass
31,Reading captured exceptions twice in a row,"Captured exceptions are not empty the first time, but empty the second time",pass
32,Writing multiple times with exceptions from each write,Captured exceptions are the sum of all exceptions in all write operations,pass
33,Writing a subclass with annotations in the subclass and the superclass,Data are written correctly,pass
34,"Specifying a superclass, but writing a subclass",Data from superclass are written,pass
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/MockBean.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean.mocks;
2 |
3 | /*
4 | * Copyright 2007 Kyle Miller.
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 | public class MockBean {
19 | private String name;
20 | private String id;
21 | private String orderNumber;
22 | private int num;
23 | private double doubleNum;
24 |
25 | public String getId() {
26 | return id;
27 | }
28 |
29 | public void setId(String id) {
30 | this.id = id;
31 | }
32 |
33 | public String getName() {
34 | return name;
35 | }
36 |
37 | public void setName(String name) {
38 | this.name = name;
39 | }
40 |
41 | public String getOrderNumber() {
42 | return orderNumber;
43 | }
44 |
45 | public void setOrderNumber(String orderNumber) {
46 | this.orderNumber = orderNumber;
47 | }
48 |
49 | public int getNum() {
50 | return num;
51 | }
52 |
53 | public void setNum(int num) {
54 | this.num = num;
55 | }
56 |
57 | public double getDoubleNum() {
58 | return doubleNum;
59 | }
60 |
61 | public void setDoubleNum(double doubleNum) {
62 | this.doubleNum = doubleNum;
63 | }
64 |
65 | @Override
66 | public boolean equals(Object o) {
67 | if (this == o) return true;
68 | if (!(o instanceof MockBean)) return false;
69 |
70 | MockBean mockBean = (MockBean) o;
71 |
72 | if (getNum() != mockBean.getNum()) return false;
73 | if (Double.compare(mockBean.getDoubleNum(), getDoubleNum()) != 0) return false;
74 | if (getName() != null ? !getName().equals(mockBean.getName()) : mockBean.getName() != null) return false;
75 | if (getId() != null ? !getId().equals(mockBean.getId()) : mockBean.getId() != null) return false;
76 | return !(getOrderNumber() != null ? !getOrderNumber().equals(mockBean.getOrderNumber()) : mockBean.getOrderNumber() != null);
77 |
78 | }
79 |
80 | @Override
81 | public int hashCode() {
82 | int result;
83 | long temp;
84 | result = getName() != null ? getName().hashCode() : 0;
85 | result = 31 * result + (getId() != null ? getId().hashCode() : 0);
86 | result = 31 * result + (getOrderNumber() != null ? getOrderNumber().hashCode() : 0);
87 | result = 31 * result + getNum();
88 | temp = Double.doubleToLongBits(getDoubleNum());
89 | result = 31 * result + (int) (temp ^ (temp >>> 32));
90 | return result;
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/test/resources/testinputposcustomgood.csv:
--------------------------------------------------------------------------------
1 | long test string;wahr;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;falsch;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.derived.string3
2 | long test string;ja;nein;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;nein;ja;really;4.d.long,long.string4;5.e.long,long.derived.string5;6.f.long,long.string6
3 | long test string;1;0;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;0;1; ;7.g.long,long.derived.string7;8.h.long,long.string8;9.i.long,long.string9
4 | long test string;j;n;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;n;j;really long test string;10.j.long,long.string10;11.k.long,long.string11;12.l.long,long.string12
5 | long test string;w;f;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;f;w;really long test string;13.m.long,long.string13;14.n.long,long.string14;15.o.long,long.string15
6 | long test string;w;f;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;;;;16.p.long,long.string16;17.q.long,long.string17;18.r.long,long.string18
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/CsvConstraintViolationException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.exceptions;
17 |
18 | /**
19 | * This exception is thrown when logical connections between data fields would
20 | * be violated by the imported data.
21 | * This can be for constraints like making certain a number is in a certain
22 | * range, or it can even be thrown by code using opencsv when constraints
23 | * outside of opencsv would be violated. An example of the latter is importing
24 | * into a database when one of the field in the CSV is supposed to contain the
25 | * primary key for a foreign table, but the foreign key cannot be satisfied.
26 | * This exception is not currently used by opencsv itself, since opencsv has
27 | * no concept of what data consistency means in the context of the application
28 | * using it. It is meant more for custom converters.
29 | *
30 | * @author Andrew Rucker Jones
31 | * @since 3.8
32 | */
33 | public class CsvConstraintViolationException extends CsvException {
34 | private final Object sourceObject;
35 |
36 | /**
37 | * Default constructor, in case no further information is necessary or
38 | * available.
39 | */
40 | public CsvConstraintViolationException() {
41 | sourceObject = null;
42 | }
43 |
44 | /**
45 | * Constructor for setting the source object that triggered the constraint
46 | * violation.
47 | *
48 | * @param sourceObject The offending source object
49 | */
50 | public CsvConstraintViolationException(Object sourceObject) {
51 | this.sourceObject = sourceObject;
52 | }
53 |
54 | /**
55 | * Constructor with a simple text.
56 | *
57 | * @param message Human-readable error text
58 | */
59 | public CsvConstraintViolationException(String message) {
60 | super(message);
61 | sourceObject = null;
62 | }
63 |
64 | /**
65 | * Constructor for setting the source object and an error message.
66 | *
67 | * @param sourceObject The offending source object
68 | * @param message Human-readable error text
69 | */
70 | public CsvConstraintViolationException(Object sourceObject, String message) {
71 | super(message);
72 | this.sourceObject = sourceObject;
73 | }
74 |
75 | /**
76 | * @return The source object that triggered the constraint violation
77 | */
78 | public Object getSourceObject() {
79 | return sourceObject;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/mocks/CustomTestMapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.mocks;
17 |
18 | import com.opencsv.bean.AbstractBeanField;
19 | import com.opencsv.exceptions.CsvConstraintViolationException;
20 | import com.opencsv.exceptions.CsvDataTypeMismatchException;
21 | import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
22 |
23 | import java.math.BigDecimal;
24 | import java.math.BigInteger;
25 |
26 | /**
27 | * A basic custom mapper that maps all primitives and wrapped primitives.
28 | * Always returns the same values, regardless of the input, unless the
29 | * destination type is a string.
30 | *
31 | * @param Type of the bean
32 | * @author Andrew Rucker Jones
33 | */
34 | public class CustomTestMapper extends AbstractBeanField {
35 | @Override
36 | protected Object convert(String value)
37 | throws CsvDataTypeMismatchException,
38 | CsvRequiredFieldEmptyException, CsvConstraintViolationException {
39 | Class fieldType = field.getType();
40 | if (fieldType.equals(Boolean.TYPE) || fieldType.equals(Boolean.class))
41 | return Boolean.TRUE;
42 | if (fieldType.equals(Byte.TYPE) || fieldType.equals(Byte.class))
43 | return Byte.MAX_VALUE;
44 | if (fieldType.equals(Double.TYPE) || fieldType.equals(Double.class))
45 | return Double.MAX_VALUE;
46 | if (fieldType.equals(Float.TYPE) || fieldType.equals(Float.class))
47 | return Float.MAX_VALUE;
48 | if (fieldType.equals(Integer.TYPE) || fieldType.equals(Integer.class))
49 | return Integer.MAX_VALUE;
50 | if (fieldType.equals(Long.TYPE) || fieldType.equals(Long.class))
51 | return Long.MAX_VALUE;
52 | if (fieldType.equals(Short.TYPE) || fieldType.equals(Short.class))
53 | return Short.MAX_VALUE;
54 | if (fieldType.equals(Character.TYPE) || fieldType.equals(Character.class))
55 | return Character.MAX_VALUE;
56 | if (fieldType.equals(BigDecimal.class))
57 | return BigDecimal.TEN;
58 | if (fieldType.equals(BigInteger.class))
59 | return BigInteger.TEN;
60 | if (fieldType.isAssignableFrom(String.class))
61 | return "inside custom converter";
62 | throw new CsvDataTypeMismatchException(value, fieldType, String.format(
63 | "Unable to set field value for field '%s' with value '%s' "
64 | + "- type is unsupported. Use primitive, boxed "
65 | + "primitive, BigDecimal, BigInteger and String types only.",
66 | fieldType, value));
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/CsvBindByName.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean;
17 |
18 | import java.lang.annotation.*;
19 |
20 | /**
21 | * Specifies a binding between a column name of the CSV input and a field in a
22 | * bean.
23 | *
24 | * @author Andrew Rucker Jones
25 | * @since 3.8
26 | */
27 | @Documented
28 | @Retention(RetentionPolicy.RUNTIME)
29 | @Target(ElementType.FIELD)
30 | public @interface CsvBindByName {
31 |
32 | /**
33 | * Whether or not the annotated field is required to be present in every
34 | * data set of the input.
35 | *
36 | * @return If the field is required to contain information.
37 | */
38 | boolean required() default false;
39 |
40 | /**
41 | * If not specified, the name of the column must be identical to the name
42 | * of the field.
43 | *
44 | * @return The name of the column in the CSV file from which this field
45 | * should be taken.
46 | */
47 | String column() default "";
48 |
49 | /**
50 | * Defines the locale to be used for decoding the argument.
51 | * If not specified, the current default locale is used. The locale must be
52 | * one recognized by {@link java.util.Locale}. Locale conversion is supported
53 | * for the following data types:
54 | * - byte and {@link java.lang.Byte}
55 | * - float and {@link java.lang.Float}
56 | * - double and {@link java.lang.Double}
57 | * - int and {@link java.lang.Integer}
58 | * - long and {@link java.lang.Long}
59 | * - short and {@link java.lang.Short}
60 | * - {@link java.math.BigDecimal}
61 | * - {@link java.math.BigInteger}
62 | * - All time data types supported by {@link com.opencsv.bean.CsvDate}
63 | * The locale must be in a format accepted by
64 | * {@link java.util.Locale#forLanguageTag(java.lang.String)}
65 | * Caution must be exercized with the default locale, for the default
66 | * locale for numerical types does not mean the locale of the running
67 | * program, such as en-US or de-DE, but rather no locale. Numbers
68 | * will be parsed more or less the way the Java compiler would parse them.
69 | * That means, for instance, that thousands separators in long numbers are
70 | * not permitted, even if the locale of the running program would accept
71 | * them. When dealing with locale-sensitive data, it is always best to
72 | * specify the locale explicitly.
73 | *
74 | * @return The locale selected. The default is indicated by an empty string.
75 | */
76 | String locale() default "";
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/CsvBindByPosition.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean;
17 |
18 | import java.lang.annotation.*;
19 |
20 | /**
21 | * Specifies a binding between a column number of the CSV input and a field in
22 | * a bean.
23 | *
24 | * @author Andrew Rucker Jones
25 | * @since 3.8
26 | */
27 | @Documented
28 | @Retention(RetentionPolicy.RUNTIME)
29 | @Target(ElementType.FIELD)
30 | public @interface CsvBindByPosition {
31 |
32 | /**
33 | * Whether or not the annotated field is required to be present in every
34 | * data set of the input.
35 | *
36 | * @return If the field is required to contain information.
37 | */
38 | boolean required() default false;
39 |
40 | /**
41 | * The column position in the input that is used to fill the annotated
42 | * field.
43 | *
44 | * @return The position of the column in the CSV file from which this field
45 | * should be taken. This column number is zero-based.
46 | */
47 | int position();
48 |
49 | /**
50 | * Defines the locale to be used for decoding the argument.
51 | * If not specified, the current default locale is used. The locale must be
52 | * one recognized by {@link java.util.Locale}. Locale conversion is supported
53 | * for the following data types:
54 | * - byte and {@link java.lang.Byte}
55 | * - float and {@link java.lang.Float}
56 | * - double and {@link java.lang.Double}
57 | * - int and {@link java.lang.Integer}
58 | * - long and {@link java.lang.Long}
59 | * - short and {@link java.lang.Short}
60 | * - {@link java.math.BigDecimal}
61 | * - {@link java.math.BigInteger}
62 | * - All time data types supported by {@link com.opencsv.bean.CsvDate}
63 | * The locale must be in a format accepted by
64 | * {@link java.util.Locale#forLanguageTag(java.lang.String)}
65 | * Caution must be exercized with the default locale, for the default
66 | * locale for numerical types does not mean the locale of the running
67 | * program, such as en-US or de-DE, but rather no locale. Numbers
68 | * will be parsed more or less the way the Java compiler would parse them.
69 | * That means, for instance, that thousands separators in long numbers are
70 | * not permitted, even if the locale of the running program would accept
71 | * them. When dealing with locale-sensitive data, it is always best to
72 | * specify the locale explicitly.
73 | *
74 | * @return The locale selected. The default is indicated by an empty string.
75 | */
76 | String locale() default "";
77 | }
78 |
--------------------------------------------------------------------------------
/src/test/resources/testinputcustomgood.csv:
--------------------------------------------------------------------------------
1 | string1;bool1;boolPrimitive;byte1;byte2;byte3;byte4;double1;double2;double3;double4;float1;float2;float3;float4;integer1;integer2;integer3;integer4;long1;long2;long3;long4;short1;short2;short3;short4;char1;char2;bigdecimal1;bigdecimal2;biginteger1;biginteger2;date1;date2;date3;date4;date5;date6;date7;date8;date9;date10;date11;date12;bool2;bool3;string2;complex1;complex2;complex3
2 | long test string;wahr;falsch;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;falsch;wahr;really long test string, yeah!;1.a.long,long.string1;2.b.long,long.string2;3.c.long,long.derived.string3
3 | long test string;ja;nein;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;nein;ja;really;4.d.long,long.string4;5.e.long,long.derived.string5;6.f.long,long.string6
4 | long test string;1;0;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;0;1; ;7.g.long,long.derived.string7;8.h.long,long.string8;9.i.long,long.string9
5 | long test string;j;n;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;n;j;really long test string;10.j.long,long.string10;11.k.long,long.string11;12.l.long,long.string12
6 | long test string;w;f;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;f;w;really long test string;13.m.long,long.string13;14.n.long,long.string14;15.o.long,long.string15
7 | long test string;w;f;1;2;3;4;123,101.101;123.202,202;123303.303;123404,404;123101.101;123202,202;123303.303;123404,404;5000;6.000;7000;8000;9000;10000;11000;12000;13000;14000;15000;16000;a;b;123101.101;123102,102;101;102;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;19780115T063209;;;;16.p.long,long.string16;17.q.long,long.string17;18.r.long,long.string18
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/CsvRequiredFieldEmptyException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.exceptions;
17 |
18 | import java.lang.reflect.Field;
19 |
20 | /**
21 | * This exception should be thrown when a field marked as required is empty in
22 | * the CSV file.
23 | *
24 | * @author Andrew Rucker Jones
25 | * @since 3.8
26 | */
27 | public class CsvRequiredFieldEmptyException extends CsvException {
28 | private final Class beanClass;
29 | private final Field destinationField;
30 |
31 | /**
32 | * Default constructor, in case no further information is necessary.
33 | */
34 | public CsvRequiredFieldEmptyException() {
35 | beanClass = null;
36 | destinationField = null;
37 | }
38 |
39 | /**
40 | * Constructor with a simple text.
41 | *
42 | * @param message Human-readable error text
43 | */
44 | public CsvRequiredFieldEmptyException(String message) {
45 | super(message);
46 | beanClass = null;
47 | destinationField = null;
48 | }
49 |
50 | /**
51 | * Constructor for setting the intended class and field of the target bean.
52 | * These may not be known in every context.
53 | *
54 | * @param beanClass Class of the destination bean
55 | * @param destinationField Field of the destination field in the destination bean
56 | */
57 | public CsvRequiredFieldEmptyException(Class beanClass, Field destinationField) {
58 | this.beanClass = beanClass;
59 | this.destinationField = destinationField;
60 | }
61 |
62 | /**
63 | * Constructor for setting the intended class and field of the target bean
64 | * along with an error message.
65 | * The class and field may not be known in every context.
66 | *
67 | * @param beanClass Class of the destination bean
68 | * @param destinationField Field of the destination field in the destination bean
69 | * @param message Human-readable error text
70 | */
71 | public CsvRequiredFieldEmptyException(Class beanClass, Field destinationField, String message) {
72 | super(message);
73 | this.beanClass = beanClass;
74 | this.destinationField = destinationField;
75 | }
76 |
77 | /**
78 | * Gets the class of the bean to which the value was to be assigned.
79 | *
80 | * @return The class of the bean to which the destination field belongs
81 | */
82 | public Class getBeanClass() {
83 | return beanClass;
84 | }
85 |
86 | /**
87 | * Gets the field from the Reflection API that was to be assigned.
88 | *
89 | * @return The destination field that was to receive the empty value
90 | */
91 | public Field getDestinationField() {
92 | return destinationField;
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/BeanField.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | import com.opencsv.exceptions.CsvConstraintViolationException;
4 | import com.opencsv.exceptions.CsvDataTypeMismatchException;
5 | import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
6 |
7 | import java.lang.reflect.Field;
8 |
9 | /**
10 | * Used to extend the {@link java.lang.reflect.Field} class to include
11 | * functionality that opencsv requires.
12 | * This includes a required flag and a {@link #write(java.lang.Object)} method
13 | * for writing beans back out to a CSV file. The required flag determines if the
14 | * field has to be non-empty.
15 | *
16 | * @param Type of the bean being populated
17 | */
18 | public interface BeanField {
19 |
20 | /**
21 | * Sets the field to be processed.
22 | *
23 | * @param field Which field is being populated
24 | */
25 | void setField(Field field);
26 |
27 | /**
28 | * Gets the field to be processed.
29 | *
30 | * @return A field object
31 | * @see java.lang.reflect.Field
32 | */
33 | Field getField();
34 |
35 | /**
36 | * Populates the selected field of the bean.
37 | * This method performs conversion on the input string and assigns the
38 | * result to the proper field in the provided bean.
39 | *
40 | * @param bean Object containing the field to be set.
41 | * @param value String containing the value to set the field to.
42 | * @param Type of the bean.
43 | * @throws CsvDataTypeMismatchException When the result of data conversion returns
44 | * an object that cannot be assigned to the selected field
45 | * @throws CsvRequiredFieldEmptyException When a field is mandatory, but there is no
46 | * input datum in the CSV file
47 | * @throws CsvConstraintViolationException When the internal structure of
48 | * data would be violated by the data in the CSV file
49 | */
50 | void setFieldValue(T bean, String value)
51 | throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException,
52 | CsvConstraintViolationException;
53 |
54 | /**
55 | * This method takes the current value of the field in question in the bean
56 | * passed in and converts it to a string.
57 | * This method is used to write beans back out to a CSV file, and should
58 | * ideally provide an accurate representation of the field such that it is
59 | * roundtrip equivalent. That is to say, this method should write data out
60 | * just as it would expect to read the data in.
61 | *
62 | * @param bean The bean holding the field to be written
63 | * @return A string representation of this field out of the bean passed in.
64 | * If either the bean or the field are null, this method returns null to
65 | * allow the writer to treat null specially. The writer may wish to write
66 | * "(null)" or "\0" or "NULL" or some other key instead of a blank string.
67 | *
68 | * @throws CsvDataTypeMismatchException If expected to convert an
69 | * unsupported data type
70 | * @throws CsvRequiredFieldEmptyException If the field is marked as required,
71 | * but currently contains null
72 | * @since 3.9
73 | */
74 | String write(T bean) throws CsvDataTypeMismatchException,
75 | CsvRequiredFieldEmptyException;
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/RFC4180ParserBuilder.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 |
4 | import com.opencsv.enums.CSVReaderNullFieldIndicator;
5 |
6 | /**
7 | * Builder for creating a RFC4180Parser.
8 | * Example code for using this class:
9 | *
10 | * final RFC4180Parser parser =
11 | * new RFC4180ParserBuilder()
12 | * .withSeparator('\t')
13 | * .build();
14 | *
15 | *
16 | * @see RFC4180Parser
17 | */
18 | public class RFC4180ParserBuilder {
19 |
20 | private char separator = ICSVParser.DEFAULT_SEPARATOR;
21 | private char quoteChar = ICSVParser.DEFAULT_QUOTE_CHARACTER;
22 | private char escapeChar = ICSVParser.DEFAULT_ESCAPE_CHARACTER;
23 | private boolean strictQuotes = ICSVParser.DEFAULT_STRICT_QUOTES;
24 | private boolean ignoreLeadingWhiteSpace = ICSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE;
25 | private boolean ignoreQuotations = ICSVParser.DEFAULT_IGNORE_QUOTATIONS;
26 | private CSVReaderNullFieldIndicator nullFieldIndicator = CSVReaderNullFieldIndicator.NEITHER;
27 |
28 | /**
29 | * default constructor
30 | */
31 | public RFC4180ParserBuilder() {
32 | }
33 |
34 | /**
35 | * @return The defined separator.
36 | */
37 | public char getSeparator() {
38 | return separator;
39 | }
40 |
41 | /**
42 | * @return The defined quotation character.
43 | */
44 | public char getQuoteChar() {
45 | return quoteChar;
46 | }
47 |
48 | /**
49 | * @return The defined escape character.
50 | */
51 | public char getEscapeChar() {
52 | return escapeChar;
53 | }
54 |
55 | /**
56 | * @return The defined strict quotation setting.
57 | */
58 | public boolean isStrictQuotes() {
59 | return strictQuotes;
60 | }
61 |
62 | /**
63 | * @return The defined ignoreLeadingWhiteSpace setting.
64 | */
65 | public boolean isIgnoreLeadingWhiteSpace() {
66 | return ignoreLeadingWhiteSpace;
67 | }
68 |
69 | /**
70 | * @return The defined ignoreQuotation setting.
71 | */
72 | public boolean isIgnoreQuotations() {
73 | return ignoreQuotations;
74 | }
75 |
76 | /**
77 | * @return The null field indicator.
78 | */
79 | public CSVReaderNullFieldIndicator nullFieldIndicator() {
80 | return nullFieldIndicator;
81 | }
82 |
83 | /**
84 | * Constructs RFC4180Parser.
85 | *
86 | * @return A new RFC4180Parser with defined settings.
87 | */
88 | public RFC4180Parser build() {
89 |
90 | return new RFC4180Parser(quoteChar, separator);
91 |
92 | }
93 |
94 | /**
95 | * Sets the delimiter to use for separating entries.
96 | *
97 | * @param separator The delimiter to use for separating entries
98 | * @return The RFC4180ParserBuilder
99 | */
100 | public RFC4180ParserBuilder withSeparator(
101 | final char separator) {
102 | this.separator = separator;
103 | return this;
104 | }
105 |
106 |
107 | /**
108 | * Sets the character to use for quoted elements.
109 | *
110 | * @param quoteChar The character to use for quoted element.
111 | * @return The RFC4180ParserBuilder
112 | */
113 | public RFC4180ParserBuilder withQuoteChar(
114 | final char quoteChar) {
115 | this.quoteChar = quoteChar;
116 | return this;
117 | }
118 |
119 | }
120 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/IterableCSVToBeanBuilderTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 | /**
3 | * Copyright 2005 Bytecode Pty Ltd.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 |
19 | import com.opencsv.CSVReader;
20 | import org.junit.Before;
21 | import org.junit.Test;
22 |
23 | import static org.junit.Assert.*;
24 | import static org.mockito.Mockito.mock;
25 |
26 | /**
27 | * Created by scott on 7/28/15.
28 | */
29 | public class IterableCSVToBeanBuilderTest {
30 | private IterableCSVToBeanBuilder builder;
31 | private MappingStrategy mockMappingStrategy;
32 | private CsvToBeanFilter mockFilter;
33 | private CSVReader mockReader;
34 |
35 | @Before
36 | public void createBuilder() {
37 | builder = new IterableCSVToBeanBuilder();
38 | mockMappingStrategy = mock(MappingStrategy.class);
39 | mockReader = mock(CSVReader.class);
40 | mockFilter = mock(CsvToBeanFilter.class);
41 | }
42 |
43 | @Test
44 | public void defaultBuilderMissingInformation() {
45 |
46 | String message = null;
47 | try {
48 | builder.build();
49 | } catch (RuntimeException rte) {
50 | message = rte.getMessage();
51 | }
52 | assertEquals(IterableCSVToBeanBuilder.NO_MAPPING_STRATEGY_DEFINED, message);
53 | }
54 |
55 | @Test
56 | public void willThrowExceptionIfMissingReader() {
57 | String message = null;
58 | try {
59 | builder.withMapper(mockMappingStrategy).build();
60 | } catch (RuntimeException rte) {
61 | message = rte.getMessage();
62 | }
63 | assertEquals(IterableCSVToBeanBuilder.NO_READER_DEFINED, message);
64 | }
65 |
66 | @Test
67 | public void builderWithoutFilter() {
68 | IterableCSVToBean bean = builder.withMapper(mockMappingStrategy)
69 | .withReader(mockReader)
70 | .build();
71 | assertEquals(mockMappingStrategy, builder.getStrategy());
72 | assertEquals(mockReader, builder.getCsvReader());
73 | assertNull(builder.getFilter());
74 |
75 | assertNotNull(bean);
76 | assertEquals(mockMappingStrategy, bean.getStrategy());
77 | assertEquals(mockReader, bean.getCSVReader());
78 | assertNull(bean.getFilter());
79 | }
80 |
81 | @Test
82 | public void builderWithFilter() {
83 | IterableCSVToBean bean = builder.withMapper(mockMappingStrategy)
84 | .withReader(mockReader)
85 | .withFilter(mockFilter)
86 | .build();
87 | assertEquals(mockMappingStrategy, builder.getStrategy());
88 | assertEquals(mockReader, builder.getCsvReader());
89 | assertEquals(mockFilter, builder.getFilter());
90 |
91 | assertNotNull(bean);
92 | assertEquals(mockMappingStrategy, bean.getStrategy());
93 | assertEquals(mockReader, bean.getCSVReader());
94 | assertEquals(mockFilter, bean.getFilter());
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/CsvDataTypeMismatchException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.exceptions;
17 |
18 | /**
19 | * This exception should be thrown when the provided string value for conversion
20 | * cannot be converted to the required type of the destination field.
21 | *
22 | * @author Andrew Rucker Jones
23 | * @since 3.8
24 | */
25 | public class CsvDataTypeMismatchException extends CsvException {
26 | private final Object sourceObject;
27 | private final Class destinationClass;
28 |
29 | /**
30 | * Default constructor, in case no further information is necessary or
31 | * available.
32 | */
33 | public CsvDataTypeMismatchException() {
34 | sourceObject = null;
35 | destinationClass = null;
36 | }
37 |
38 | /**
39 | * Constructor for setting the data and the class of the intended
40 | * destination field.
41 | *
42 | * @param sourceObject Object that was to be assigned to the destination
43 | * field. This may not be available in all contexts.
44 | * @param destinationClass Class of the destination field. This may not be
45 | * available in all contexts.
46 | */
47 | public CsvDataTypeMismatchException(Object sourceObject, Class destinationClass) {
48 | this.sourceObject = sourceObject;
49 | this.destinationClass = destinationClass;
50 | }
51 |
52 | /**
53 | * Constructor with a simple text.
54 | *
55 | * @param message Human-readable error text
56 | */
57 | public CsvDataTypeMismatchException(String message) {
58 | super(message);
59 | sourceObject = null;
60 | destinationClass = null;
61 | }
62 |
63 | /**
64 | * Constructor for setting the data and the class of the intended
65 | * destination field along with an error message.
66 | *
67 | * @param sourceObject Object that was to be assigned to the destination
68 | * field. This may not be available in all contexts.
69 | * @param destinationClass Class of the destination field. This may not be
70 | * available in all contexts.
71 | * @param message Human-readable error text
72 | */
73 | public CsvDataTypeMismatchException(Object sourceObject, Class destinationClass, String message) {
74 | super(message);
75 | this.sourceObject = sourceObject;
76 | this.destinationClass = destinationClass;
77 | }
78 |
79 | /**
80 | * Gets the object that was to be assigned to a field of the wrong type.
81 | *
82 | * @return The data that could not be assigned
83 | */
84 | public Object getSourceObject() {
85 | return sourceObject;
86 | }
87 |
88 | /**
89 | * Gets the type of the field to which the data were to be assigned.
90 | *
91 | * @return The class of the destination field
92 | */
93 | public Class getDestinationClass() {
94 | return destinationClass;
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/CSVReaderBuilderTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import com.opencsv.enums.CSVReaderNullFieldIndicator;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 |
7 | import java.io.Reader;
8 |
9 | import static org.junit.Assert.*;
10 | import static org.mockito.Mockito.mock;
11 |
12 | public class CSVReaderBuilderTest {
13 |
14 | private CSVReaderBuilder builder;
15 | private Reader reader;
16 |
17 | @Before
18 | public void setUp() throws Exception {
19 | reader = mock(Reader.class);
20 | builder = new CSVReaderBuilder(reader);
21 | }
22 |
23 | @Test
24 | public void testDefaultBuilder() {
25 | assertSame(reader, builder.getReader());
26 | assertNull(builder.getCsvParser());
27 | assertEquals(
28 | CSVReader.DEFAULT_SKIP_LINES,
29 | builder.getSkipLines());
30 |
31 | final CSVReader csvReader = builder.build();
32 | assertEquals(
33 | CSVReader.DEFAULT_SKIP_LINES,
34 | csvReader.getSkipLines());
35 | assertEquals(CSVReader.DEFAULT_KEEP_CR, csvReader.keepCarriageReturns());
36 | assertEquals(CSVReader.DEFAULT_VERIFY_READER, csvReader.verifyReader());
37 | }
38 |
39 | @Test(expected = IllegalArgumentException.class)
40 | public void testNullReader() {
41 | builder = new CSVReaderBuilder(null);
42 | }
43 |
44 | @Test
45 | public void testWithCSVParserNull() {
46 | builder.withCSVParser(mock(CSVParser.class));
47 | builder.withCSVParser(null);
48 | assertNull(builder.getCsvParser());
49 | }
50 |
51 | @Test
52 | public void testWithCSVParser() {
53 | final ICSVParser csvParser = mock(CSVParser.class);
54 |
55 | builder.withCSVParser(csvParser);
56 |
57 | assertSame(csvParser, builder.getCsvParser());
58 |
59 | final CSVReader actual = builder.build();
60 | assertSame(csvParser, actual.getParser());
61 | }
62 |
63 | @Test
64 | public void testWithSkipLines() {
65 | builder.withSkipLines(99);
66 |
67 | assertEquals(99, builder.getSkipLines());
68 |
69 | final CSVReader actual = builder.build();
70 | assertSame(99, actual.getSkipLines());
71 | }
72 |
73 | @Test
74 | public void testWithKeepCR() {
75 | builder.withKeepCarriageReturn(true);
76 | assertTrue(builder.keepCarriageReturn());
77 |
78 | final CSVReader actual = builder.build();
79 | assertTrue(actual.keepCarriageReturns());
80 | }
81 |
82 | @Test
83 | public void testWithSkipLinesZero() {
84 | builder.withSkipLines(0);
85 |
86 | assertEquals(0, builder.getSkipLines());
87 |
88 | final CSVReader actual = builder.build();
89 | assertSame(0, actual.getSkipLines());
90 | }
91 |
92 | @Test
93 | public void testWithSkipLinesNegative() {
94 | builder.withSkipLines(-1);
95 |
96 | assertEquals(0, builder.getSkipLines());
97 |
98 | final CSVReader actual = builder.build();
99 | assertSame(0, actual.getSkipLines());
100 | }
101 |
102 | @Test
103 | public void testWithVerifyReader() {
104 | final CSVReader reader = builder.withVerifyReader(false).build();
105 | assertFalse(reader.verifyReader());
106 | }
107 |
108 | @Test
109 | public void builderWithNullFieldIndicator() {
110 | final CSVReader reader = builder.withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS).build();
111 |
112 | assertEquals(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS, reader.getParser().nullFieldIndicator());
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/AbstractCSVToBean.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | import java.beans.PropertyDescriptor;
4 | import java.beans.PropertyEditor;
5 | import java.beans.PropertyEditorManager;
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | /**
10 | * Converts CSV data to objects.
11 | */
12 | public abstract class AbstractCSVToBean {
13 |
14 | private Map, PropertyEditor> editorMap = null;
15 |
16 | /**
17 | * Attempt to find custom property editor on descriptor first, else try the
18 | * propery editor manager.
19 | *
20 | * @param desc PropertyDescriptor.
21 | * @return The PropertyEditor for the given PropertyDescriptor.
22 | * @throws InstantiationException Thrown when getting the PropertyEditor for the class.
23 | * @throws IllegalAccessException Thrown when getting the PropertyEditor for the class.
24 | */
25 | abstract protected PropertyEditor getPropertyEditor(PropertyDescriptor desc)
26 | throws InstantiationException, IllegalAccessException;
27 |
28 | /**
29 | * Returns the trimmed value of the string only if the property the string
30 | * is describing should be trimmed to be converted to that type.
31 | *
32 | * @param s String describing the value.
33 | * @param prop Property descriptor of the value.
34 | * @return The string passed in if the property is a string, otherwise it
35 | * will return the string with the beginning and end whitespace removed.
36 | */
37 | protected String checkForTrim(String s, PropertyDescriptor prop) {
38 | return s != null && trimmableProperty(prop) ? s.trim() : s;
39 | }
40 |
41 | private boolean trimmableProperty(PropertyDescriptor prop) {
42 | return !prop.getPropertyType().getName().contains("String");
43 | }
44 |
45 | /**
46 | * Convert a string value to its Object value.
47 | *
48 | * @param value String value
49 | * @param prop PropertyDescriptor
50 | * @return The object set to value (i.e. Integer). Will return String if
51 | * no PropertyEditor is found.
52 | * @throws InstantiationException Thrown on error getting the property
53 | * editor from the property descriptor.
54 | * @throws IllegalAccessException Thrown on error getting the property
55 | * editor from the property descriptor.
56 | */
57 | protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException, IllegalAccessException {
58 | PropertyEditor editor = getPropertyEditor(prop);
59 | Object obj = value;
60 | if (null != editor) {
61 | editor.setAsText(value);
62 | obj = editor.getValue();
63 | }
64 | return obj;
65 | }
66 |
67 | /**
68 | * Returns the PropertyEditor for the given class.
69 | * Should be more efficient if used often, because it caches PropertyEditors.
70 | *
71 | * @param cls The class for which the property editor is desired
72 | * @return The PropertyEditor for the given class
73 | */
74 | protected PropertyEditor getPropertyEditorValue(Class> cls) {
75 | if (editorMap == null) {
76 | editorMap = new HashMap, PropertyEditor>();
77 | }
78 |
79 | PropertyEditor editor = editorMap.get(cls);
80 |
81 | if (editor == null) {
82 | editor = PropertyEditorManager.findEditor(cls);
83 | addEditorToMap(cls, editor);
84 | }
85 |
86 | return editor;
87 | }
88 |
89 | private void addEditorToMap(Class> cls, PropertyEditor editor) {
90 | if (editor != null) {
91 | editorMap.put(cls, editor);
92 | }
93 | }
94 |
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/ICSVParser.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import com.opencsv.enums.CSVReaderNullFieldIndicator;
4 |
5 | import java.io.IOException;
6 |
7 | import static com.opencsv.enums.CSVReaderNullFieldIndicator.NEITHER;
8 |
9 | /**
10 | * Created by scott on 6/26/16.
11 | */
12 | public interface ICSVParser {
13 | /**
14 | * The default separator to use if none is supplied to the constructor.
15 | */
16 | char DEFAULT_SEPARATOR = ',';
17 | /**
18 | * The average size of a line read by opencsv (used for setting the size of StringBuilders).
19 | */
20 | int INITIAL_READ_SIZE = 1024;
21 | /**
22 | * In most cases we know the size of the line we want to read. In that case we will set the initial read
23 | * to that plus an buffer size.
24 | */
25 | int READ_BUFFER_SIZE = 128;
26 | /**
27 | * The default quote character to use if none is supplied to the
28 | * constructor.
29 | */
30 | char DEFAULT_QUOTE_CHARACTER = '"';
31 | /**
32 | * The default escape character to use if none is supplied to the
33 | * constructor.
34 | */
35 | char DEFAULT_ESCAPE_CHARACTER = '\\';
36 | /**
37 | * The default strict quote behavior to use if none is supplied to the
38 | * constructor.
39 | */
40 | boolean DEFAULT_STRICT_QUOTES = false;
41 | /**
42 | * The default leading whitespace behavior to use if none is supplied to the
43 | * constructor.
44 | */
45 | boolean DEFAULT_IGNORE_LEADING_WHITESPACE = true;
46 | /**
47 | * If the quote character is set to null then there is no quote character.
48 | */
49 | boolean DEFAULT_IGNORE_QUOTATIONS = false;
50 | /**
51 | * This is the "null" character - if a value is set to this then it is ignored.
52 | */
53 | char NULL_CHARACTER = '\0';
54 | /**
55 | * Multi-line fields with more than this number of lines are considered an
56 | * error. This is to fail faster in the case of a stray unmatched quote in
57 | * a very large file.
58 | */
59 | int MAX_LINES_IN_MULTILINE = 10000;
60 | /**
61 | * Denotes what field contents will cause the parser to return null: EMPTY_SEPARATORS, EMPTY_QUOTES, BOTH, NEITHER (default)
62 | */
63 | CSVReaderNullFieldIndicator DEFAULT_NULL_FIELD_INDICATOR = NEITHER;
64 |
65 | /**
66 | * @return The default separator for this parser.
67 | */
68 | char getSeparator();
69 |
70 | /**
71 | * @return The default quotation character for this parser.
72 | */
73 | char getQuotechar();
74 |
75 | /**
76 | * @return True if something was left over from last call(s)
77 | */
78 | boolean isPending();
79 |
80 | /**
81 | * Parses an incoming String and returns an array of elements.
82 | * This method is used when the data spans multiple lines.
83 | *
84 | * @param nextLine Current line to be processed
85 | * @return The comma-tokenized list of elements, or null if nextLine is null
86 | * @throws IOException If bad things happen during the read
87 | */
88 | String[] parseLineMulti(String nextLine) throws IOException;
89 |
90 | /**
91 | * Parses an incoming String and returns an array of elements.
92 | * This method is used when all data is contained in a single line.
93 | *
94 | * @param nextLine Line to be parsed.
95 | * @return The list of elements, or null if nextLine is null
96 | * @throws IOException If bad things happen during the read
97 | */
98 | String[] parseLine(String nextLine) throws IOException;
99 |
100 | /**
101 | * @return The null field indicator.
102 | */
103 | CSVReaderNullFieldIndicator nullFieldIndicator();
104 | }
105 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/CsvToBeanFilterTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | import com.opencsv.CSVReader;
4 | import org.junit.Test;
5 |
6 | import java.io.InputStreamReader;
7 | import java.io.StringReader;
8 | import java.util.HashMap;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | import static org.junit.Assert.assertEquals;
13 |
14 | public class CsvToBeanFilterTest {
15 |
16 | private static final String TEST_STRING =
17 | "FEATURE_NAME,STATE,USER_COUNT\n" +
18 | "hello world,production,3228\n" +
19 | "calc age,beta,74\n" +
20 | "wash dishes,alpha,3";
21 |
22 | private CSVReader createReader() {
23 | StringReader reader = new StringReader(TEST_STRING);
24 | return new CSVReader(reader);
25 | }
26 |
27 | private MappingStrategy CreateMappingStrategy() {
28 | HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy();
29 | Map columnMap = new HashMap();
30 | columnMap.put("FEATURE_NAME", "name");
31 | columnMap.put("STATE", "state");
32 | strategy.setColumnMapping(columnMap);
33 | strategy.setType(Feature.class);
34 | return strategy;
35 | }
36 |
37 | public static class Feature {
38 | private String name;
39 | private String state;
40 |
41 | public void setName(String name) {
42 | this.name = name;
43 | }
44 |
45 | public void setState(String state) {
46 | this.state = state;
47 | }
48 |
49 | public String getName() {
50 | return name;
51 | }
52 |
53 | public String getState() {
54 | return state;
55 | }
56 | }
57 |
58 | private class NonProductionFilter implements CsvToBeanFilter {
59 |
60 | private final MappingStrategy strategy;
61 |
62 | public NonProductionFilter(MappingStrategy strategy) {
63 | this.strategy = strategy;
64 | }
65 |
66 | @Override
67 | public boolean allowLine(String[] line) {
68 | int index = strategy.getColumnIndex("STATE");
69 | String value = line[index];
70 | boolean result = !"production".equals(value);
71 | return result;
72 | }
73 |
74 | }
75 |
76 | @Test
77 | public void testColumnNameTranslationWithLineFiltering() {
78 | CsvToBean csvToBean = new CsvToBean();
79 | CSVReader reader = createReader();
80 | MappingStrategy strategy = CreateMappingStrategy();
81 | CsvToBeanFilter filter = new NonProductionFilter(strategy);
82 | List list = csvToBean.parse(strategy, reader, filter);
83 | assertEquals("Parsing resulted in the wrong number of items.", 2, list.size());
84 | assertEquals("The first item has the wrong name.", "calc age", list.get(0).getName());
85 | assertEquals("The first item has the wrong state.", "beta", list.get(0).getState());
86 | assertEquals("The second item has the wrong name.", "wash dishes", list.get(1).getName());
87 | assertEquals("The second item has the wrong state.", "alpha", list.get(1).getState());
88 | }
89 |
90 | public List parseCsv(InputStreamReader streamReader) {
91 | HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy();
92 | Map columnMap = new HashMap();
93 | columnMap.put("FEATURE_NAME", "name");
94 | columnMap.put("STATE", "state");
95 | strategy.setColumnMapping(columnMap);
96 | strategy.setType(Feature.class);
97 | CSVReader reader = new CSVReader(streamReader);
98 | CsvToBeanFilter filter = new NonProductionFilter(strategy);
99 | return new CsvToBean().parse(strategy, reader, filter);
100 | }
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/HeaderColumnNameTranslateMappingStrategyTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | /*
4 | Copyright 2007 Kyle Miller.
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | */
18 |
19 | import com.opencsv.bean.mocks.MockBean;
20 | import org.junit.Test;
21 |
22 | import java.io.StringReader;
23 | import java.util.HashMap;
24 | import java.util.List;
25 | import java.util.Map;
26 |
27 | import static org.junit.Assert.*;
28 |
29 | public class HeaderColumnNameTranslateMappingStrategyTest {
30 |
31 | @Test
32 | public void testParse() {
33 | String s = "n,o,foo\n" +
34 | "kyle,123456,emp123\n" +
35 | "jimmy,abcnum,cust09878";
36 | HeaderColumnNameTranslateMappingStrategy strat = new HeaderColumnNameTranslateMappingStrategy();
37 | strat.setType(MockBean.class);
38 | Map map = new HashMap();
39 | map.put("n", "name");
40 | map.put("o", "orderNumber");
41 | map.put("foo", "id");
42 | strat.setColumnMapping(map);
43 |
44 | CsvToBean csv = new CsvToBean();
45 | List list = csv.parse(strat, new StringReader(s));
46 | assertNotNull(list);
47 | assertTrue(list.size() == 2);
48 | MockBean bean = list.get(0);
49 | assertEquals("kyle", bean.getName());
50 | assertEquals("123456", bean.getOrderNumber());
51 | assertEquals("emp123", bean.getId());
52 | }
53 |
54 | @Test
55 | public void getColumnNameReturnsNullIfColumnNumberIsTooLarge() {
56 | String s = "n,o,foo\n" +
57 | "kyle,123456,emp123\n" +
58 | "jimmy,abcnum,cust09878";
59 | HeaderColumnNameTranslateMappingStrategy strat = new HeaderColumnNameTranslateMappingStrategy();
60 | strat.setType(MockBean.class);
61 | Map map = new HashMap();
62 | map.put("n", "name");
63 | map.put("o", "orderNumber");
64 | map.put("foo", "id");
65 | strat.setColumnMapping(map);
66 |
67 | CsvToBean csv = new CsvToBean();
68 | csv.parse(strat, new StringReader(s));
69 |
70 | assertEquals("name", strat.getColumnName(0));
71 | assertEquals("orderNumber", strat.getColumnName(1));
72 | assertEquals("id", strat.getColumnName(2));
73 | assertNull(strat.getColumnName(3));
74 | }
75 |
76 | @Test
77 | public void columnNameMappingShouldBeCaseInsensitive() {
78 | String s = "n,o,Foo\n" +
79 | "kyle,123456,emp123\n" +
80 | "jimmy,abcnum,cust09878";
81 | HeaderColumnNameTranslateMappingStrategy strat = new HeaderColumnNameTranslateMappingStrategy();
82 | strat.setType(MockBean.class);
83 | Map map = new HashMap();
84 | map.put("n", "name");
85 | map.put("o", "orderNumber");
86 | map.put("foo", "id");
87 | strat.setColumnMapping(map);
88 | assertNotNull(strat.getColumnMapping());
89 |
90 | CsvToBean csv = new CsvToBean();
91 | csv.parse(strat, new StringReader(s));
92 |
93 | assertEquals("name", strat.getColumnName(0));
94 | assertEquals("orderNumber", strat.getColumnName(1));
95 | assertEquals("id", strat.getColumnName(2));
96 | assertNull(strat.getColumnName(3));
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/test/java/integrationTest/SR34/SR34Test.java:
--------------------------------------------------------------------------------
1 | package integrationTest.SR34;
2 |
3 | import com.opencsv.CSVReader;
4 | import com.opencsv.CSVReaderBuilder;
5 | import com.opencsv.ICSVParser;
6 |
7 | import org.junit.Before;
8 | import org.junit.Test;
9 |
10 | import java.io.*;
11 | import java.util.List;
12 |
13 | import static org.junit.Assert.fail;
14 | import static org.junit.Assert.assertEquals;
15 |
16 | /**
17 | * Created by scott on 3/6/15.
18 | */
19 | public class SR34Test {
20 | private static final String TEST_FILE = "src/test/java/integrationTest/SR34/NULSpecialChar2.log";
21 | private static final String DOUBLE_NULL_FILE = "src/test/java/integrationTest/SR34/NULSpecialChar3.log";
22 | InputStreamReader inputStreamReader;
23 |
24 | @Before
25 | public void setUp() throws FileNotFoundException, UnsupportedEncodingException {
26 | inputStreamReader = new InputStreamReader(new FileInputStream(TEST_FILE), "UTF-8");
27 | }
28 |
29 | @Test
30 | public void defaultReaderInterpetsNullCorrectly() throws IOException {
31 | CSVReaderBuilder builder = new CSVReaderBuilder(inputStreamReader);
32 | CSVReader csvReader = builder.build();
33 |
34 | String[] line = csvReader.readNext();
35 | assertEquals(6, line.length);
36 | assertEquals("10", line[0]);
37 | assertEquals("IBM", line[1]);
38 | assertEquals("2015063", line[2]);
39 | assertEquals("064230733910", line[3]);
40 | assertEquals("\0", line[4]);
41 | assertEquals("01 ", line[5]);
42 | }
43 |
44 | @Test
45 | public void doubleBufferedReaderInterpetsNullCorrectly() throws IOException {
46 | BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
47 | CSVReaderBuilder builder = new CSVReaderBuilder(bufferedReader);
48 | CSVReader csvReader = builder.build();
49 |
50 | String[] line = csvReader.readNext();
51 | assertEquals(6, line.length);
52 | assertEquals("10", line[0]);
53 | assertEquals("IBM", line[1]);
54 | assertEquals("2015063", line[2]);
55 | assertEquals("064230733910", line[3]);
56 | assertEquals("\0", line[4]);
57 | assertEquals("01 ", line[5]);
58 | }
59 |
60 | @Test
61 | public void usingNullAsDelimeterWillFailBecauseYouAreEscapingTheQuote() throws IOException {
62 | BufferedReader bufferedStringReader1 = new BufferedReader(new InputStreamReader(new FileInputStream(TEST_FILE), "UTF-8"));
63 | CSVReader reader1 = new CSVReader(bufferedStringReader1, ICSVParser.DEFAULT_SEPARATOR, ICSVParser.DEFAULT_QUOTE_CHARACTER, '\0');
64 |
65 | try {
66 | reader1.readAll();
67 | fail("Should have thrown IOException due to unterminated quote");
68 | } catch (IOException possiblyExpected) {
69 | if (!possiblyExpected.getMessage().toLowerCase().contains("un-terminated")) {
70 | fail("Unexpected IOException: " + possiblyExpected.getMessage());
71 | }
72 | } finally {
73 | reader1.close();
74 | }
75 | }
76 |
77 | @Test
78 | public void youNeedToEscapeTheNullCharactersIfUsingNullAsEscape() throws IOException {
79 | BufferedReader bufferedStringReader1 = new BufferedReader(new InputStreamReader(new FileInputStream(DOUBLE_NULL_FILE), "UTF-8"));
80 | CSVReader reader1 = new CSVReader(bufferedStringReader1, ICSVParser.DEFAULT_SEPARATOR, ICSVParser.DEFAULT_QUOTE_CHARACTER, '\0');
81 |
82 | List rawTokens1;
83 | rawTokens1 = reader1.readAll();
84 | reader1.close();
85 |
86 | assertEquals(1, rawTokens1.size());
87 |
88 | String[] line = rawTokens1.get(0);
89 | assertEquals(6, line.length);
90 | assertEquals("10", line[0]);
91 | assertEquals("IBM", line[1]);
92 | assertEquals("2015063", line[2]);
93 | assertEquals("064230733910", line[3]);
94 | assertEquals("\0", line[4]);
95 | assertEquals("01 ", line[5]);
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/customconverter/ConvertSplitOnWhitespace.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.customconverter;
17 |
18 | import com.opencsv.bean.AbstractBeanField;
19 | import com.opencsv.exceptions.CsvConstraintViolationException;
20 | import com.opencsv.exceptions.CsvDataTypeMismatchException;
21 | import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
22 | import java.util.ArrayList;
23 | import java.util.Arrays;
24 | import java.util.List;
25 | import org.apache.commons.lang3.StringUtils;
26 |
27 | /**
28 | * This class takes a string and splits it on whitespace into a list of strings.
29 | *
30 | * @param Type of the bean to be manipulated
31 | *
32 | * @author Andrew Rucker Jones
33 | * @since 3.8
34 | */
35 | public class ConvertSplitOnWhitespace extends AbstractBeanField {
36 |
37 | /**
38 | * Silence code style checker by adding a useless constructor.
39 | */
40 | public ConvertSplitOnWhitespace() {
41 | }
42 |
43 | /**
44 | * Takes a string that is a list of substrings separated by whitespace and
45 | * returns a list of the substrings.
46 | * For example, the string "Jones Smith Cartwright Cooper" would be
47 | * converted by this method to ("Jones", "Smith", "Cartwright", "Cooper").
48 | * When might this be useful? A CSV has a set number of columns, but
49 | * sometimes some fields might need to contain a variable number of entries.
50 | * In this case, a list within one field of a CSV might make sense.
51 | *
52 | * @param value The string to be converted
53 | * @return List<String> consisting of the substrings from the input
54 | * that were separated in the input by whitespace
55 | * @throws CsvDataTypeMismatchException Is not thrown by this implementation
56 | * @throws CsvRequiredFieldEmptyException Is not thrown by this implementation
57 | * @throws CsvConstraintViolationException Is not thrown by this implementation
58 | *
59 | */
60 | @Override
61 | protected Object convert(String value)
62 | throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException,
63 | CsvConstraintViolationException {
64 | List l = null;
65 | if (!StringUtils.isEmpty(value)) {
66 | l = new ArrayList(Arrays.asList(value.split("\\s+")));
67 | }
68 | return l;
69 | }
70 |
71 | /**
72 | * This method takes the current value of the field in question in the bean
73 | * passed in and converts it to a string.
74 | *
75 | * @return The concatenation of a list of strings, with every entry
76 | * separated by a space
77 | * @throws CsvDataTypeMismatchException If the field is not a list of strings
78 | */
79 | @Override
80 | protected String convertToWrite(Object value) throws CsvDataTypeMismatchException {
81 | String result = "";
82 | try {
83 | if(value != null) {
84 | List values = (List) value;
85 | result = StringUtils.join(values, ' ');
86 | }
87 | }
88 | catch(ClassCastException e) {
89 | CsvDataTypeMismatchException csve =
90 | new CsvDataTypeMismatchException("The field must be of type List.");
91 | csve.initCause(e);
92 | throw csve;
93 | }
94 | return result;
95 | }
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/CSVParserBuilderTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv;
2 |
3 | import com.opencsv.enums.CSVReaderNullFieldIndicator;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 |
7 | import static org.junit.Assert.assertEquals;
8 |
9 | public class CSVParserBuilderTest {
10 |
11 | private CSVParserBuilder builder;
12 |
13 | @Before
14 | public void setUp() throws Exception {
15 | builder = new CSVParserBuilder();
16 | }
17 |
18 | @Test
19 | public void testDefaultBuilder() {
20 | assertEquals(
21 | ICSVParser.DEFAULT_SEPARATOR,
22 | builder.getSeparator());
23 | assertEquals(
24 | ICSVParser.DEFAULT_QUOTE_CHARACTER,
25 | builder.getQuoteChar());
26 | assertEquals(
27 | ICSVParser.DEFAULT_ESCAPE_CHARACTER,
28 | builder.getEscapeChar());
29 | assertEquals(
30 | ICSVParser.DEFAULT_STRICT_QUOTES,
31 | builder.isStrictQuotes());
32 | assertEquals(
33 | ICSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
34 | builder.isIgnoreLeadingWhiteSpace());
35 | assertEquals(
36 | ICSVParser.DEFAULT_IGNORE_QUOTATIONS,
37 | builder.isIgnoreQuotations());
38 | assertEquals(CSVReaderNullFieldIndicator.NEITHER, builder.nullFieldIndicator());
39 |
40 | CSVParser parser = builder.build();
41 | assertEquals(
42 | ICSVParser.DEFAULT_SEPARATOR,
43 | parser.getSeparator());
44 | assertEquals(
45 | ICSVParser.DEFAULT_QUOTE_CHARACTER,
46 | parser.getQuotechar());
47 | assertEquals(
48 | ICSVParser.DEFAULT_ESCAPE_CHARACTER,
49 | parser.getEscape());
50 | assertEquals(
51 | ICSVParser.DEFAULT_STRICT_QUOTES,
52 | parser.isStrictQuotes());
53 | assertEquals(
54 | ICSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
55 | parser.isIgnoreLeadingWhiteSpace());
56 | assertEquals(
57 | ICSVParser.DEFAULT_IGNORE_QUOTATIONS,
58 | parser.isIgnoreQuotations());
59 | assertEquals(CSVReaderNullFieldIndicator.NEITHER, parser.nullFieldIndicator());
60 | }
61 |
62 | @Test
63 | public void testWithSeparator() {
64 | final char expected = '1';
65 | builder.withSeparator(expected);
66 | assertEquals(expected, builder.getSeparator());
67 | assertEquals(expected, builder.build().getSeparator());
68 | }
69 |
70 | @Test
71 | public void testWithQuoteChar() {
72 | final char expected = '2';
73 | builder.withQuoteChar(expected);
74 | assertEquals(expected, builder.getQuoteChar());
75 | assertEquals(expected, builder.build().getQuotechar());
76 | }
77 |
78 | @Test
79 | public void testWithEscapeChar() {
80 | final char expected = '3';
81 | builder.withEscapeChar(expected);
82 | assertEquals(expected, builder.getEscapeChar());
83 | assertEquals(expected, builder.build().getEscape());
84 | }
85 |
86 | @Test
87 | public void testWithStrictQuotes() {
88 | final boolean expected = true;
89 | builder.withStrictQuotes(expected);
90 | assertEquals(expected, builder.isStrictQuotes());
91 | assertEquals(expected, builder.build().isStrictQuotes());
92 | }
93 |
94 | @Test
95 | public void testWithIgnoreLeadingWhiteSpace() {
96 | final boolean expected = true;
97 | builder.withIgnoreLeadingWhiteSpace(expected);
98 | assertEquals(expected, builder.isIgnoreLeadingWhiteSpace());
99 | assertEquals(expected, builder.build().isIgnoreLeadingWhiteSpace());
100 | }
101 |
102 | @Test
103 | public void testWithIgnoreQuotations() {
104 | final boolean expected = true;
105 | builder.withIgnoreQuotations(expected);
106 | assertEquals(expected, builder.isIgnoreQuotations());
107 | assertEquals(expected, builder.build().isIgnoreQuotations());
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/exceptions/CsvBeanIntrospectionException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.exceptions;
17 |
18 | import java.lang.reflect.Field;
19 |
20 | /**
21 | * This exception is to be thrown when anything goes bad during introspection of
22 | * beans given to opencsv.
23 | * It encapsulates exceptions such as {@link java.lang.NoSuchMethodException},
24 | * {@link java.lang.IllegalAccessException} and
25 | * {@link java.lang.reflect.InvocationTargetException}. Some might notice that
26 | * this effectively converts checked exceptions into unchecked exceptions.
27 | * Introspection exceptions are coding errors that should be fixed during
28 | * development, and should not have to be handled in production code.
29 | *
30 | * @author Andrew Rucker Jones
31 | * @since 3.9
32 | */
33 | public class CsvBeanIntrospectionException extends CsvRuntimeException {
34 |
35 | /** The bean that was acted upon. */
36 | private final Object bean;
37 |
38 | /** The field that was supposed to be manipulated in the bean. */
39 | private final Field field;
40 |
41 | /**
42 | * Nullary constructor.
43 | */
44 | public CsvBeanIntrospectionException() {
45 | super();
46 | bean = null;
47 | field = null;
48 | }
49 |
50 | /**
51 | * Constructor with a human-readable error message.
52 | * @param message Error message
53 | */
54 | public CsvBeanIntrospectionException(String message) {
55 | super(message);
56 | bean = null;
57 | field = null;
58 | }
59 |
60 | /**
61 | * Constructor to specify the bean and field whose manipulation caused this
62 | * exception.
63 | * @param bean The bean that was to be manipulated
64 | * @param field The field in the bean
65 | */
66 | public CsvBeanIntrospectionException(Object bean, Field field) {
67 | super();
68 | this.bean = bean;
69 | this.field = field;
70 | }
71 |
72 | /**
73 | * Constructor to provide all information connected to the error raised.
74 | * @param bean The bean that was to be manipulated
75 | * @param field The field in the bean
76 | * @param message Error message
77 | */
78 | public CsvBeanIntrospectionException(Object bean, Field field, String message) {
79 | super(message);
80 | this.bean = bean;
81 | this.field = field;
82 | }
83 |
84 | /**
85 | * Gets a human-readable error message.
86 | * @return The error message, or if none is found, but {@link #bean} and
87 | * {@link #field} have been set, returns a default error message
88 | * incorporating the names of {@link #bean} and {@link #field}
89 | */
90 | @Override
91 | public String getMessage() {
92 | String supermessage = super.getMessage();
93 | if(supermessage == null && getBean() != null && getField() != null) {
94 | return String.format("An introspection error was thrown while attempting to manipulate property %s of bean %s.",
95 | getField().getName(),
96 | getBean().getClass().getCanonicalName());
97 | }
98 | return supermessage;
99 | }
100 |
101 | /**
102 | * @return The bean that caused this exception
103 | */
104 | public Object getBean() {
105 | return bean;
106 | }
107 |
108 | /**
109 | * @return The field in the bean that caused this exception
110 | */
111 | public Field getField() {
112 | return field;
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/IterableCSVToBeanBuilder.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | /*
4 | * Copyright 2005 Bytecode Pty Ltd.
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | import com.opencsv.CSVReader;
20 |
21 | /**
22 | * Builder for creating an IterableCSVToBean.
23 | * This should be the preferred method of creating an IterableCSVToBean to keep
24 | * the number of constructors to a minimum.
25 | *
26 | *
27 | * {@code
28 | * IterableCSVToBean bean =
29 | * new IterableCSVToBean()
30 | * .withReader(csvReader)
31 | * .withMapper(mappingStrategy)
32 | * .withFilter(csvToBeanFilter)
33 | * .build();
34 | * }
35 | *
36 | *
37 | * @see IterableCSVToBean
38 | *
39 | * @param Type of the bean to be iterated over
40 | */
41 | public class IterableCSVToBeanBuilder {
42 |
43 | public static final String NO_MAPPING_STRATEGY_DEFINED = "Unable to instantiate IterableCSVToBeanBuilder because there is no MappingStrategy defined.";
44 | public static final String NO_READER_DEFINED = "Unable to instantiate IterableCSVToBeanBuilder because there is no CSVReader defined.";
45 |
46 | private MappingStrategy mapper;
47 | private CSVReader csvReader;
48 | private CsvToBeanFilter filter;
49 |
50 | /**
51 | * Default constructor.
52 | */
53 | public IterableCSVToBeanBuilder() {
54 | }
55 |
56 | /**
57 | * Creates the IterableCSVToBean.
58 | *
59 | * Will throw a runtime exception if the MappingStrategy or CSVReader is not set.
60 | *
61 | * @return An instance of IterableCSVToBean
62 | */
63 | public IterableCSVToBean build() {
64 | if (mapper == null) {
65 | throw new RuntimeException(NO_MAPPING_STRATEGY_DEFINED);
66 | }
67 | if (csvReader == null) {
68 | throw new RuntimeException(NO_READER_DEFINED);
69 | }
70 | return new IterableCSVToBean(csvReader, mapper, filter);
71 | }
72 |
73 | /**
74 | * Sets the MappingStrategy to be used by the builder.
75 | *
76 | * @param mappingStrategy An object that implements
77 | * {@link com.opencsv.bean.MappingStrategy}
78 | * @return The builder with the MappingStrategy set
79 | */
80 | public IterableCSVToBeanBuilder withMapper(final MappingStrategy mappingStrategy) {
81 | this.mapper = mappingStrategy;
82 | return this;
83 | }
84 |
85 | /**
86 | * Sets the reader to be used by the builder.
87 | * @param reader CSVReader to be incorporated in the builder.
88 | * @return The builder with the CSVReader set
89 | */
90 | public IterableCSVToBeanBuilder withReader(final CSVReader reader) {
91 | this.csvReader = reader;
92 | return this;
93 | }
94 |
95 | /**
96 | * Used by unit tests.
97 | * @return The MappingStrategy to be used by the builder.
98 | */
99 | protected MappingStrategy getStrategy() {
100 | return mapper;
101 | }
102 |
103 | /**
104 | * Used by unit tests.
105 | * @return The csvReader to be used by the builder.
106 | */
107 | protected CSVReader getCsvReader() {
108 | return csvReader;
109 | }
110 |
111 | /**
112 | * Used by unit tests.
113 | *
114 | * @return Filter to be used by the builder.
115 | */
116 | protected Object getFilter() {
117 | return filter;
118 | }
119 |
120 | /**
121 | * Sets the filter used to remove unwanted data from the CSV file.
122 | *
123 | * @param filter An object implementing CsvToBeanFilter
124 | * @return The builder with the filter set
125 | */
126 | public IterableCSVToBeanBuilder withFilter(final CsvToBeanFilter filter) {
127 | this.filter = filter;
128 | return this;
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/MappingStrategy.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 |
4 | /*
5 | Copyright 2007 Kyle Miller.
6 |
7 | Licensed under the Apache License, Version 2.0 (the "License");
8 | you may not use this file except in compliance with the License.
9 | You may obtain a copy of the License at
10 |
11 | http://www.apache.org/licenses/LICENSE-2.0
12 |
13 | Unless required by applicable law or agreed to in writing, software
14 | distributed under the License is distributed on an "AS IS" BASIS,
15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | See the License for the specific language governing permissions and
17 | limitations under the License.
18 | */
19 |
20 | import com.opencsv.CSVReader;
21 | import com.opencsv.exceptions.CsvBadConverterException;
22 |
23 | import java.beans.IntrospectionException;
24 | import java.beans.PropertyDescriptor;
25 | import java.io.IOException;
26 |
27 | /**
28 | * The interface for the classes that handle translating between the columns in
29 | * the CSV file to an actual object.
30 | *
31 | * @param Type of object you are converting the data to.
32 | */
33 | public interface MappingStrategy {
34 |
35 | /**
36 | * Gets the property descriptor for a given column position.
37 | *
38 | * @param col The column to find the description for
39 | * @return The property descriptor for the column position or null if one
40 | * could not be found.
41 | * @throws IntrospectionException Thrown on error retrieving the property
42 | * description.
43 | */
44 | PropertyDescriptor findDescriptor(int col) throws IntrospectionException;
45 |
46 | /**
47 | * Gets the field for a given column position.
48 | *
49 | * @param col The column to find the field for
50 | * @return BeanField containing the field for a given column position, or
51 | * null if one could not be found
52 | * @throws CsvBadConverterException If a custom converter for a field cannot
53 | * be initialized
54 | */
55 | BeanField findField(int col) throws CsvBadConverterException;
56 |
57 | /**
58 | * Finds and returns the highest index in this mapping.
59 | * This is especially important for writing, since position-based mapping
60 | * can ignore some columns that must be included in the output anyway.
61 | * {@link #findField(int) } will return null for these columns, so we need
62 | * a way to know when to stop writing new columns.
63 | * @return The highest index in the mapping. If there are no columns in the
64 | * mapping, returns -1.
65 | * @since 3.9
66 | */
67 | int findMaxFieldIndex();
68 |
69 | /**
70 | * Implementation will return a bean of the type of object you are mapping.
71 | *
72 | * @return A new instance of the class being mapped.
73 | * @throws InstantiationException Thrown on error creating object.
74 | * @throws IllegalAccessException Thrown on error creating object.
75 | */
76 | T createBean() throws InstantiationException, IllegalAccessException;
77 |
78 | /**
79 | * Implementation of this method can grab the header line before parsing
80 | * begins to use to map columns to bean properties.
81 | *
82 | * @param reader The CSVReader to use for header parsing
83 | * @throws java.io.IOException If parsing fails
84 | */
85 | void captureHeader(CSVReader reader) throws IOException;
86 |
87 | /**
88 | * Implementations of this method must return an array of column headers
89 | * based on the contents of the mapping strategy.
90 | * If no header can or should be generated, an array of zero length should
91 | * be returned, and not null.
92 | * @return An array of column names for a header
93 | * @since 3.9
94 | */
95 | String[] generateHeader();
96 |
97 | /**
98 | * Gets the column index that corresponds to a specific column name.
99 | * If the CSV file doesn't have a header row, this method will always return
100 | * null.
101 | *
102 | * @param name The column name
103 | * @return The column index, or null if the name doesn't exist
104 | */
105 | Integer getColumnIndex(String name);
106 |
107 | /**
108 | * Determines whether the mapping strategy is driven by annotations.
109 | *
110 | * @return Whether the mapping strategy is driven by annotations
111 | */
112 | boolean isAnnotationDriven();
113 | }
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/customconverter/ConvertGermanToBoolean.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean.customconverter;
17 |
18 | import com.opencsv.bean.AbstractBeanField;
19 | import com.opencsv.exceptions.CsvDataTypeMismatchException;
20 | import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
21 | import org.apache.commons.beanutils.ConversionException;
22 | import org.apache.commons.beanutils.Converter;
23 | import org.apache.commons.beanutils.converters.BooleanConverter;
24 | import org.apache.commons.lang3.StringUtils;
25 |
26 | /**
27 | * This class converts common German representations of boolean values into a
28 | * Boolean.
29 | * This class also demonstrates how to localize booleans for any other language.
30 | *
31 | * @param Type of the bean to be manipulated
32 | *
33 | * @author Andrew Rucker Jones
34 | * @since 3.8
35 | */
36 | public class ConvertGermanToBoolean extends AbstractBeanField {
37 |
38 | protected static final String WAHR = "wahr";
39 | protected static final String FALSCH = "falsch";
40 |
41 | /**
42 | * Silence code style checker by adding a useless constructor.
43 | */
44 | public ConvertGermanToBoolean() {
45 | }
46 |
47 | /**
48 | * Converts German text into a Boolean.
49 | * The comparisons are case-insensitive. The recognized pairs are
50 | * wahr/falsch, w/f, ja/nein, j/n, 1/0.
51 | *
52 | * @param value String that should represent a Boolean
53 | * @return Boolean
54 | * @throws CsvDataTypeMismatchException If anything other than the
55 | * explicitly translated pairs is found
56 | * @throws CsvRequiredFieldEmptyException Is not thrown by this
57 | * implementation. See {@link com.opencsv.bean.customconverter.ConvertGermanToBooleanRequired}.
58 | */
59 | @Override
60 | protected Object convert(String value)
61 | throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
62 | if (StringUtils.isEmpty(value)) {
63 | return null;
64 | }
65 | String[] trueStrings = {WAHR, "ja", "j", "1", "w"};
66 | String[] falseStrings = {FALSCH, "nein", "n", "0", "f"};
67 | Converter bc = new BooleanConverter(trueStrings, falseStrings);
68 | try {
69 | return bc.convert(Boolean.class, value.trim());
70 | } catch (ConversionException e) {
71 | CsvDataTypeMismatchException csve = new CsvDataTypeMismatchException(
72 | value, field.getType(), "Eingabe war kein boolischer Wert.");
73 | csve.initCause(e);
74 | throw csve;
75 | }
76 | }
77 |
78 | /**
79 | * This method takes the current value of the field in question in the bean
80 | * passed in and converts it to a string.
81 | * This implementation returns true/false values in German.
82 | *
83 | * @return "wahr" if true, "falsch" if false
84 | * @throws CsvDataTypeMismatchException If the field is not a {@code boolean}
85 | * or {@link java.lang.Boolean}
86 | * @throws CsvRequiredFieldEmptyException Not thrown by this implementation
87 | */
88 | @Override
89 | protected String convertToWrite(Object value)
90 | throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
91 | String result = "";
92 | try {
93 | if(value != null) {
94 | Boolean b = (Boolean) value;
95 | result = b?WAHR:FALSCH;
96 | }
97 | }
98 | catch(ClassCastException e) {
99 | CsvDataTypeMismatchException csve =
100 | new CsvDataTypeMismatchException("The field must be of type Boolean or boolean.");
101 | csve.initCause(e);
102 | throw csve;
103 | }
104 | return result;
105 | }
106 |
107 | }
108 |
--------------------------------------------------------------------------------
/src/main/java/com/opencsv/bean/MappingUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Andrew Rucker Jones.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.opencsv.bean;
17 |
18 | import com.opencsv.CSVReader;
19 | import com.opencsv.exceptions.CsvBeanIntrospectionException;
20 | import java.beans.IntrospectionException;
21 | import java.io.IOException;
22 | import java.io.StringReader;
23 | import java.lang.reflect.Field;
24 | import java.util.SortedSet;
25 | import java.util.TreeSet;
26 | import org.apache.commons.lang3.StringUtils;
27 | import org.apache.commons.lang3.reflect.FieldUtils;
28 |
29 | /**
30 | * This class is meant to be a collection of general purpose static methods
31 | * useful in processing mapping strategies.
32 | *
33 | * @author Andrew Rucker Jones
34 | * @since 3.9
35 | */
36 | public final class MappingUtils {
37 |
38 | /** This class can't be instantiated. */
39 | private MappingUtils() {}
40 |
41 | /**
42 | * Determines which mapping strategy is appropriate for this bean.
43 | * The algorithm is:
44 | * - If annotations {@link CsvBindByPosition} or
45 | * {@link CsvCustomBindByPosition} are present,
46 | * {@link ColumnPositionMappingStrategy} is chosen.
47 | * - Otherwise, {@link HeaderColumnNameMappingStrategy} is chosen. If
48 | * annotations are present, they will be used, otherwise the field names
49 | * will be used as the column names.
50 | *
51 | * @param The type of the bean for which the mapping strategy is sought
52 | * @param type The class of the bean for which the mapping strategy is sought
53 | * @return A functional mapping strategy for the bean in question
54 | */
55 | public static MappingStrategy determineMappingStrategy(Class type) {
56 | // Check for annotations
57 | Field[] fields = FieldUtils.getAllFields(type);
58 | boolean positionAnnotationsPresent = false;
59 | for(Field field : fields) {
60 | if(field.isAnnotationPresent(CsvBindByPosition.class)
61 | || field.isAnnotationPresent(CsvCustomBindByPosition.class)) {
62 | positionAnnotationsPresent = true;
63 | break;
64 | }
65 | if(positionAnnotationsPresent) { break; }
66 | }
67 |
68 | // Set the mapping strategy according to what we've found.
69 | MappingStrategy mappingStrategy;
70 | if(positionAnnotationsPresent) {
71 | ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
72 | ms.setType(type);
73 | mappingStrategy = ms;
74 | }
75 | else {
76 | HeaderColumnNameMappingStrategy ms = new HeaderColumnNameMappingStrategy();
77 | ms.setType(type);
78 |
79 | // Ugly hack, but I have to get the field names into the stupid
80 | // strategy somehow.
81 | if(!ms.isAnnotationDriven()) {
82 | SortedSet sortedFields = new TreeSet();
83 | for(Field f : fields) {
84 | if(!f.isSynthetic()) { // Otherwise JaCoCo breaks tests
85 | sortedFields.add(f.getName());
86 | }
87 | }
88 | String header = StringUtils.join(sortedFields, ',').concat("\n");
89 | try {
90 | ms.captureHeader(new CSVReader(new StringReader(header)));
91 | ms.findDescriptor(0);
92 | }
93 | catch(IOException e) {
94 | // Can't happen. It's a StringReader with a defined string.
95 | }
96 | catch(IntrospectionException e) {
97 | CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException("");
98 | csve.initCause(e);
99 | throw csve;
100 | }
101 | }
102 |
103 | mappingStrategy = ms;
104 | }
105 | return mappingStrategy;
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/src/test/java/com/opencsv/bean/HeaderColumnNameMappingStrategyTest.java:
--------------------------------------------------------------------------------
1 | package com.opencsv.bean;
2 |
3 | /*
4 | Copyright 2007 Kyle Miller.
5 |
6 | Licensed under the Apache License, Version 2.0 (the "License");
7 | you may not use this file except in compliance with the License.
8 | You may obtain a copy of the License at
9 |
10 | http://www.apache.org/licenses/LICENSE-2.0
11 |
12 | Unless required by applicable law or agreed to in writing, software
13 | distributed under the License is distributed on an "AS IS" BASIS,
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | See the License for the specific language governing permissions and
16 | limitations under the License.
17 | */
18 |
19 | import com.opencsv.CSVReader;
20 | import com.opencsv.bean.mocks.MockBean;
21 | import org.junit.Before;
22 | import org.junit.Test;
23 |
24 | import java.beans.IntrospectionException;
25 | import java.io.IOException;
26 | import java.io.StringReader;
27 | import java.util.List;
28 |
29 | import static org.junit.Assert.*;
30 |
31 | public class HeaderColumnNameMappingStrategyTest {
32 |
33 | private static final String TEST_STRING = "name,orderNumber,num\n" +
34 | "kyle,abc123456,123\n" +
35 | "jimmy,def098765,456";
36 |
37 | private static final String TEST_QUOTED_STRING = "\"name\",\"orderNumber\",\"num\"\n" +
38 | "\"kyle\",\"abc123456\",\"123\"\n" +
39 | "\"jimmy\",\"def098765\",\"456\"";
40 |
41 | private HeaderColumnNameMappingStrategy strat;
42 |
43 | @Before
44 | public void setUp() {
45 | strat = new HeaderColumnNameMappingStrategy();
46 | }
47 |
48 | private List createTestParseResult(String parseString) {
49 | strat.setType(MockBean.class);
50 | CsvToBean csv = new CsvToBean();
51 | return csv.parse(strat, new StringReader(parseString));
52 | }
53 |
54 | @Test(expected = IllegalStateException.class)
55 | public void getColumnIndexWithoutHeaderThrowsException() {
56 | assertNull(strat.getColumnIndex("some index name"));
57 | }
58 |
59 | @Test
60 | public void getColumnIndexAfterParse() {
61 | List list = createTestParseResult(TEST_STRING);
62 | assertEquals(0, strat.getColumnIndex("name").intValue());
63 | assertEquals(1, strat.getColumnIndex("orderNumber").intValue());
64 | assertEquals(2, strat.getColumnIndex("num").intValue());
65 | assertNull(strat.getColumnIndex("unknown column"));
66 | }
67 |
68 | @Test
69 | public void testParse() {
70 | List list = createTestParseResult(TEST_STRING);
71 | assertNotNull(list);
72 | assertTrue(list.size() == 2);
73 | MockBean bean = list.get(0);
74 | assertEquals("kyle", bean.getName());
75 | assertEquals("abc123456", bean.getOrderNumber());
76 | assertEquals(123, bean.getNum());
77 | }
78 |
79 | @Test
80 | public void testQuotedString() {
81 | List list = createTestParseResult(TEST_QUOTED_STRING);
82 | assertNotNull(list);
83 | assertTrue(list.size() == 2);
84 | MockBean bean = list.get(0);
85 | assertEquals("kyle", bean.getName());
86 | assertEquals("abc123456", bean.getOrderNumber());
87 | assertEquals(123, bean.getNum());
88 | }
89 |
90 | @Test
91 | public void testParseWithSpacesInHeader() {
92 | List list = createTestParseResult(TEST_STRING);
93 | assertNotNull(list);
94 | assertTrue(list.size() == 2);
95 | MockBean bean = list.get(0);
96 | assertEquals("kyle", bean.getName());
97 | assertEquals("abc123456", bean.getOrderNumber());
98 | assertEquals(123, bean.getNum());
99 | }
100 |
101 | @Test
102 | public void verifyColumnNames() throws IOException, IntrospectionException {
103 | HeaderColumnNameMappingStrategy strat = new HeaderColumnNameMappingStrategy();
104 | strat.setType(MockBean.class);
105 | assertNull(strat.getColumnName(0));
106 | assertNull(strat.findDescriptor(0));
107 |
108 | StringReader reader = new StringReader(TEST_STRING);
109 |
110 | CSVReader csvReader = new CSVReader(reader);
111 | strat.captureHeader(csvReader);
112 |
113 | assertEquals("name", strat.getColumnName(0));
114 | assertEquals(strat.findDescriptor(0), strat.findDescriptor("name"));
115 | assertEquals("name", strat.findDescriptor("name").getName());
116 | }
117 |
118 | @Test
119 | public void throwsIllegalStateExceptionIfTypeNotSet() throws IOException {
120 | HeaderColumnNameMappingStrategy strat = new HeaderColumnNameMappingStrategy();
121 | StringReader reader = new StringReader(TEST_STRING);
122 | CSVReader csvReader = new CSVReader(reader);
123 | CsvToBean csvtb = new CsvToBean();
124 | try {
125 | csvtb.parse(strat, csvReader);
126 | }
127 | catch(RuntimeException e) {
128 | assertEquals(IllegalStateException.class, e.getCause().getClass());
129 | }
130 | }
131 | }
132 |
--------------------------------------------------------------------------------