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

com.atlassian.router.Router Maven / Gradle / Ivy

The newest version!
package com.atlassian.router;

import com.atlassian.router.internal.PathMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Router implements Servlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(Router.class);

    public enum Method {
        GET,
        POST,
        PUT,
        DELETE
    }

    private final Map> routes;

    public Router() {
        routes = new ConcurrentHashMap<>();
        routes.put("GET", new ArrayList<>());
        routes.put("POST", new ArrayList<>());
        routes.put("PUT", new ArrayList<>());
        routes.put("DELETE", new ArrayList<>());
    }

    public Router register(
            final Method method,
            final String path,
            final Servlet servlet
    ) throws ParseException {
        try {
            routes.get(method.name()).add(
                    new Routing(
                            PathMatcher.parse(path),
                            servlet
                    )
            );
        } catch (IOException e) {
            // No IO happening so this should never execute
            throw new RuntimeException(e);
        }
        return this;
    }

    @Override
    public void handle(HttpServletRequestWithContext request, HttpServletResponse response) throws IOException {
        List mRoutes = routes.get(request.getMethod().toUpperCase());
        for (Routing r : mRoutes) {
            if (r.matches(request.getPathInfo())) {
                request.addContext(new WithParams(r.matcher.params));
                r.handle(request, response);
                return;
            }
        }
        LOGGER.error("No route matched.");
        response.setStatus(500);
        response.getWriter().close();
    }

    static class Routing implements Servlet {
        final PathMatcher matcher;
        final Servlet servlet;

        public Routing(PathMatcher matcher, Servlet servlet) {
            this.matcher = matcher;
            this.servlet = servlet;
        }

        public boolean matches(String servletPath) {
            return matcher.matches(servletPath);
        }

        @Override
        public void handle(HttpServletRequestWithContext request, HttpServletResponse response) throws IOException {
            servlet.handle(request, response);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy