Skip to content

Instantly share code, notes, and snippets.

@SharkFourSix
Last active July 2, 2019 15:15
Show Gist options
  • Save SharkFourSix/1d176fcf535b86fd54921f2b897f54e0 to your computer and use it in GitHub Desktop.
Save SharkFourSix/1d176fcf535b86fd54921f2b897f54e0 to your computer and use it in GitHub Desktop.
Spark Java HTTP to HTTPS redirector
import java.io.Closeable;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public final class HttpsRedirector {
private final ServerSocketChannel server;
private final Selector selector;
private final byte[] redirectResponseHeaders;
public HttpsRedirector(int http_port, String https_url) throws Exception {
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.bind(new InetSocketAddress(http_port));
selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
redirectResponseHeaders = ("HTTP/1.1 301 Moved Permanently\r\nLocation: " + https_url + "\r\n\r\n").getBytes();
}
public void start() {
new Thread(() -> {
try {
while (true) {
if (selector.select() > 0) {
final Set<SelectionKey> keySet = selector.selectedKeys();
final Iterator<SelectionKey> iterator = keySet.iterator();
while (iterator.hasNext()) {
final SelectionKey selectionKey = iterator.next();
if (selectionKey.isAcceptable()) {
redirectClient();
iterator.remove();
}
}
}
}
} catch (Exception ignore) {
} finally {
closeResource(selector);
closeResource(server);
}
}).start();
}
public void stop() {
closeResource(selector);
closeResource(server);
}
private void closeResource(Closeable c) {
if (c != null) {
try {
c.close();
} catch (Exception ignore) {
}
}
}
private void redirectClient() {
SocketChannel client = null;
try {
client = server.accept();
client.socket().getOutputStream().write(redirectResponseHeaders);
client.socket().getOutputStream().flush();
} catch (Exception ignore) {
} finally {
closeResource(client);
}
}
}
public final class TestServer {
public static void main(String... args) throws Exception {
port(443);
secure(".config/keystore.jks", "password123", null, null);
final HttpsRedirector redirector = new HttpsRedirector(80, "https://localhost/");
redirector.start();
get("/", (request, response) -> {
halt(200, "Hello World");
return response;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment