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

io.yawp.tools.ToolsServlet Maven / Gradle / Ivy

There is a newer version: 2.08alpha
Show newest version
package io.yawp.tools;

import io.yawp.commons.http.RequestContext;
import io.yawp.tools.datastore.DeleteAll;
import io.yawp.tools.pipes.ReloadPipe;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static io.yawp.repository.Yawp.yawp;

public class ToolsServlet extends HttpServlet {

    private Map> routes = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        routes.put("/datastore/delete_all", DeleteAll.class);
        routes.put("/pipes/reload", ReloadPipe.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestContext ctx = new RequestContext(req, resp);
        String path = ctx.getUri();

        if (!routes.containsKey(path)) {
            resp.setStatus(404);
            return;
        }
        execute(routes.get(path), ctx);
    }

    private String getToolPath(HttpServletRequest req) {
        return req.getRequestURI().substring(req.getServletPath().length());
    }

    private void execute(Class toolClazz, RequestContext ctx) throws IOException {
        Tool tool = newToolInstance(toolClazz, ctx);
        tool.prepareAndExecute();
    }

    private Tool newToolInstance(Class toolClazz, RequestContext ctx) {
        try {
            Tool tool = toolClazz.newInstance();
            tool.setRepository(yawp().setRequestContext(ctx));
            return tool;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy