package org.apache.tomcat.util.http;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.parser.TokenList;
public class ResponseUtil {
private static final String = "vary";
private static final String VARY_ALL = "*";
private ResponseUtil() {
}
public static void (MimeHeaders headers, String name) {
addVaryFieldName(new HeaderAdapter(headers), name);
}
public static void addVaryFieldName(HttpServletResponse response, String name) {
addVaryFieldName(new ResponseAdapter(response), name);
}
private static void addVaryFieldName(Adapter adapter, String name) {
Collection<String> varyHeaders = adapter.getHeaders(VARY_HEADER);
if (varyHeaders.size() == 1 && varyHeaders.iterator().next().trim().equals(VARY_ALL)) {
return;
}
if (varyHeaders.size() == 0) {
adapter.addHeader(VARY_HEADER, name);
return;
}
if (VARY_ALL.equals(name.trim())) {
adapter.setHeader(VARY_HEADER, VARY_ALL);
return;
}
LinkedHashSet<String> fieldNames = new LinkedHashSet<>();
for (String varyHeader : varyHeaders) {
StringReader input = new StringReader(varyHeader);
try {
TokenList.parseTokenList(input, fieldNames);
} catch (IOException ioe) {
}
}
if (fieldNames.contains(VARY_ALL)) {
adapter.setHeader(VARY_HEADER, VARY_ALL);
return;
}
fieldNames.add(name);
StringBuilder varyHeader = new StringBuilder();
Iterator<String> iter = fieldNames.iterator();
varyHeader.append(iter.next());
while (iter.hasNext()) {
varyHeader.append(',');
varyHeader.append(iter.next());
}
adapter.setHeader(VARY_HEADER, varyHeader.toString());
}
private static interface Adapter {
Collection<String> (String name);
void (String name, String value);
void (String name, String value);
}
private static final class implements Adapter {
private final MimeHeaders ;
public (MimeHeaders headers) {
this.headers = headers;
}
@Override
public Collection<String> (String name) {
Enumeration<String> values = headers.values(name);
List<String> result = new ArrayList<>();
while (values.hasMoreElements()) {
result.add(values.nextElement());
}
return result;
}
@Override
public void (String name, String value) {
headers.setValue(name).setString(value);
}
@Override
public void (String name, String value) {
headers.addValue(name).setString(value);
}
}
private static final class ResponseAdapter implements Adapter {
private final HttpServletResponse response;
public ResponseAdapter(HttpServletResponse response) {
this.response = response;
}
@Override
public Collection<String> (String name) {
return response.getHeaders(name);
}
@Override
public void (String name, String value) {
response.setHeader(name, value);
}
@Override
public void (String name, String value) {
response.addHeader(name, value);
}
}
}