// --------------------------------------------- Methods from Filter
@Override
public NextAction handleRead(final FilterChainContext ctx) throws IOException {
final Connection connection = ctx.getConnection();
final HttpContent httpContent = ctx.getMessage();
final HttpRequestPacket request = (HttpRequestPacket) httpContent.getHttpHeader();
final URI requestURI;
try {
final String uri = request.getQueryString() == null ?
request.getRequestURI() :
request.getRequestURI() + "?" + request.getQueryString();
requestURI = new URI(uri);
} catch (URISyntaxException ignored) {
return ctx.getStopAction();
}
final boolean redirectToSecure;
if (secure != null) { // if secure is set - we use it
redirectToSecure = secure;
} else { // if secure is not set - use secure settings opposite to the current request
final SSLEngine sslEngine = SSLUtils.getSSLEngine(connection);
redirectToSecure = sslEngine == null;
}
final StringBuilder hostPort = new StringBuilder();
String hostHeader = request.getHeader("host");
if (hostHeader == null) {
String hostRequestURI = requestURI.getHost();
if (hostRequestURI == null) {
hostPort.append(request.getLocalHost());
} else {
hostPort.append(hostRequestURI);
}
hostPort.append(':');
if (redirectPort == null) {
int port = requestURI.getPort();
if (port == -1) {
hostPort.append(request.getLocalPort());
} else {
hostPort.append(port);
}
} else {
hostPort.append(redirectPort);
}
} else if (redirectPort != null) { // if port is specified - cut it from host header
final int colonIdx = hostHeader.indexOf(':');
if (colonIdx != -1) {
hostHeader = hostHeader.substring(0, colonIdx);
}
hostPort.append(hostHeader)
.append(':')
.append(redirectPort);
} else {
hostPort.append(hostHeader);
}
if (hostPort.length() > 0) {
String path = requestURI.toString();
assert path != null;
final StringBuilder sb = new StringBuilder();
sb.append((redirectToSecure ? "https://" : "http://"))
.append(hostPort)
.append(path);
request.setSkipRemainder(true);
final HttpResponsePacket response = HttpResponsePacket.builder(request)
.status(302)
.header("Location", sb.toString())
.contentLength(0)
.build();
ctx.write(response);
} else {
connection.closeSilently();
}
return ctx.getStopAction();
}