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

com.davfx.ninio.http.util.PatternDispatchHttpServerHandler Maven / Gradle / Ivy

There is a newer version: 1.0.99
Show newest version
package com.davfx.ninio.http.util;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

import com.davfx.ninio.common.Address;
import com.davfx.ninio.http.HttpRequest;
import com.davfx.ninio.http.HttpServerHandler;

public final class PatternDispatchHttpServerHandler implements HttpServerHandler {
	private final Map handlers = new LinkedHashMap();
	private HttpServerHandler currentHandler = null;

	public PatternDispatchHttpServerHandler() {
	}
	
	public PatternDispatchHttpServerHandler add(Pattern pattern, HttpServerHandler handler) {
		handlers.put(pattern, handler);
		return this;
	}
	
	@Override
	public void handle(HttpRequest request) {
		String path = new HttpQuery(request.getPath()).getPath();
		for (Map.Entry e : handlers.entrySet()) {
			if (e.getKey().matcher(path).matches()) {
				currentHandler = e.getValue();
				break;
			}
		}
		if (currentHandler == null) {
			return;
		}
		currentHandler.handle(request);
	}
	
	@Override
	public void handle(Address address, ByteBuffer buffer) {
		if (currentHandler == null) {
			return;
		}
		currentHandler.handle(address, buffer);
	}
	
	@Override
	public void close() {
		if (currentHandler == null) {
			return;
		}
		currentHandler.close();
		currentHandler = null;
	}
	
	@Override
	public void failed(IOException e) {
		if (currentHandler == null) {
			return;
		}
		currentHandler.failed(e);
		currentHandler = null;
	}
	
	@Override
	public void ready(Write write) {
		if (currentHandler == null) {
			write.failed(null);
			return;
		}
		currentHandler.ready(write);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy