2 * Copyright © 2016-2018 European Support Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.openecomp.sdc.logging.servlet;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.List;
22 import java.util.Objects;
23 import java.util.Optional;
24 import java.util.function.Function;
27 * Handles any of possible header names to read a value for that header. This is useful for backward compatibility, if
28 * multiple headers may have the same meaning. For instance, when requests come from multiple service, some using an old
29 * header and others using a new header to pass the same information.
34 public class HttpHeader {
36 private static final String NAMES_CANNOT_BE_NULL = "Names cannot be null";
37 private static final String AT_LEAST_ONE_NAME_REQUIRED = "At least one name required";
39 private final List<String> headerNames;
42 * Receives a list of accepted header names as a String array.
44 * @param headerNames cannot be null or empty
46 public HttpHeader(String[] headerNames) {
48 if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).length < 1) {
49 throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED);
52 this.headerNames = Arrays.asList(headerNames);
56 * Receives a list of accepted header names as a list of String.
58 * @param headerNames cannot be null or empty
60 public HttpHeader(List<String> headerNames) {
62 if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).isEmpty()) {
63 throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED);
66 this.headerNames = new ArrayList<>(headerNames);
70 * Returns the value of any of the possible headers.
72 * @param reader function for reading an HTTP header.
73 * @return value or empty if not found
75 public Optional<String> getAny(Function<String, String> reader) {
77 for (String k : headerNames) {
79 String value = reader.apply(k);
81 return Optional.of(value);
85 return Optional.empty();
89 public boolean equals(Object o) {
95 if (o == null || getClass() != o.getClass()) {
99 HttpHeader that = (HttpHeader) o;
100 return Objects.equals(headerNames, that.headerNames);
104 public int hashCode() {
105 return Objects.hash(headerNames);
109 public String toString() {
110 return "HttpHeader{headerNames=" + headerNames + '}';