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

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

There is a newer version: 1.6-RELEASE
Show newest version
package org.bitbucket.gkutiel.in;

import static io.reactivex.netty.RxNetty.createHttpServer;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;
import java.util.LinkedList;
import java.util.List;
import org.bitbucket.gkutiel.in.Handler.Stop;

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(req, res, handler);
			return handler;
		}

		public void handle() throws Stop {
			handle(dispatcher.handler(req));
		}

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

	public static Server use(final int port, final Dispatcher dispatcher) {
		return use(port, dispatcher, (e, req, res) -> {
			throw new RuntimeException(e);
		});
	}

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

	final List filters = new LinkedList<>();
	final int port;
	final Dispatcher dispatcher;
	final ExceptionHandler exceptionHandler;

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

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

	public void start() {
		createHttpServer(port, (req, res) -> {
			try {
				new ServerHandler(req, res).handle();
			} catch (final Stop e) {} catch (final Exception e) {
				exceptionHandler.handle(e, req, res);
			}
			return res.close();
		}).startAndWait();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy