Java Code Examples for org.supercsv.prefs.CsvPreference#STANDARD_PREFERENCE

The following examples show how to use org.supercsv.prefs.CsvPreference#STANDARD_PREFERENCE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SuperCsvBOMTest.java    From super-csv with Apache License 2.0 6 votes vote down vote up
public void ReadTestCSVFile(Reader reader) throws IOException {
	ICsvBeanReader beanReader = new CsvBeanReader(reader, CsvPreference.STANDARD_PREFERENCE);
	final String[] header = beanReader.getHeader(true);
	assertEquals("customerNo", header[0]);
	CustomerBean customer = null;
	final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust!
	StrRegEx.registerMessage(emailRegex, "must be a valid email address");
	final CellProcessor[] processors = new CellProcessor[]{new UniqueHashCode(), // customerNo (must be unique)
			new NotNull(), // firstName
			new NotNull(), // lastName
			new ParseDate("dd/MM/yyyy"), // birthDate
			new ParseSqlTime("HH:mm:ss"), // birthTime
			new NotNull(), // mailingAddress
			new Optional(new ParseBool()), // married
			new Optional(new ParseInt()), // numberOfKids
			new NotNull(), // favouriteQuote
			new StrRegEx(emailRegex), // email
			new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints
	};
	customer = beanReader.read(CustomerBean.class, header, processors);
	assertEquals("1", customer.getCustomerNo());
	assertEquals("John", customer.getFirstName());
	assertEquals("[email protected]", customer.getEmail());
	assertEquals(0, customer.getLoyaltyPoints());
	beanReader.close();
}
 
Example 2
Source File: CsvTypedBeanWriterTest.java    From super-csv with Apache License 2.0 6 votes vote down vote up
@Test
public void writesTypedBeanToCsv() throws Exception {
    try (
        final StringWriter writer = new StringWriter();
        final ICsvTypedBeanWriter<CsvTypedBeanWriterTest.FakeBean> beanWriter =
            new CsvTypedBeanWriter<>(writer, CsvPreference.STANDARD_PREFERENCE)
    ) {
        final Collection<Function<FakeBean, ?>> extractors =
            Arrays.asList(
                FakeBean::bool,
                FakeBean::stringField,
                FakeBean::collection,
                FakeBean::decimal
            );
        final FakeBean bean = new FakeBean("Oh, String!", false,
            BigDecimal.TEN, Arrays.asList("Foo", "Bar", "Bazz"));
        beanWriter.writeHeader(CsvTypedBeanWriterTest.headers());
        beanWriter.write(Collections.singleton(bean), extractors);
        beanWriter.flush();
        Assert.assertEquals(
            CsvTypedBeanWriterTest.csv(CsvTypedBeanWriterTest.headers(), bean),
            writer.toString()
        );
    }
}
 
Example 3
Source File: CsvDownload.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public void download(List<T> data, String fileName, HttpServletResponse response, Class<T> clazz) throws IOException, SecurityException, NoSuchMethodException {
	String headerKey = "Content-Disposition";
	String headerValue = String.format("attachment; filename=\"%s\"", fileName);

	response.setContentType("text/csv");
	response.setHeader(headerKey, headerValue);
	
	String[] header = createHeader(clazz);
	
	ICsvDozerBeanWriter csvWriter = new CsvDozerBeanWriter(response.getWriter(), CsvPreference.STANDARD_PREFERENCE);
	csvWriter.configureBeanMapping(clazz, header);
	csvWriter.writeHeader(header);
	
	for (T t : data) {
		csvWriter.write(t);
	}
	
	csvWriter.close();
}
 
Example 4
Source File: Serialization.java    From joinery with GNU General Public License v3.0 6 votes vote down vote up
public static <V> void writeCsv(final DataFrame<V> df, final OutputStream output)
throws IOException {
    try (CsvListWriter writer = new CsvListWriter(new OutputStreamWriter(output), CsvPreference.STANDARD_PREFERENCE)) {
        final String[] header = new String[df.size()];
        final Iterator<Object> it = df.columns().iterator();
        for (int c = 0; c < df.size(); c++) {
            header[c] = String.valueOf(it.hasNext() ? it.next() : c);
        }
        writer.writeHeader(header);
        final CellProcessor[] procs = new CellProcessor[df.size()];
        final List<Class<?>> types = df.types();
        for (int c = 0; c < df.size(); c++) {
            final Class<?> cls = types.get(c);
            if (Date.class.isAssignableFrom(cls)) {
                procs[c] = new ConvertNullTo("", new FmtDate("yyyy-MM-dd'T'HH:mm:ssXXX"));
            } else {
                procs[c] = new ConvertNullTo("");
            }
        }
        for (final List<V> row : df) {
            writer.write(row, procs);
        }
    }
}
 
Example 5
Source File: CsvAnnotationBeanReaderTest.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * 全件読み込み(正常系のテスト)
 */
@Test
public void testReadAll_normal() throws IOException {
    
    File file = new File("src/test/data/test_read_normal.csv");
    
    CsvAnnotationBeanReader<SampleNormalBean> csvReader = new CsvAnnotationBeanReader<>(
            SampleNormalBean.class,
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")),
            CsvPreference.STANDARD_PREFERENCE,
            DefaultGroup.class, SampleNormalBean.ReadGroup.class);
    csvReader.setExceptionConverter(exceptionConverter);
    
    List<SampleNormalBean> list = csvReader.readAll();
    assertThat(list).hasSize(2);
    
    for(SampleNormalBean bean : list) {
        assertBean(bean);
    }
    
    assertThat(csvReader.getErrorMessages()).hasSize(0);
    
    csvReader.close();
    
}
 
Example 6
Source File: LazyCsvAnnotationBeanWriterTest.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * 初期化が完了していない場合
 */
@Test
public void testWrite_notInit() throws Exception {
    
    StringWriter strWriter = new StringWriter();
    
    LazyCsvAnnotationBeanWriter<SampleLazyBean> csvWriter = new LazyCsvAnnotationBeanWriter<>(
            SampleLazyBean.class,
            strWriter,
            CsvPreference.STANDARD_PREFERENCE);
    
    // writeメソッド
    assertThatThrownBy(() -> csvWriter.write(createNormalData().get(0)))
            .isInstanceOf(IllegalStateException.class)
            .hasMessageContaining(MESSAGE_NOT_INIT);
    
    // getDefinedHeaderメソッド
    assertThatThrownBy(() -> csvWriter.getDefinedHeader())
            .isInstanceOf(IllegalStateException.class)
            .hasMessageContaining(MESSAGE_NOT_INIT);
    
    // getBeanMappingメソッド
    assertThatThrownBy(() -> csvWriter.getBeanMapping())
            .isInstanceOf(IllegalStateException.class)
            .hasMessageContaining(MESSAGE_NOT_INIT);
    
    // writeHeaderメソッド
    assertThatThrownBy(() -> csvWriter.writeHeader())
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(MESSAGE_NOT_INIT);
    
    csvWriter.close();
}
 
Example 7
Source File: ColumnQuoteModeTest.java    From super-csv with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the quotesRequired() method with the supplied quote mode.
 * 
 * @param quoteMode
 *            the quote mode to use
 */
private void testQuotesRequired(final QuoteMode quoteMode) {
	final String input = "input";
	final CsvPreference prefs = CsvPreference.STANDARD_PREFERENCE;
	
	assertTrue(quoteMode.quotesRequired(input, new CsvContext(1, 1, 1), prefs));
	assertFalse(quoteMode.quotesRequired(input, new CsvContext(1, 1, 2), prefs));
	assertFalse(quoteMode.quotesRequired(input, new CsvContext(1, 1, 3), prefs));
	assertTrue(quoteMode.quotesRequired(input, new CsvContext(1, 1, 4), prefs));
}
 
Example 8
Source File: LazyCsvAnnotationBeanReaderTest.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * 全件読み込み - カラムにエラーがある場合
 */
@Test
public void testReadAll_error_column() throws Exception {
    
    File file = new File("src/test/data/test_read_lazy_wrong_pattern.csv");
    
    LazyCsvAnnotationBeanReader<SampleLazyBean> csvReader = new LazyCsvAnnotationBeanReader<>(
            SampleLazyBean.class,
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")),
            CsvPreference.STANDARD_PREFERENCE);
    csvReader.setExceptionConverter(exceptionConverter);
    
    try {
        List<SampleLazyBean> list = csvReader.readAll();
    
    } catch(Exception e) {
        assertThat(e).isInstanceOf(SuperCsvBindingException.class);
    }
    
    // convert error messages.
    List<String> messages = csvReader.getErrorMessages();
    assertThat(messages).hasSize(1)
        .contains("[2行, 3列] : 項目「生年月日」の値(2000-10-01)は、日時の書式「uuuu/MM/dd」として不正です。");
    messages.forEach(System.out::println);
    
    csvReader.close();
    
}
 
Example 9
Source File: CsvAnnotationBeanReaderTest.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * 全件読み込み - カラムにエラーがある
 */
@Test
public void testReadAll_error_column() throws IOException {
    
    File file = new File("src/test/data/test_read_error_wrong_pattern.csv");
    
    CsvAnnotationBeanReader<SampleNormalBean> csvReader = new CsvAnnotationBeanReader<>(
            SampleNormalBean.class,
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")),
            CsvPreference.STANDARD_PREFERENCE,
            DefaultGroup.class, SampleNormalBean.ReadGroup.class);
    csvReader.setExceptionConverter(exceptionConverter);
    
    try {
        List<SampleNormalBean> list = csvReader.readAll();
    
    } catch(Exception e) {
        assertThat(e).isInstanceOf(SuperCsvBindingException.class);
    }
    
    // convert error messages.
    List<String> messages = csvReader.getErrorMessages();
    assertThat(messages).hasSize(1)
        .contains("[2行, 6列] : 項目「date1」の値(2000/01/01 00:01:02)の書式は不正です。");
    messages.forEach(System.out::println);
    
    csvReader.close();
    
}
 
Example 10
Source File: Writing.java    From super-csv with Apache License 2.0 4 votes vote down vote up
/**
 * An example of partial reading using CsvDozerBeanWriter.
 */
private static void partialWriteWithCsvDozerBeanWriter() throws Exception {
	// ignore questionNo/answer 1 columns
	final String[] partialFieldMapping = new String[] {
			"age",
			"consentGiven",
			"answers[1].questionNo",
			"answers[1].answer",
			"answers[2].questionNo",
			"answers[2].answer" };
	
	// ignore questionNo/answer 1 columns keep up with partialFieldMapping
	final CellProcessor[] partialProcessors = new CellProcessor[] { 
		new Token(0, "age not supplied"), // age
		new FmtBool("Y", "N"),                 // consent
		new NotNull(),                         // questionNo 2
		new ConvertNullTo("not answered"),     // answer 2
		new NotNull(),                         // questionNo 3
		new ConvertNullTo("not answered")};    // answer 3
	
	// create the survey responses to write
	SurveyResponse response1 = new SurveyResponse(18, true, Arrays.asList(new Answer(1, "Twelve"), new Answer(2,
		"Albert Einstein"), new Answer(3, "Big Bang Theory")));
	SurveyResponse response2 = new SurveyResponse(0, true, Arrays.asList(new Answer(1, "Thirteen"), new Answer(2,
		"Nikola Tesla"), new Answer(3, "Stargate")));
	SurveyResponse response3 = new SurveyResponse(42, false, Arrays.asList(new Answer(1, null), new Answer(2,
		"Carl Sagan"), new Answer(3, "Star Wars")));
	final List<SurveyResponse> surveyResponses = Arrays.asList(response1, response2, response3);
	
	ICsvDozerBeanWriter beanWriter = null;
	try {
		beanWriter = new CsvDozerBeanWriter(new FileWriter("target/partialWriteWithCsvDozerBeanWriter.csv"),
			CsvPreference.STANDARD_PREFERENCE);
		
		// configure the mapping from the fields to the CSV columns
		beanWriter.configureBeanMapping(SurveyResponse.class, partialFieldMapping);
		
		// write the header
		beanWriter.writeHeader("age", "consentGiven", "questionNo2", "answer2",
			"questionNo3", "answer3");
		
		// write the beans
		for( final SurveyResponse surveyResponse : surveyResponses ) {
			beanWriter.write(surveyResponse, partialProcessors);
		}
		
	}
	finally {
		if( beanWriter != null ) {
			beanWriter.close();
		}
	}
}
 
Example 11
Source File: LazyCsvAnnotationBeanWriterTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 全て書き出す - ヘッダーを持たない設定の場合
 */
@Test
public void testWriteAll_noHeader() throws Exception {
    
    // BeanMappingの作成
    LazyBeanMappingFactory factory = new LazyBeanMappingFactory();
    BeanMapping<SampleLazyBean> beanMapping = factory.create(SampleLazyBean.class);
    
    // ヘッダーを持たない設定に変更する
    beanMapping.setHeader(false);
    
    // テストデータの作成
    final List<SampleLazyBean> list = createNormalData();
    
    StringWriter strWriter = new StringWriter();
    
    LazyCsvAnnotationBeanWriter<SampleLazyBean> csvWriter = new LazyCsvAnnotationBeanWriter<>(
            beanMapping,
            strWriter,
            CsvPreference.STANDARD_PREFERENCE);
    
    csvWriter.writeAll(list);
    
    final String[] expectedHeaders = new String[]{
            "生年月日",
            "name",
            "no",
            "備考"
            };
    
    final String[] definitionHeaders = csvWriter.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    String actual = strWriter.toString();
    System.out.println(actual);
    
    String expected = getTextFromFile("src/test/data/test_write_lazy_noSetHeader_noHeader.csv", Charset.forName("UTF-8"));
    assertThat(actual).isEqualTo(expected);
    
    assertThat(csvWriter.getErrorMessages()).hasSize(0);
    
    csvWriter.close();
    
}
 
Example 12
Source File: CsvAnnotationBeanWriterTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 書き込みのテスト - 部分的に書き込む。
 */
@Test
public void testWrite_partial() throws IOException {
    
    // テストデータの作成
    final List<SamplePartialBean> list = createPartialData();
    
    StringWriter strWriter = new StringWriter();
    
    CsvAnnotationBeanWriter<SamplePartialBean> csvWriter = new CsvAnnotationBeanWriter<>(
            SamplePartialBean.class,
            strWriter,
            CsvPreference.STANDARD_PREFERENCE,
            DefaultGroup.class, SampleNormalBean.WriteGroup.class);
    
    final String[] expectedHeaders = new String[]{
            "id",
            "数字1", "number2",
            "string1", "string2",
            "date1", "date2",
            "enum1", "列挙型2",
            "boolean1", "boolean2"};
    
    final String[] definitionHeaders = csvWriter.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    csvWriter.writeHeader();
    csvWriter.flush();
    
    for(SamplePartialBean item : list) {
        csvWriter.write(item);
        csvWriter.flush();
    }
    
    String actual = strWriter.toString();
    System.out.println(actual);
    
    String expected = getTextFromFile("src/test/data/test_write_partial.csv", Charset.forName("UTF-8"));
    assertThat(actual).isEqualTo(expected);
    
    assertThat(csvWriter.getErrorMessages()).hasSize(0);
    
    csvWriter.close();
    
}
 
Example 13
Source File: CsvAnnotationBeanReaderTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 正常系のテスト
 * @throws IOException 
 */
@Test
public void testRead_normal() throws IOException {
    
    File file = new File("src/test/data/test_read_normal.csv");
    
    CsvAnnotationBeanReader<SampleNormalBean> csvReader = new CsvAnnotationBeanReader<>(
            SampleNormalBean.class,
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")),
            CsvPreference.STANDARD_PREFERENCE,
            DefaultGroup.class, SampleNormalBean.ReadGroup.class);
    csvReader.setExceptionConverter(exceptionConverter);
    
    List<SampleNormalBean> list = new ArrayList<>();
    
    final String[] expectedHeaders = new String[]{
            "id",
            "数字1", "number2",
            "string1", "string2",
            "date1", "date2",
            "enum1", "列挙型2",
            "boolean1", "boolean2"
        };
    
    final String[] definitionHeaders = csvReader.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    // read header
    final String[] csvHeaders = csvReader.getHeader(true);
    assertThat(csvHeaders).containsExactly(expectedHeaders);
    
    SampleNormalBean bean;
    while((bean = csvReader.read()) != null) {
        list.add(bean);
        
        assertBean(bean);
    }
    
    assertThat(csvReader.getErrorMessages()).hasSize(0);
    
    csvReader.close();
    
}
 
