All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bitbucket.gkutiel.in.Server Maven / Gradle / Ivy

The newest version!
package org.bitbucket.gkutiel.in;

import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.reactivex.netty.RxNetty.createHttpServer;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.LinkedList;
import java.util.List;
import org.bitbucket.gkutiel.in.Handler.Stop;
import org.slf4j.Logger;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.server.HttpServer;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;

public class Server {
	class ServerHandler {

		final HttpServerRequest req;
		final HttpServerResponse res;

		public ServerHandler(final HttpServerRequest req, final HttpServerResponse res) {
			this.req = req;
			this.res = res;
		}

		Handler filter(final Handler handler) {
			for (final Filter filter : filters)
				filter.filter(handler);
			return handler;
		}

		void handle() throws Stop {
			final Handler handler = dispatcher.handler(req);
			if (handler == null) return;
			handler.req = req;
			handler.res = res;
			filter(handler).handle();
		}
	}

	public interface StartCallback {

		void started();
	}

	private static final Logger log = getLogger(Server.class);

	public static Server use(final int port, final Dispatcher dispatcher) {
		return new Server(port, dispatcher);
	}

	final List filters = new LinkedList<>();
	final int port;

	final Dispatcher dispatcher;

	Server(final int port, final Dispatcher dispatcher) {
		this.port = port;
		this.dispatcher = dispatcher;
	}

	public Server addFilter(final Filter filter) {
		filters.add(filter);
		return this;
	}

	private HttpServer createAndStart() {
		final HttpServer server = createHttpServer(port, (req, res) -> {
			try {
				new ServerHandler(req, res).handle();
			} catch (final Stop e) {
				log.debug(e.getMessage());
			} catch (final Exception e) {
				res.setStatus(BAD_REQUEST);
				log.error(e.getMessage(), e);
			}
			return res.close();
		});
		server.start();
		return server;
	}

	public void start() {
		start(() -> {});
	}

	public void start(StartCallback cb) {
		final HttpServer server = createAndStart();
		cb.started();
		wait(server);

	}

	private void wait(final HttpServer server) {
		try {
			server.waitTillShutdown();
		} catch (final InterruptedException e) {
			log.warn(e.getMessage(), e);
			Thread.interrupted();
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy