package io.undertow.predicate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import io.undertow.attribute.ExchangeAttribute;
import io.undertow.server.HttpServerExchange;
public class EqualsPredicate implements Predicate {
private final ExchangeAttribute[] attributes;
EqualsPredicate(final ExchangeAttribute[] attributes) {
this.attributes = attributes;
}
@Override
public boolean resolve(final HttpServerExchange value) {
if(attributes.length < 2) {
return true;
}
String first = attributes[0].readAttribute(value);
for(int i = 1; i < attributes.length; ++i) {
String current = attributes[i].readAttribute(value);
if(first == null) {
if(current != null) {
return false;
}
} else if(current == null) {
return false;
} else if(!first.equals(current)) {
return false;
}
}
return true;
}
@Override
public String toString() {
return "equals( {" + Arrays.asList( attributes ).stream().map(a->a.toString()).collect(Collectors.joining(", ")) + "} )";
}
public static class Builder implements PredicateBuilder {
@Override
public String name() {
return "equals";
}
@Override
public Map<String, Class<?>> parameters() {
final Map<String, Class<?>> params = new HashMap<>();
params.put("value", ExchangeAttribute[].class);
return params;
}
@Override
public Set<String> requiredParameters() {
return Collections.singleton("value");
}
@Override
public String defaultParameter() {
return "value";
}
@Override
public Predicate build(final Map<String, Object> config) {
ExchangeAttribute[] value = (ExchangeAttribute[]) config.get("value");
return new EqualsPredicate(value);
}
}
}