Example 14
Source File: CsvAnnotationBeanWriterTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 書き込みのテスト - 追加書き込み
 */
@Test
public void testWriteAll_append() throws IOException {
    
    // テストデータの作成
    final List<SampleNormalBean> list = createNormalData();
    
    StringWriter strWriter = new StringWriter();
    
    CsvAnnotationBeanWriter<SampleNormalBean> csvWriter = new CsvAnnotationBeanWriter<>(
            SampleNormalBean.class,
            strWriter,
            CsvPreference.STANDARD_PREFERENCE,
            DefaultGroup.class, SampleNormalBean.WriteGroup.class);
    
    csvWriter.writeAll(list);
    csvWriter.flush();
    
    // 追加データの作成
    final List<SampleNormalBean> append = createNormalData();
    final SampleNormalBean bean3 = append.get(0);
    bean3.setId(3);
    bean3.setNumber1(-98765);
    
    final SampleNormalBean bean4 = append.get(1);
    bean4.setId(4);
    bean4.setNumber1(0);
    
    csvWriter.writeAll(append);
    csvWriter.flush();
    
    String actual = strWriter.toString();
    System.out.println(actual);
    
    String expected = getTextFromFile("src/test/data/test_write_append.csv", Charset.forName("UTF-8"));
    assertThat(actual).isEqualTo(expected);
    
    assertThat(csvWriter.getErrorMessages()).hasSize(0);
    
    csvWriter.close();
    
}
 
Example 15
Source File: Serialization.java    From joinery with GNU General Public License v3.0 4 votes vote down vote up
public static DataFrame<Object> readCsv(final InputStream input, String separator, NumberDefault numDefault, String naString, boolean hasHeader)
throws IOException {
    CsvPreference csvPreference;
    switch (separator) {
        case "\\t":
            csvPreference = CsvPreference.TAB_PREFERENCE;
            break;
        case ",":
            csvPreference = CsvPreference.STANDARD_PREFERENCE;
            break;
        case ";":
            csvPreference = CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE;
            break;
        case "|":
        	csvPreference  = new CsvPreference.Builder('"', '|', "\n").build();
            break;
        default:
            throw new IllegalArgumentException("Separator: " + separator + " is not currently supported");
    }
    try (CsvListReader reader = new CsvListReader(new InputStreamReader(input), csvPreference)) {
    	final List<String> header;
    	final DataFrame<Object> df;
    	final CellProcessor[] procs;
    	if(hasHeader) {
    		header = Arrays.asList(reader.getHeader(true));
    		procs = new CellProcessor[header.size()];
            df = new DataFrame<>(header);
    	} else {
    		// Read the first row to figure out how many columns we have
    		reader.read();
    		header = new ArrayList<String>();
    		for (int i = 0; i < reader.length(); i++) {
	header.add("V"+i);
}
    		procs = new CellProcessor[header.size()];
    		df = new DataFrame<>(header);
    		// The following line executes the procs on the previously read row again
    		df.append(reader.executeProcessors(procs));
    	}
        for (List<Object> row = reader.read(procs); row != null; row = reader.read(procs)) {
            df.append(new ArrayList<>(row));
        }
        return df.convert(numDefault, naString);
    }
}
 
Example 16
Source File: LazyCsvAnnotationBeanReaderTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 正常系のテスト
 */
@Test
public void testRead() throws IOException {
    
    File file = new File("src/test/data/test_read_lazy.csv");
    
    LazyCsvAnnotationBeanReader<SampleLazyBean> csvReader = new LazyCsvAnnotationBeanReader<>(
            SampleLazyBean.class,
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")),
            CsvPreference.STANDARD_PREFERENCE);
    csvReader.setExceptionConverter(exceptionConverter);
    
    List<SampleLazyBean> list = new ArrayList<>();
    
    final String[] expectedHeaders = new String[]{
            "no",
            "name",
            "生年月日",
            "備考"
        };
    
    // read header
    final String[] csvHeaders = csvReader.init();
    assertThat(csvHeaders).containsExactly(expectedHeaders);
    
    final String[] definitionHeaders = csvReader.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    SampleLazyBean bean;
    while((bean = csvReader.read()) != null) {
        list.add(bean);
        
        assertBean(bean);
    }
    
    assertThat(list).hasSize(2);
    assertThat(csvReader.getErrorMessages()).hasSize(0);
    
    csvReader.close();
    
}
 
Example 17
Source File: LazyCsvAnnotationBeanReaderTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 部分的にカラムを読み込む
 */
@Test
public void testRead_parital() throws Exception {
    
    File file = new File("src/test/data/test_read_lazy_partial.csv");
    
    LazyCsvAnnotationBeanReader<SampleLazyPartialBean> csvReader = new LazyCsvAnnotationBeanReader<>(
            SampleLazyPartialBean.class,
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")),
            CsvPreference.STANDARD_PREFERENCE);
    csvReader.setExceptionConverter(exceptionConverter);
    
    List<SampleLazyPartialBean> list = new ArrayList<>();
    
    final String[] expectedHeaders = new String[]{
            "id",
            "名前",
            "誕生日",
            "電話番号",
            "住所",
            "有効期限",
            "削除フラグ",
            "備考"
        };
    
    // read header
    final String[] csvHeaders = csvReader.init();
    assertThat(csvHeaders).containsExactly(expectedHeaders);
    
    final String[] definitionHeaders = csvReader.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    {
        // カラム情報のチェック
        List<ColumnMapping> columnMappingList = csvReader.getBeanMapping().getColumns();
        assertThat(columnMappingList).hasSize(8);
        for(int i=0; i < columnMappingList.size(); i++) {
            int number = i+1;
            ColumnMapping columnMapping = columnMappingList.get(i);
            assertThat(columnMapping.getNumber()).isEqualTo(number);
            assertThat(columnMapping.getLabel()).isEqualTo(expectedHeaders[i]);
            assertThat(columnMapping.isDeterminedNumber()).isEqualTo(true);
            
            if(number == 1 || number == 2 || number == 6 || number == 8) {
                assertThat(columnMapping.isPartialized()).isEqualTo(false);
            } else {
                assertThat(columnMapping.isPartialized()).isEqualTo(true);
                
            }
        }
    }
    
    SampleLazyPartialBean bean;
    while((bean = csvReader.read()) != null) {
        list.add(bean);
        
        assertBean(bean);
    }
    
    assertThat(list).hasSize(3);
    assertThat(csvReader.getErrorMessages()).hasSize(0);
    
    csvReader.close();
    
    
}
 
Example 18
Source File: LazyCsvAnnotationBeanWriterTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 書き込みのテスト
 * ・ヘッダーの指定あり
 */
@Test
public void testWrite_setHeaders() throws Exception {
    
    // テストデータの作成
    final List<SampleLazyBean> list = createNormalData();
    
    StringWriter strWriter = new StringWriter();
    
    LazyCsvAnnotationBeanWriter<SampleLazyBean> csvWriter = new LazyCsvAnnotationBeanWriter<>(
            SampleLazyBean.class,
            strWriter,
            CsvPreference.STANDARD_PREFERENCE);
    
    csvWriter.init("no", "name", "生年月日", "備考");
    
    final String[] expectedHeaders = new String[]{
            "no",
            "name",
            "生年月日",
            "備考"
            };
    
    final String[] definitionHeaders = csvWriter.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    csvWriter.writeHeader();
    csvWriter.flush();
    
    for(SampleLazyBean item : list) {
        csvWriter.write(item);
        csvWriter.flush();
    }
    
    String actual = strWriter.toString();
    System.out.println(actual);
    
    String expected = getTextFromFile("src/test/data/test_write_lazy_setHeader.csv", Charset.forName("UTF-8"));
    assertThat(actual).isEqualTo(expected);
    
    assertThat(csvWriter.getErrorMessages()).hasSize(0);
    
    csvWriter.close();
}
 
