View Javadoc
1   package com.github.mygreen.supercsv.cellprocessor.conversion;
2   
3   import org.supercsv.cellprocessor.CellProcessorAdaptor;
4   import org.supercsv.cellprocessor.ift.StringCellProcessor;
5   import org.supercsv.util.CsvContext;
6   
7   /**
8    * 文字列を切り詰めるCellProcessor
9    *
10   * @since 2.0
11   * @author T.TSUCHIE
12   *
13   */
14  public class Truncate extends CellProcessorAdaptor implements StringCellProcessor{
15      
16      private final int maxSize;
17      private final String suffix;
18      
19      public Truncate(final int maxSize, final String suffix) {
20          super();
21          checkPreconditions(maxSize, suffix);
22          this.maxSize = maxSize;
23          this.suffix = suffix;
24      }
25      
26      public Truncate(final int maxSize, final String suffix, final StringCellProcessor next) {
27          super(next);
28          checkPreconditions(maxSize, suffix);
29          this.maxSize = maxSize;
30          this.suffix = suffix;
31      }
32      
33      private static void checkPreconditions(final int maxSize, final String suffix) {
34          if( maxSize <= 0 ) {
35              throw new IllegalArgumentException(String.format("maxSize should be > 0 but was %d", maxSize));
36          }
37          
38          if( suffix == null ) {
39              throw new NullPointerException("suffix should not be null");
40          }
41      }
42      
43      @Override
44      public <T> T execute(final Object value, final CsvContext context) {
45          if(value == null) {
46              return next.execute(value, context);
47          }
48          
49          final String stringValue = value.toString();
50          final String result;
51          if(stringValue.length() <= maxSize) {
52              result = stringValue;
53          } else {
54              result = stringValue.substring(0, maxSize) + suffix;
55          }
56          
57          return next.execute(result, context);
58          
59      }
60      
61      /**
62       * 最大文字長を取得する。
63       * @return 最大文字長
64       */
65      public int getMaxSize() {
66          return maxSize;
67      }
68      
69      /**
70       * 接尾語を取得する
71       * @return 接尾語
72       */
73      public String getSuffix() {
74          return suffix;
75      }
76      
77  }