Search in sources :

Example 6 with ModelAndView

use of spark.ModelAndView in project gocd by gocd.

the class NewDashboardController method index.

public ModelAndView index(Request request, Response response) {
    Username username = currentUsername();
    if (pipelineConfigService.viewableGroupsFor(username).isEmpty() && securityService.canCreatePipelines(username)) {
        response.redirect("/go/admin/pipelines/create?group=defaultGroup");
        return null;
    }
    HashMap<Object, Object> object = new HashMap<Object, Object>() {

        {
            put("viewTitle", "Dashboard");
            put("showEmptyPipelineGroups", Toggles.isToggleOn(Toggles.ALLOW_EMPTY_PIPELINE_GROUPS_DASHBOARD));
            put("shouldShowAnalyticsIcon", showAnalyticsIcon());
            put("testDrive", Toggles.isToggleOn(Toggles.TEST_DRIVE));
        }
    };
    return new ModelAndView(object, "new_dashboard/index.ftlh");
}
Also used : Username(com.thoughtworks.go.server.domain.Username) HashMap(java.util.HashMap) ModelAndView(spark.ModelAndView)

Example 7 with ModelAndView

use of spark.ModelAndView in project searchcode-server by boyter.

the class App method main.

public static void main(String[] args) {
    // Database migrations happen before we start
    preStart();
    Singleton.getLogger().info("Starting searchcode server on port " + getServerPort());
    if (getOnlyLocalhost()) {
        Singleton.getLogger().info("Only listening on 127.0.0.1 ");
        Spark.ipAddress("127.0.0.1");
    }
    Spark.port(getServerPort());
    Spark.staticFileLocation("/public");
    Singleton.getJobService().initialJobs();
    ////////////////////////////////////////////////////
    //          Search/Code Routes Below
    ////////////////////////////////////////////////////
    get("/", (request, response) -> {
        response.header("Content-Encoding", "gzip");
        CodeRouteService codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(codeRouteService.root(request, response));
    });
    get("/html/", (request, response) -> {
        response.header("Content-Encoding", "gzip");
        CodeRouteService codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(codeRouteService.html(request, response));
    });
    get("/literal/", (request, response) -> {
        CodeRouteService codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(new ModelAndView(codeRouteService.literalSearch(request, response), "index.ftl"));
    });
    get("/file/:codeid/:reponame/*", (request, response) -> {
        response.header("Content-Encoding", "gzip");
        CodeRouteService codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(new ModelAndView(codeRouteService.getCode(request, response), "coderesult.ftl"));
    });
    get("/repository/overview/:reponame/", (request, response) -> {
        response.header("Content-Encoding", "gzip");
        CodeRouteService codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(new ModelAndView(codeRouteService.getProject(request, response), "repository_overview.ftl"));
    });
    get("/repository/list/", (request, response) -> {
        response.header("Content-Encoding", "gzip");
        CodeRouteService codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(new ModelAndView(codeRouteService.getRepositoryList(request, response), "repository_list.ftl"));
    });
    ////////////////////////////////////////////////////
    //              Page Routes Below
    ////////////////////////////////////////////////////
    get("/documentation/", (request, response) -> {
        Map<String, Object> map = new HashMap<>();
        map.put("logoImage", CommonRouteService.getLogo());
        map.put("isCommunity", ISCOMMUNITY);
        map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
        return new FreeMarkerEngine().render(new ModelAndView(map, "documentation.ftl"));
    });
    get("/404/", (request, response) -> {
        Map<String, Object> map = new HashMap<>();
        map.put("logoImage", CommonRouteService.getLogo());
        map.put("isCommunity", ISCOMMUNITY);
        map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
        return new FreeMarkerEngine().render(new ModelAndView(map, "404.ftl"));
    });
    ////////////////////////////////////////////////////
    //              API Routes Below
    ////////////////////////////////////////////////////
    path("/api", () -> {
        get("/codesearch/", (request, response) -> {
            addJsonHeaders(response);
            SearchRouteService searchRouteService = new SearchRouteService();
            return new JsonTransformer().render(searchRouteService.codeSearch(request, response));
        });
        get("/codesearch/rss/", (request, response) -> {
            addXmlHeaders(response);
            SearchRouteService searchRouteService = new SearchRouteService();
            Map<String, Object> map = new HashMap<>();
            map.put("result", searchRouteService.codeSearch(request, response));
            map.put("hostname", Properties.getProperties().getProperty(Values.HOST_NAME, Values.DEFAULT_HOST_NAME));
            return new FreeMarkerEngine().render(new ModelAndView(map, "codesearchrss.ftl"));
        });
        get("/timecodesearch/", (request, response) -> {
            addJsonHeaders(response);
            TimeSearchRouteService ars = new TimeSearchRouteService();
            return new JsonTransformer().render(ars.getTimeSearch(request, response));
        });
        path("/repo", () -> {
            get("/add/", "application/json", (request, response) -> {
                addJsonHeaders(response);
                ApiRouteService apiRouteService = new ApiRouteService();
                return new JsonTransformer().render(apiRouteService.repoAdd(request, response));
            });
            get("/delete/", "application/json", (request, response) -> {
                addJsonHeaders(response);
                ApiRouteService apiRouteService = new ApiRouteService();
                return new JsonTransformer().render(apiRouteService.repoDelete(request, response));
            });
            get("/list/", "application/json", (request, response) -> {
                addJsonHeaders(response);
                ApiRouteService apiRouteService = new ApiRouteService();
                return new JsonTransformer().render(apiRouteService.repoList(request, response));
            });
            get("/reindex/", "application/json", (request, response) -> {
                addJsonHeaders(response);
                ApiRouteService apiRouteService = new ApiRouteService();
                return new JsonTransformer().render(apiRouteService.repositoryReindex(request, response));
            });
            ////////////////////////////////////////////////////
            //          Unsecured API Routes Below
            ////////////////////////////////////////////////////
            get("/index/", "application/json", (request, response) -> {
                addJsonHeaders(response);
                ApiRouteService apiRouteService = new ApiRouteService();
                return new JsonTransformer().render(apiRouteService.repositoryIndex(request, response));
            });
            get("/filecount/", "application/json", (request, response) -> {
                ApiRouteService apiRouteService = new ApiRouteService();
                return apiRouteService.getFileCount(request, response);
            });
            get("/indextime/", "application/json", (request, response) -> {
                ApiRouteService apiRouteService = new ApiRouteService();
                return apiRouteService.getIndexTime(request, response);
            });
            get("/indextimeseconds/", "application/json", (request, response) -> {
                ApiRouteService apiRouteService = new ApiRouteService();
                return apiRouteService.getAverageIndexTimeSeconds(request, response);
            });
            get("/repo/", "application/json", (request, response) -> {
                addJsonHeaders(response);
                ApiRouteService apiRouteService = new ApiRouteService();
                return new JsonTransformer().render(apiRouteService.getRepo(request, response));
            });
        });
    });
    ////////////////////////////////////////////////////
    //              Admin Routes Below
    ////////////////////////////////////////////////////
    get("/login/", (request, response) -> {
        if (getAuthenticatedUser(request) != null) {
            response.redirect("/admin/");
            halt();
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("logoImage", CommonRouteService.getLogo());
        map.put("isCommunity", ISCOMMUNITY);
        map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
        return new FreeMarkerEngine().render(new ModelAndView(map, "login.ftl"));
    });
    post("/login/", (request, response) -> {
        if (request.queryParams().contains("password") && request.queryParams("password").equals(com.searchcode.app.util.Properties.getProperties().getProperty("password"))) {
            addAuthenticatedUser(request);
            response.redirect("/admin/");
            halt();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("logoImage", CommonRouteService.getLogo());
        map.put("isCommunity", ISCOMMUNITY);
        map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
        if (request.queryParams().contains("password")) {
            map.put("passwordInvalid", true);
        }
        return new FreeMarkerEngine().render(new ModelAndView(map, "login.ftl"));
    });
    get("/logout/", (req, res) -> {
        removeAuthenticatedUser(req);
        res.redirect("/");
        return null;
    });
    path("/admin", () -> {
        get("/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            Map<String, Object> map = adminRouteService.adminPage(request, response);
            return new FreeMarkerEngine().render(new ModelAndView(map, "admin.ftl"));
        });
        get("/repo/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            Map<String, Object> map = adminRouteService.adminRepo(request, response);
            return new FreeMarkerEngine().render(new ModelAndView(map, "admin_repo.ftl"));
        });
        post("/repo/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            ValidatorResult validatorResult = adminRouteService.postRepo(request, response);
            if (!validatorResult.isValid) {
                Map<String, Object> map = adminRouteService.adminRepo(request, response);
                map.put("validatorResult", validatorResult);
                return new FreeMarkerEngine().render(new ModelAndView(map, "admin_repo.ftl"));
            }
            String[] returns = request.queryParamsValues("return");
            if (returns != null) {
                response.redirect("/admin/repo/");
            } else {
                response.redirect("/admin/repolist/");
            }
            halt();
            return null;
        });
        get("/repolist/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            Map<String, Object> map = adminRouteService.adminRepo(request, response);
            return new FreeMarkerEngine().render(new ModelAndView(map, "admin_repolist.ftl"));
        });
        get("/bulk/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            Map<String, Object> map = new HashMap<>();
            map.put("logoImage", CommonRouteService.getLogo());
            map.put("isCommunity", ISCOMMUNITY);
            map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
            map.put("repoCount", adminRouteService.getStat("repoCount"));
            return new FreeMarkerEngine().render(new ModelAndView(map, "admin_bulk.ftl"));
        });
        post("/bulk/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            List<ValidatorResult> validatorResults = adminRouteService.postBulk(request, response);
            if (!validatorResults.isEmpty()) {
                Map<String, Object> map = new HashMap<>();
                map.put("logoImage", CommonRouteService.getLogo());
                map.put("isCommunity", ISCOMMUNITY);
                map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
                map.put("repoCount", adminRouteService.getStat("repoCount"));
                map.put("validatorResults", validatorResults);
                return new FreeMarkerEngine().render(new ModelAndView(map, "admin_bulk.ftl"));
            }
            response.redirect("/admin/repolist/");
            halt();
            return null;
        });
        get("/settings/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            Map<String, Object> map = adminRouteService.adminSettings(request, response);
            return new FreeMarkerEngine().render(new ModelAndView(map, "admin_settings.ftl"));
        });
        get("/logs/", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            Map<String, Object> map = adminRouteService.adminLogs(request, response);
            return new FreeMarkerEngine().render(new ModelAndView(map, "admin_logs.ftl"));
        });
        post("/settings/", (request, response) -> {
            checkLoggedIn(request, response);
            if (ISCOMMUNITY) {
                response.redirect("/admin/settings/");
                halt();
            }
            AdminRouteService adminRouteService = new AdminRouteService();
            adminRouteService.postSettings(request, response);
            response.redirect("/admin/settings/");
            halt();
            return null;
        });
        get("/delete/", "application/json", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            adminRouteService.deleteRepo(request, response);
            return new JsonTransformer().render(true);
        });
        post("/rebuild/", "application/json", (request, response) -> {
            checkLoggedIn(request, response);
            boolean result = Singleton.getJobService().rebuildAll();
            if (result) {
                Singleton.getJobService().forceEnqueue();
            }
            return new JsonTransformer().render(result);
        });
        post("/forcequeue/", "application/json", (request, response) -> {
            checkLoggedIn(request, response);
            return Singleton.getJobService().forceEnqueue();
        }, new JsonTransformer());
        post("/togglepause/", "application/json", (request, response) -> {
            checkLoggedIn(request, response);
            Singleton.getSharedService().setPauseBackgroundJobs(!Singleton.getSharedService().getPauseBackgroundJobs());
            return new JsonTransformer().render(Singleton.getSharedService().getPauseBackgroundJobs());
        });
        post("/clearsearchcount/", "application/json", (request, response) -> {
            checkLoggedIn(request, response);
            Singleton.getStatsService().clearSearchCount();
            return new JsonTransformer().render(Values.EMPTYSTRING);
        });
        post("/resetspellingcorrector/", "application/json", (request, response) -> {
            checkLoggedIn(request, response);
            Singleton.getSpellingCorrector().reset();
            return new JsonTransformer().render(Values.EMPTYSTRING);
        });
        get("/checkversion/", "application/json", (request, response) -> {
            checkLoggedIn(request, response);
            AdminRouteService adminRouteService = new AdminRouteService();
            return adminRouteService.checkVersion();
        });
        path("/api", () -> {
            get("/", (request, response) -> {
                checkLoggedIn(request, response);
                AdminRouteService adminRouteService = new AdminRouteService();
                Map<String, Object> map = adminRouteService.adminApi(request, response);
                return new FreeMarkerEngine().render(new ModelAndView(map, "admin_api.ftl"));
            });
            post("/", (request, response) -> {
                checkLoggedIn(request, response);
                Singleton.getApiService().createKeys();
                response.redirect("/admin/api/");
                halt();
                return null;
            });
            get("/delete/", "application/json", (request, response) -> {
                checkLoggedIn(request, response);
                if (getAuthenticatedUser(request) == null || !request.queryParams().contains("publicKey")) {
                    response.redirect("/login/");
                    halt();
                    return new JsonTransformer().render(false);
                }
                String publicKey = request.queryParams("publicKey");
                Singleton.getApiService().deleteKey(publicKey);
                return new JsonTransformer().render(true);
            });
            get("/getstat/", (request, response) -> {
                checkLoggedIn(request, response);
                AdminRouteService adminRouteService = new AdminRouteService();
                return adminRouteService.getStat(request, response);
            });
            get("/getstatjson/", "application/json", (request, response) -> {
                checkLoggedIn(request, response);
                AdminRouteService adminRouteService = new AdminRouteService();
                return new JsonTransformer().render(adminRouteService.getStat(request, response));
            });
            get("/checkindexstatus/", "application/json", (request, response) -> {
                // TODO move this to unsecured routes
                AdminRouteService adminRouteService = new AdminRouteService();
                return adminRouteService.checkIndexStatus(request, response);
            });
        });
    });
}
Also used : FreeMarkerEngine(spark.template.freemarker.FreeMarkerEngine) HashMap(java.util.HashMap) ValidatorResult(com.searchcode.app.model.ValidatorResult) ModelAndView(spark.ModelAndView) JsonTransformer(com.searchcode.app.util.JsonTransformer)

Example 8 with ModelAndView

use of spark.ModelAndView in project searchcode-server by boyter.

the class CodeRouteService method html.

public ModelAndView html(Request request, Response response) {
    Repo repo = Singleton.getRepo();
    Data data = Singleton.getData();
    SearchcodeLib scl = Singleton.getSearchcodeLib(data);
    CodeSearcher cs = new CodeSearcher();
    CodeMatcher cm = new CodeMatcher(data);
    Map<String, Object> map = new HashMap<>();
    map.put("repoCount", repo.getRepoCount());
    if (request.queryParams().contains("q")) {
        String query = request.queryParams("q").trim();
        String altquery = query.replaceAll("[^A-Za-z0-9 ]", " ").trim().replaceAll(" +", " ");
        int page = 0;
        if (request.queryParams().contains("p")) {
            try {
                page = Integer.parseInt(request.queryParams("p"));
                page = page > 19 ? 19 : page;
            } catch (NumberFormatException ex) {
                page = 0;
            }
        }
        String[] repos = new String[0];
        String[] langs = new String[0];
        String[] owners = new String[0];
        String reposFilter = Values.EMPTYSTRING;
        String langsFilter = Values.EMPTYSTRING;
        String ownersFilter = Values.EMPTYSTRING;
        String reposQueryString = Values.EMPTYSTRING;
        String langsQueryString = Values.EMPTYSTRING;
        String ownsQueryString = Values.EMPTYSTRING;
        if (request.queryParams().contains("repo")) {
            repos = request.queryParamsValues("repo");
            if (repos.length != 0) {
                List<String> reposList = Arrays.asList(repos).stream().map((s) -> "reponame:" + QueryParser.escape(s)).collect(Collectors.toList());
                reposFilter = " && (" + StringUtils.join(reposList, " || ") + ")";
                List<String> reposQueryList = Arrays.asList(repos).stream().map((s) -> "&repo=" + URLEncoder.encode(s)).collect(Collectors.toList());
                reposQueryString = StringUtils.join(reposQueryList, "");
            }
        }
        if (request.queryParams().contains("lan")) {
            langs = request.queryParamsValues("lan");
            if (langs.length != 0) {
                List<String> langsList = Arrays.asList(langs).stream().map((s) -> "languagename:" + QueryParser.escape(s)).collect(Collectors.toList());
                langsFilter = " && (" + StringUtils.join(langsList, " || ") + ")";
                List<String> langsQueryList = Arrays.asList(langs).stream().map((s) -> "&lan=" + URLEncoder.encode(s)).collect(Collectors.toList());
                langsQueryString = StringUtils.join(langsQueryList, "");
            }
        }
        if (request.queryParams().contains("own")) {
            owners = request.queryParamsValues("own");
            if (owners.length != 0) {
                List<String> ownersList = Arrays.asList(owners).stream().map((s) -> "codeowner:" + QueryParser.escape(s)).collect(Collectors.toList());
                ownersFilter = " && (" + StringUtils.join(ownersList, " || ") + ")";
                List<String> ownsQueryList = Arrays.asList(owners).stream().map((s) -> "&own=" + URLEncoder.encode(s)).collect(Collectors.toList());
                ownsQueryString = StringUtils.join(ownsQueryList, "");
            }
        }
        // split the query escape it and and it together
        String cleanQueryString = scl.formatQueryString(query);
        SearchResult searchResult = cs.search(cleanQueryString + reposFilter + langsFilter + ownersFilter, page);
        searchResult.setCodeResultList(cm.formatResults(searchResult.getCodeResultList(), query, true));
        for (CodeFacetRepo f : searchResult.getRepoFacetResults()) {
            if (Arrays.asList(repos).contains(f.getRepoName())) {
                f.setSelected(true);
            }
        }
        for (CodeFacetLanguage f : searchResult.getLanguageFacetResults()) {
            if (Arrays.asList(langs).contains(f.getLanguageName())) {
                f.setSelected(true);
            }
        }
        for (CodeFacetOwner f : searchResult.getOwnerFacetResults()) {
            if (Arrays.asList(owners).contains(f.getOwner())) {
                f.setSelected(true);
            }
        }
        map.put("searchValue", query);
        map.put("searchResult", searchResult);
        map.put("reposQueryString", reposQueryString);
        map.put("langsQueryString", langsQueryString);
        map.put("ownsQueryString", ownsQueryString);
        map.put("altQuery", altquery);
        map.put("totalPages", searchResult.getPages().size());
        map.put("isHtml", true);
        map.put("logoImage", CommonRouteService.getLogo());
        map.put("isCommunity", App.ISCOMMUNITY);
        map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
        return new ModelAndView(map, "searchresults.ftl");
    }
    map.put("photoId", CommonRouteService.getPhotoId());
    map.put("numDocs", cs.getTotalNumberDocumentsIndexed());
    map.put("logoImage", CommonRouteService.getLogo());
    map.put("isCommunity", App.ISCOMMUNITY);
    map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
    return new ModelAndView(map, "index.ftl");
}
Also used : java.util(java.util) Singleton(com.searchcode.app.service.Singleton) Spark.halt(spark.Spark.halt) RepoResult(com.searchcode.app.model.RepoResult) ModelAndView(spark.ModelAndView) Repo(com.searchcode.app.dao.Repo) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) Values(com.searchcode.app.config.Values) CodeMatcher(com.searchcode.app.service.CodeMatcher) com.searchcode.app.util(com.searchcode.app.util) CommonRouteService(com.searchcode.app.service.route.CommonRouteService) URLEncoder(java.net.URLEncoder) com.searchcode.app.dto(com.searchcode.app.dto) CodeSearcher(com.searchcode.app.service.CodeSearcher) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) Gson(com.google.gson.Gson) Request(spark.Request) Data(com.searchcode.app.dao.Data) Response(spark.Response) Properties(com.searchcode.app.util.Properties) StringEscapeUtils(org.apache.commons.lang3.StringEscapeUtils) App(com.searchcode.app.App) ModelAndView(spark.ModelAndView) Data(com.searchcode.app.dao.Data) CodeSearcher(com.searchcode.app.service.CodeSearcher) Repo(com.searchcode.app.dao.Repo) CodeMatcher(com.searchcode.app.service.CodeMatcher)

Example 9 with ModelAndView

use of spark.ModelAndView in project searchcode-server by boyter.

the class CodeRouteService method root.

public ModelAndView root(Request request, Response response) {
    Map<String, Object> map = new HashMap<>();
    Repo repo = Singleton.getRepo();
    Gson gson = new Gson();
    map.put("repoCount", repo.getRepoCount());
    if (request.queryParams().contains("q") && !request.queryParams("q").trim().equals("")) {
        String query = request.queryParams("q").trim();
        int page = 0;
        if (request.queryParams().contains("p")) {
            try {
                page = Integer.parseInt(request.queryParams("p"));
                page = page > 19 ? 19 : page;
            } catch (NumberFormatException ex) {
                page = 0;
            }
        }
        List<String> reposList = new ArrayList<>();
        List<String> langsList = new ArrayList<>();
        List<String> ownsList = new ArrayList<>();
        if (request.queryParams().contains("repo")) {
            String[] repos;
            repos = request.queryParamsValues("repo");
            if (repos.length != 0) {
                reposList = Arrays.asList(repos);
            }
        }
        if (request.queryParams().contains("lan")) {
            String[] langs;
            langs = request.queryParamsValues("lan");
            if (langs.length != 0) {
                langsList = Arrays.asList(langs);
            }
        }
        if (request.queryParams().contains("own")) {
            String[] owns;
            owns = request.queryParamsValues("own");
            if (owns.length != 0) {
                ownsList = Arrays.asList(owns);
            }
        }
        map.put("searchValue", query);
        map.put("searchResultJson", gson.toJson(new CodePreload(query, page, langsList, reposList, ownsList)));
        map.put("logoImage", CommonRouteService.getLogo());
        map.put("isCommunity", App.ISCOMMUNITY);
        map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
        return new ModelAndView(map, "search_ajax.ftl");
    }
    CodeSearcher cs = new CodeSearcher();
    map.put("photoId", CommonRouteService.getPhotoId());
    map.put("numDocs", cs.getTotalNumberDocumentsIndexed());
    map.put("logoImage", CommonRouteService.getLogo());
    map.put("isCommunity", App.ISCOMMUNITY);
    map.put(Values.EMBED, Singleton.getData().getDataByName(Values.EMBED, Values.EMPTYSTRING));
    return new ModelAndView(map, "index.ftl");
}
Also used : ModelAndView(spark.ModelAndView) Gson(com.google.gson.Gson) CodeSearcher(com.searchcode.app.service.CodeSearcher) Repo(com.searchcode.app.dao.Repo)

Example 10 with ModelAndView

use of spark.ModelAndView in project DisCal-Discord-Bot by NovaFox161.

the class SparkUtils method initSpark.

@SuppressWarnings("ThrowableNotThrown")
public static void initSpark() {
    if (BotSettings.RUN_API.get().equalsIgnoreCase("true")) {
        port(Integer.valueOf(BotSettings.PORT.get()));
        // Main site location
        staticFileLocation("/web/public");
        notFound(((request, response) -> {
            response.redirect("/", 301);
            return response.body();
        }));
        // Register the API Endpoints
        before("/api/*", (request, response) -> {
            if (!request.requestMethod().equalsIgnoreCase("POST")) {
                Logger.getLogger().api("Denied '" + request.requestMethod() + "' access", request.ip());
                halt(405, "Method not allowed");
            }
            // Check authorization
            if (DiscordAccountHandler.getHandler().hasAccount(request.session().id())) {
                // User is logged in from website, no API key needed
                Logger.getLogger().api("API Call from website", request.ip());
            } else {
                // Requires "Authorization Header
                if (request.headers().contains("Authorization")) {
                    String key = request.headers("Authorization");
                    UserAPIAccount acc = DatabaseManager.getManager().getAPIAccount(key);
                    if (acc != null) {
                        if (acc.isBlocked()) {
                            Logger.getLogger().api("Attempted to use blocked API Key: " + acc.getAPIKey(), request.ip());
                            halt(401, "Unauthorized");
                        } else {
                            // Everything checks out!
                            acc.setUses(acc.getUses() + 1);
                            DatabaseManager.getManager().updateAPIAccount(acc);
                        }
                    } else {
                        Logger.getLogger().api("Attempted to use invalid API Key: " + key, request.ip());
                        halt(401, "Unauthorized");
                    }
                } else {
                    Logger.getLogger().api("Attempted to use API without authorization header", request.ip());
                    halt(400, "Bad Request");
                }
            }
        // Only accept json because its easier to parse and handle.
        /*
				if (!request.contentType().equalsIgnoreCase("application/json")) {
					halt(400, "Bad Request");
				}
				*/
        });
        // API endpoints
        path("/api/v1", () -> {
            before("/*", (q, a) -> Logger.getLogger().api("Received API Call", q.ip(), q.host(), q.pathInfo()));
            path("/guild", () -> {
                path("/settings", () -> {
                    post("/get", GuildEndpoint::getSettings);
                    post("/update", GuildEndpoint::updateSettings);
                });
                path("/info", () -> post("/from-user/list", GuildEndpoint::getUserGuilds));
            });
            path("/announcement", () -> {
                post("/get", AnnouncementEndpoint::getAnnouncement);
                post("/create", AnnouncementEndpoint::createAnnouncement);
                post("/update", AnnouncementEndpoint::updateAnnouncement);
                post("/delete", AnnouncementEndpoint::deleteAnnouncement);
                post("/list", AnnouncementEndpoint::listAnnouncements);
            });
            path("/calendar", () -> {
                post("/get", CalendarEndpoint::getCalendar);
                post("/list", CalendarEndpoint::listCalendars);
            });
            path("/events", () -> {
                path("/list", () -> {
                    post("/month", EventEndpoint::getEventsForMonth);
                    post("/date", EventEndpoint::getEventsForSelectedDate);
                });
                post("/update", EventEndpoint::updateEvent);
                post("/create", EventEndpoint::createEvent);
                post("/delete", EventEndpoint::deleteEvent);
            });
            path("/rsvp", () -> {
                post("/get", RsvpEndpoint::getRsvp);
                post("/update", RsvpEndpoint::updateRsvp);
            });
            path("/dashboard", () -> {
                path("/select", () -> {
                    post("/guild", DashboardHandler::handleGuildSelect);
                    post("/settings", DashboardHandler::handleSettingsSelect);
                });
                path("/create", () -> {
                    post("/calendar", DashboardHandler::handleCalendarCreate);
                    post("/announcement", DashboardHandler::handleAnnouncementCreate);
                });
                path("/update", () -> {
                    post("/announcement", DashboardHandler::handleAnnouncementUpdate);
                    post("/calendar", DashboardHandler::handleCalendarUpdate);
                    post("/settings", DashboardHandler::handleSettingsUpdate);
                });
                path("/delete", () -> {
                    post("/calendar", DashboardHandler::deleteCalendar);
                    post("/announcement", DashboardHandler::deleteAnnouncement);
                });
            });
        });
        // Various endpoints for thyme because yeah...
        path("/account", () -> {
            get("/login", DiscordLoginHandler::handleDiscordCode);
            get("/logout", DiscordLoginHandler::handleLogout);
        });
        // Templates and pages...
        get("/", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/index"), new ThymeleafTemplateEngine());
        get("/home", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/index"), new ThymeleafTemplateEngine());
        get("/about", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/about"), new ThymeleafTemplateEngine());
        get("/commands", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/commands"), new ThymeleafTemplateEngine());
        get("/lazy-discal", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/lazy-discal"), new ThymeleafTemplateEngine());
        get("/setup", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/setup"), new ThymeleafTemplateEngine());
        get("/policy/privacy", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/policy/privacy"), new ThymeleafTemplateEngine());
        // Dashboard pages
        get("/dashboard", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/dashboard/dashboard"), new ThymeleafTemplateEngine());
        get("/dashboard/guild", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/dashboard/guild"), new ThymeleafTemplateEngine());
        get("/dashboard/guild/calendar", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/dashboard/components/calendar"), new ThymeleafTemplateEngine());
        get("/dashboard/guild/events", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/dashboard/components/events"), new ThymeleafTemplateEngine());
        get("/dashboard/guild/announcements", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/dashboard/components/announcements"), new ThymeleafTemplateEngine());
        get("/dashboard/guild/rsvp", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/dashboard/components/rsvp"), new ThymeleafTemplateEngine());
        // Various other doc pages
        get("/docs/event/colors", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/events/event-colors"), new ThymeleafTemplateEngine());
        // API Doc Pages
        get("/docs/api/overview", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/overview"), new ThymeleafTemplateEngine());
        get("/docs/api/errors", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/errors"), new ThymeleafTemplateEngine());
        // API v1 Doc Pages
        get("/docs/api/v1/announcement", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/v1/announcement"), new ThymeleafTemplateEngine());
        get("/docs/api/v1/calendar", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/v1/calendar"), new ThymeleafTemplateEngine());
        get("/docs/api/v1/events", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/v1/events"), new ThymeleafTemplateEngine());
        get("/docs/api/v1/guild", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/v1/guild"), new ThymeleafTemplateEngine());
        get("/docs/api/v1/rsvp", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/v1/rsvp"), new ThymeleafTemplateEngine());
        get("/docs/api/v1/time", (rq, rs) -> new ModelAndView(DiscordAccountHandler.getHandler().getAccount(rq.session().id()), "pages/docs/api/v1/time"), new ThymeleafTemplateEngine());
    }
}
Also used : UserAPIAccount(com.cloudcraftgaming.discal.api.object.web.UserAPIAccount) Logger(com.cloudcraftgaming.discal.logger.Logger) DashboardHandler(com.cloudcraftgaming.discal.web.handler.DashboardHandler) DiscordLoginHandler(com.cloudcraftgaming.discal.api.network.discord.DiscordLoginHandler) ModelAndView(spark.ModelAndView) BotSettings(com.cloudcraftgaming.discal.api.object.BotSettings) com.cloudcraftgaming.discal.web.endpoints.v1(com.cloudcraftgaming.discal.web.endpoints.v1) DiscordAccountHandler(com.cloudcraftgaming.discal.web.handler.DiscordAccountHandler) Spark(spark.Spark) DatabaseManager(com.cloudcraftgaming.discal.api.database.DatabaseManager) DiscordLoginHandler(com.cloudcraftgaming.discal.api.network.discord.DiscordLoginHandler) UserAPIAccount(com.cloudcraftgaming.discal.api.object.web.UserAPIAccount) ModelAndView(spark.ModelAndView) DashboardHandler(com.cloudcraftgaming.discal.web.handler.DashboardHandler)

Aggregations

ModelAndView (spark.ModelAndView)15 HashMap (java.util.HashMap)8 FreeMarkerEngine (spark.template.freemarker.FreeMarkerEngine)5 Request (spark.Request)4 CodeRouteService (com.searchcode.app.service.route.CodeRouteService)3 JsonTransformer (com.searchcode.app.util.JsonTransformer)3 Gson (com.google.gson.Gson)2 Data (com.searchcode.app.dao.Data)2 Repo (com.searchcode.app.dao.Repo)2 CodeSearcher (com.searchcode.app.service.CodeSearcher)2 CaseInsensitiveString (com.thoughtworks.go.config.CaseInsensitiveString)2 Date (java.util.Date)2 Response (spark.Response)2 DatabaseManager (com.cloudcraftgaming.discal.api.database.DatabaseManager)1 DiscordLoginHandler (com.cloudcraftgaming.discal.api.network.discord.DiscordLoginHandler)1 BotSettings (com.cloudcraftgaming.discal.api.object.BotSettings)1 UserAPIAccount (com.cloudcraftgaming.discal.api.object.web.UserAPIAccount)1 Logger (com.cloudcraftgaming.discal.logger.Logger)1 com.cloudcraftgaming.discal.web.endpoints.v1 (com.cloudcraftgaming.discal.web.endpoints.v1)1 DashboardHandler (com.cloudcraftgaming.discal.web.handler.DashboardHandler)1