Example 19
Source File: LazyCsvAnnotationBeanWriterTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 部分的な書き込み - ヘッダーの指定なし
 */
@Test
public void testWrite_partial_noSetHeader() throws Exception {
    
    // テストデータの作成
    final List<SampleLazyPartialBean> list = createPartialData();
    
    StringWriter strWriter = new StringWriter();
    
    LazyCsvAnnotationBeanWriter<SampleLazyPartialBean> csvWriter = new LazyCsvAnnotationBeanWriter<>(
            SampleLazyPartialBean.class,
            strWriter,
            CsvPreference.STANDARD_PREFERENCE);
    
    final String[] expectedHeaders = new String[]{
            "id",
            "備考",
            "誕生日",
            "名前",
            "住所",
            "有効期限",
            "column7",
            "column8",
        };
    
    csvWriter.init();
    
    final String[] definitionHeaders = csvWriter.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    {
        // カラム情報のチェック
        List<ColumnMapping> columnMappingList = csvWriter.getBeanMapping().getColumns();
        assertThat(columnMappingList).hasSize(8);
        for(int i=0; i < columnMappingList.size(); i++) {
            int number = i+1;
            ColumnMapping columnMapping = columnMappingList.get(i);
            assertThat(columnMapping.getNumber()).isEqualTo(number);
            assertThat(columnMapping.getLabel()).isEqualTo(expectedHeaders[i]);
            assertThat(columnMapping.isDeterminedNumber()).isEqualTo(true);
            
            if(number == 1 || number == 2 || number == 4 || number == 6) {
                assertThat(columnMapping.isPartialized()).isEqualTo(false);
            } else {
                assertThat(columnMapping.isPartialized()).isEqualTo(true);
                
            }
        }
    }
    
    csvWriter.writeHeader();
    
    for(SampleLazyPartialBean item : list) {
        csvWriter.write(item);
        csvWriter.flush();
    }
    
    String actual = strWriter.toString();
    System.out.println(actual);
    
    String expected = getTextFromFile("src/test/data/test_write_lazy_partial_noSetHeader.csv", Charset.forName("UTF-8"));
    assertThat(actual).isEqualTo(expected);
    
    assertThat(csvWriter.getErrorMessages()).hasSize(0);
    
    csvWriter.close();
    
}
 
Example 20
Source File: CsvAnnotationBeanWriterTest.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 書き込みのテスト - 正常
 */
@Test
public void testWrite_normal() throws IOException {
    
    // テストデータの作成
    final List<SampleNormalBean> list = createNormalData();
    
    StringWriter strWriter = new StringWriter();
    
    CsvAnnotationBeanWriter<SampleNormalBean> csvWriter = new CsvAnnotationBeanWriter<>(
            SampleNormalBean.class,
            strWriter,
            CsvPreference.STANDARD_PREFERENCE,
            DefaultGroup.class, SampleNormalBean.WriteGroup.class);
    
    final String[] expectedHeaders = new String[]{
            "id",
            "数字1", "number2",
            "string1", "string2",
            "date1", "date2",
            "enum1", "列挙型2",
            "boolean1", "boolean2"};
    
    final String[] definitionHeaders = csvWriter.getDefinedHeader();
    assertThat(definitionHeaders).containsExactly(expectedHeaders);
    
    csvWriter.writeHeader();
    csvWriter.flush();
    
    for(SampleNormalBean item : list) {
        csvWriter.write(item);
        csvWriter.flush();
    }
    
    String actual = strWriter.toString();
    System.out.println(actual);
    
    String expected = getTextFromFile("src/test/data/test_write_normal.csv", Charset.forName("UTF-8"));
    assertThat(actual).isEqualTo(expected);
    
    assertThat(csvWriter.getErrorMessages()).hasSize(0);
    
    csvWriter.close();
    
}