1 package com.github.mygreen.supercsv.io;
2
3 import java.util.function.Supplier;
4
5 import org.supercsv.encoder.CsvEncoder;
6 import org.supercsv.prefs.CsvPreference;
7 import org.supercsv.util.CsvContext;
8
9 import com.github.mygreen.supercsv.builder.BeanMapping;
10 import com.github.mygreen.supercsv.builder.FixedSizeColumnProperty;
11 import com.github.mygreen.supercsv.exception.SuperCsvFixedSizeException;
12
13
14
15
16
17
18
19
20
21
22
23
24 public class FixedSizeCsvEncoder<T> implements CsvEncoder {
25
26
27
28
29
30 private final Supplier<BeanMapping<T>> beanMappingSupplier;
31
32
33
34
35
36
37
38 public FixedSizeCsvEncoder(Supplier<BeanMapping<T>> beanMappingSupplier) {
39 this.beanMappingSupplier = beanMappingSupplier;
40 }
41
42
43
44
45
46
47
48
49
50 private FixedSizeColumnProperty getColumnProperty(int columnNumber) {
51 BeanMapping<T> beanMapping = beanMappingSupplier.get();
52 return beanMapping.getColumnMapping(columnNumber)
53 .orElseThrow(() -> new IllegalStateException("columnMappings not found with columnNumber=" + columnNumber))
54 .getFixedSizeProperty();
55 }
56
57
58
59
60
61
62 @Override
63 public String encode(final String input, final CsvContext context, final CsvPreference preference) {
64
65 FixedSizeColumnProperty fixedSizeProperty = getColumnProperty(context.getColumnNumber());
66
67
68
69
70
71 int actualSize = fixedSizeProperty.getPaddingProcessor().count(input);
72 if (actualSize > fixedSizeProperty.getSize()) {
73 throw new SuperCsvFixedSizeException.Builder("csvError.fixedSizeOver", context)
74 .messageFormat("Over column size. fixedColumnSize: %d, actualSize: %d",
75 fixedSizeProperty.getSize(), actualSize)
76 .messageVariables("fixedColumnSize", fixedSizeProperty.getSize())
77 .messageVariables("actualSize", actualSize)
78 .messageVariables("validatedValue", input)
79 .build();
80 }
81
82
83
84
85
86 if (input.contains("\r") || input.contains("\n")) {
87 throw new SuperCsvFixedSizeException.Builder("csvError.fixedSizeContainsLineBreak", context)
88 .messageFormat("Contains line break. input: [%s]", input)
89 .messageVariables("validatedValue", input)
90 .build();
91 }
92
93
94 return input;
95 }
96 }