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.server.provider;
015
016import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
017import org.gbif.api.model.occurrence.search.OccurrenceSearchRequest;
018
019import java.util.Optional;
020
021import org.springframework.core.MethodParameter;
022import org.springframework.web.bind.support.WebDataBinderFactory;
023import org.springframework.web.context.request.NativeWebRequest;
024import org.springframework.web.context.request.WebRequest;
025import org.springframework.web.method.support.HandlerMethodArgumentResolver;
026import org.springframework.web.method.support.ModelAndViewContainer;
027
028public class OccurrenceSearchRequestHandlerMethodArgumentResolver
029    extends FacetedSearchRequestProvider<OccurrenceSearchRequest, OccurrenceSearchParameter>
030    implements HandlerMethodArgumentResolver {
031
032  private static final String MATCH_CASE_PARAM = "matchCase";
033  private static final String SHUFFLE_PARAM = "shuffle";
034
035  public OccurrenceSearchRequestHandlerMethodArgumentResolver() {
036    super(OccurrenceSearchRequest.class, OccurrenceSearchParameter.class);
037  }
038
039  @Override
040  public boolean supportsParameter(MethodParameter parameter) {
041    return OccurrenceSearchRequest.class.equals(parameter.getParameterType());
042  }
043
044  @Override
045  public Object resolveArgument(
046      MethodParameter parameter,
047      ModelAndViewContainer mavContainer,
048      NativeWebRequest webRequest,
049      WebDataBinderFactory binderFactory) {
050    return getValue(webRequest);
051  }
052
053  @Override
054  protected OccurrenceSearchRequest getSearchRequest(
055      WebRequest webRequest, OccurrenceSearchRequest searchRequest) {
056    OccurrenceSearchRequest occurrenceSearchRequest =
057        super.getSearchRequest(webRequest, searchRequest);
058    Optional.ofNullable(webRequest.getParameter(MATCH_CASE_PARAM))
059        .ifPresent(
060            matchVerbatim ->
061                occurrenceSearchRequest.setMatchCase(Boolean.parseBoolean(matchVerbatim)));
062
063    Optional.ofNullable(webRequest.getParameter(SHUFFLE_PARAM))
064        .ifPresent(occurrenceSearchRequest::setShuffle);
065
066    return occurrenceSearchRequest;
067  }
068}