package io.undertow.attribute;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.Cookie;
import io.undertow.server.handlers.CookieImpl;
public class RequestCookieAttribute implements ExchangeAttribute {
private static final String TOKEN_PREFIX = "%{req-cookie,";
private final String cookieName;
public RequestCookieAttribute(final String cookieName) {
this.cookieName = cookieName;
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
for (Cookie cookie : exchange.requestCookies()) {
if (cookieName.equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
exchange.setRequestCookie(new CookieImpl(cookieName, newValue));
}
@Override
public String toString() {
return TOKEN_PREFIX + cookieName + "}";
}
public static final class Builder implements ExchangeAttributeBuilder {
@Override
public String name() {
return "Request cookie";
}
@Override
public ExchangeAttribute build(final String token) {
if (token.startsWith(TOKEN_PREFIX) && token.endsWith("}")) {
final String cookieName = token.substring(TOKEN_PREFIX.length(), token.length() - 1);
return new RequestCookieAttribute(cookieName);
}
return null;
}
@Override
public int priority() {
return 0;
}
}
}