001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.matcher;
018
019import static org.apache.juneau.common.utils.StringUtils.*;
020import static org.apache.juneau.rest.annotation.RestOpAnnotation.*;
021
022import org.apache.juneau.*;
023import org.apache.juneau.common.utils.*;
024import org.apache.juneau.internal.*;
025import org.apache.juneau.reflect.*;
026
027import jakarta.servlet.http.*;
028
029/**
030 * Specialized matcher for matching client versions.
031 *
032 * <h5 class='section'>See Also:</h5><ul>
033 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ClientVersioning">Client Versioning</a>
034 * </ul>
035 */
036public class ClientVersionMatcher extends RestMatcher {
037
038   private final String clientVersionHeader;
039   private final VersionRange range;
040
041   /**
042    * Constructor.
043    *
044    * @param clientVersionHeader
045    *    The HTTP request header name containing the client version.
046    *    If <jk>null</jk> or an empty string, uses <js>"Client-Version"</js>
047    * @param mi The version string that the client version must match.
048    */
049   public ClientVersionMatcher(String clientVersionHeader, MethodInfo mi) {
050      this.clientVersionHeader = Utils.isEmpty(clientVersionHeader) ? "Client-Version" : clientVersionHeader;
051      Value<String> clientVersion = Value.empty();
052      mi.getAnnotationList(REST_OP_GROUP).forEachValue(String.class, "clientVersion", NOT_EMPTY, x -> clientVersion.set(x));
053      range = new VersionRange(clientVersion.orElse(null));
054   }
055
056   @Override /* RestMatcher */
057   public boolean matches(HttpServletRequest req) {
058      return range.matches(req.getHeader(clientVersionHeader));
059   }
060
061   @Override /* RestMatcher */
062   public boolean required() {
063      return true;
064   }
065}