001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.ws.client;
015
016import org.gbif.api.annotation.PartialDate;
017
018import java.lang.annotation.Annotation;
019import java.lang.reflect.Method;
020import java.util.Collection;
021
022import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
023
024import feign.MethodMetadata;
025import feign.Util;
026
027/**
028 * Process method arguments annotated with annotation {@link PartialDate}.
029 * Should be used instead of {@link org.springframework.web.bind.annotation.RequestParam}.
030 * Only for date parameters!
031 */
032public class PartialDateParameterProcessor implements AnnotatedParameterProcessor {
033
034  private static final Class<PartialDate> ANNOTATION = PartialDate.class;
035
036  private PartialDateExpander partialDateExpander = new PartialDateExpander();
037
038  @Override
039  public Class<? extends Annotation> getAnnotationType() {
040    return ANNOTATION;
041  }
042
043  @Override
044  public boolean processArgument(
045      AnnotatedParameterContext context, Annotation annotation, Method method) {
046    int parameterIndex = context.getParameterIndex();
047    MethodMetadata data = context.getMethodMetadata();
048    PartialDate requestParam = ANNOTATION.cast(annotation);
049    String name = requestParam.value();
050
051    Util.checkState(Util.emptyToNull(name) != null, "PartialDate.value() was null");
052
053    context.setParameterName(name);
054
055    data.indexToExpander().put(parameterIndex, partialDateExpander);
056    Collection<String> query =
057        context.setTemplateParameter(name, data.template().queries().get(name));
058    data.template().query(name, query);
059
060    return true;
061  }
062}