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.
16 package org.openecomp.sdc.logging.servlet;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.List;
21 import java.util.Objects;
22 import java.util.Optional;
23 import java.util.function.Function;
26 * Handles any of possible header names to read a value for that header. This is useful for backward compatibility, if multiple headers may have the
27 * same meaning. For instance, when requests come from multiple service, some using an old header and others using a new header to pass the same
33 public class HttpHeader {
35 private static final String NAMES_CANNOT_BE_NULL = "Names cannot be null";
36 private static final String AT_LEAST_ONE_NAME_REQUIRED = "At least one name required";
37 private final List<String> headerNames;
40 * Receives a list of accepted header names as a String array.
42 * @param headerNames cannot be null or empty
44 public HttpHeader(String... headerNames) {
45 if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).length < 1) {
46 throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED);
48 this.headerNames = Arrays.asList(headerNames);
52 * Receives a list of accepted header names as a list of String.
54 * @param headerNames cannot be null or empty
56 public HttpHeader(List<String> headerNames) {
57 if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).isEmpty()) {
58 throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED);
60 this.headerNames = new ArrayList<>(headerNames);
64 * Returns the value of any of the possible headers.
66 * @param reader function for reading an HTTP header.
67 * @return value or empty if not found
69 public Optional<String> getAny(Function<String, String> reader) {
70 for (String k : headerNames) {
71 String value = reader.apply(k);
73 return Optional.of(value);
76 return Optional.empty();
80 public boolean equals(Object o) {
84 if (o == null || getClass() != o.getClass()) {
87 HttpHeader that = (HttpHeader) o;
88 return Objects.equals(headerNames, that.headerNames);
92 public int hashCode() {
93 return Objects.hash(headerNames);
97 public String toString() {
98 return "HttpHeader{headerNames=" + headerNames + '}';