001/*
002 * Copyright 2002-2020 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.reactive.result.condition;
018
019import java.util.Collection;
020import java.util.Collections;
021import java.util.LinkedHashSet;
022import java.util.Set;
023
024import org.springframework.lang.Nullable;
025import org.springframework.util.ObjectUtils;
026import org.springframework.web.bind.annotation.RequestMapping;
027import org.springframework.web.cors.reactive.CorsUtils;
028import org.springframework.web.server.ServerWebExchange;
029
030/**
031 * A logical conjunction (' && ') request condition that matches a request against
032 * a set of header expressions with syntax defined in {@link RequestMapping#headers()}.
033 *
034 * <p>Expressions passed to the constructor with header names 'Accept' or
035 * 'Content-Type' are ignored. See {@link ConsumesRequestCondition} and
036 * {@link ProducesRequestCondition} for those.
037 *
038 * @author Rossen Stoyanchev
039 * @since 5.0
040 */
041public final class HeadersRequestCondition extends AbstractRequestCondition<HeadersRequestCondition> {
042
043        private static final HeadersRequestCondition PRE_FLIGHT_MATCH = new HeadersRequestCondition();
044
045
046        private final Set<HeaderExpression> expressions;
047
048
049        /**
050         * Create a new instance from the given header expressions. Expressions with
051         * header names 'Accept' or 'Content-Type' are ignored. See {@link ConsumesRequestCondition}
052         * and {@link ProducesRequestCondition} for those.
053         * @param headers media type expressions with syntax defined in {@link RequestMapping#headers()};
054         * if 0, the condition will match to every request
055         */
056        public HeadersRequestCondition(String... headers) {
057                this.expressions = parseExpressions(headers);
058        }
059
060        private static Set<HeaderExpression> parseExpressions(String... headers) {
061                Set<HeaderExpression> result = null;
062                if (!ObjectUtils.isEmpty(headers)) {
063                        for (String header : headers) {
064                                HeaderExpression expr = new HeaderExpression(header);
065                                if ("Accept".equalsIgnoreCase(expr.name) || "Content-Type".equalsIgnoreCase(expr.name)) {
066                                        continue;
067                                }
068                                result = (result != null ? result : new LinkedHashSet<>(headers.length));
069                                result.add(expr);
070                        }
071                }
072                return (result != null ? result : Collections.emptySet());
073        }
074
075        private HeadersRequestCondition(Set<HeaderExpression> conditions) {
076                this.expressions = conditions;
077        }
078
079
080        /**
081         * Return the contained request header expressions.
082         */
083        public Set<NameValueExpression<String>> getExpressions() {
084                return new LinkedHashSet<>(this.expressions);
085        }
086
087        @Override
088        protected Collection<HeaderExpression> getContent() {
089                return this.expressions;
090        }
091
092        @Override
093        protected String getToStringInfix() {
094                return " && ";
095        }
096
097        /**
098         * Returns a new instance with the union of the header expressions
099         * from "this" and the "other" instance.
100         */
101        @Override
102        public HeadersRequestCondition combine(HeadersRequestCondition other) {
103                if (isEmpty() && other.isEmpty()) {
104                        return this;
105                }
106                else if (other.isEmpty()) {
107                        return this;
108                }
109                else if (isEmpty()) {
110                        return other;
111                }
112                Set<HeaderExpression> set = new LinkedHashSet<>(this.expressions);
113                set.addAll(other.expressions);
114                return new HeadersRequestCondition(set);
115        }
116
117        /**
118         * Returns "this" instance if the request matches all expressions;
119         * or {@code null} otherwise.
120         */
121        @Override
122        @Nullable
123        public HeadersRequestCondition getMatchingCondition(ServerWebExchange exchange) {
124                if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
125                        return PRE_FLIGHT_MATCH;
126                }
127                for (HeaderExpression expression : this.expressions) {
128                        if (!expression.match(exchange)) {
129                                return null;
130                        }
131                }
132                return this;
133        }
134
135        /**
136         * Compare to another condition based on header expressions. A condition
137         * is considered to be a more specific match, if it has:
138         * <ol>
139         * <li>A greater number of expressions.
140         * <li>A greater number of non-negated expressions with a concrete value.
141         * </ol>
142         * <p>It is assumed that both instances have been obtained via
143         * {@link #getMatchingCondition(ServerWebExchange)} and each instance
144         * contains the matching header expression only or is otherwise empty.
145         */
146        @Override
147        public int compareTo(HeadersRequestCondition other, ServerWebExchange exchange) {
148                int result = other.expressions.size() - this.expressions.size();
149                if (result != 0) {
150                        return result;
151                }
152                return (int) (getValueMatchCount(other.expressions) - getValueMatchCount(this.expressions));
153        }
154
155        private long getValueMatchCount(Set<HeaderExpression> expressions) {
156                long count = 0;
157                for (HeaderExpression e : expressions) {
158                        if (e.getValue() != null && !e.isNegated()) {
159                                count++;
160                        }
161                }
162                return count;
163        }
164
165
166        /**
167         * Parses and matches a single header expression to a request.
168         */
169        static class HeaderExpression extends AbstractNameValueExpression<String> {
170
171                public HeaderExpression(String expression) {
172                        super(expression);
173                }
174
175                @Override
176                protected boolean isCaseSensitiveName() {
177                        return false;
178                }
179
180                @Override
181                protected String parseValue(String valueExpression) {
182                        return valueExpression;
183                }
184
185                @Override
186                protected boolean matchName(ServerWebExchange exchange) {
187                        return (exchange.getRequest().getHeaders().get(this.name) != null);
188                }
189
190                @Override
191                protected boolean matchValue(ServerWebExchange exchange) {
192                        return (this.value != null && this.value.equals(exchange.getRequest().getHeaders().getFirst(this.name)));
193                }
194        }
195
196}