View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    *     http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package org.gbif.ws.client;
15  
16  import java.text.ParseException;
17  import java.text.SimpleDateFormat;
18  import java.util.Date;
19  
20  import org.slf4j.Logger;
21  import org.slf4j.LoggerFactory;
22  
23  import feign.Param;
24  
25  /**
26   * Convert date string from the default {@link Date} format to custom 'yyyy-MM'.
27   */
28  public class PartialDateExpander implements Param.Expander {
29  
30    private static final Logger LOG = LoggerFactory.getLogger(PartialDateExpander.class);
31  
32    private static final String UTIL_DATE_FORMAT_PATTERN = "EEE MMM dd HH:mm:ss zzz yyyy";
33    private static final String CUSTOM_DATE_FORMAT_PATTERN = "yyyy-MM";
34  
35    @Override
36    public String expand(Object value) {
37      return convertDate(value);
38    }
39  
40    private String convertDate(Object rawDate) {
41      Date utilDate;
42  
43      try {
44        utilDate = new SimpleDateFormat(UTIL_DATE_FORMAT_PATTERN).parse(rawDate.toString());
45      } catch (ParseException e) {
46        LOG.error("Wrong date format {}. Expected format: {}", rawDate, UTIL_DATE_FORMAT_PATTERN);
47        return null;
48      }
49  
50      return new SimpleDateFormat(CUSTOM_DATE_FORMAT_PATTERN).format(utilDate);
51    }
52  }