View Javadoc
1   /*
2    * Copyright 2018 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.AbstractCsvConverter;
19  import com.opencsv.bean.mocks.join.ErrorCode;
20  
21  import java.util.MissingResourceException;
22  import java.util.ResourceBundle;
23  
24  /**
25   * This is a perfectly terrible converter, full of bugs and such, but for
26   * simple tests, I just don't care.
27   * And yes, it is also a contestant for a conversion to and from the worst
28   * data representation ever.
29   */
30  public class ErrorCodeConverter extends AbstractCsvConverter {
31  
32      private ResourceBundle res;
33  
34      @Override
35      public void setLocale(String locale) {
36          super.setLocale(locale);
37          if(this.locale != null) {
38              res = ResourceBundle.getBundle("collectionconverter", this.locale);
39          }
40          else {
41              res = ResourceBundle.getBundle("collectionconverter");
42          }
43      }
44  
45      @Override
46      public Object convertToRead(String value) {
47          ErrorCode ec = new ErrorCode();
48          ec.errorCode = Integer.parseInt(value.substring(0, 2));
49          try {
50              ec.errorMessage = res.getString(value.substring(2));
51          }
52          catch(MissingResourceException e) {
53              ec.errorMessage = value.substring(2);
54          }
55  
56          return ec;
57      }
58  
59      @Override
60      public String convertToWrite(Object value) {
61          ErrorCode ec = (ErrorCode) value;
62          StringBuilder sb = new StringBuilder();
63          sb.append(ec.errorCode);
64          sb.append("default.error");
65          return sb.toString();
66      }
67  }