Search in sources :

Example 1 with ModelAndView

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

the class CodeRouteServiceTest method testRootNoQueryString.

public void testRootNoQueryString() {
    CodeRouteService codeRouteService = new CodeRouteService();
    Request request = Mockito.mock(Request.class);
    Data mockData = Mockito.mock(Data.class);
    when(mockData.getDataByName(Values.LOGO, Values.EMPTYSTRING)).thenReturn(Values.EMPTYSTRING);
    Singleton.setData(mockData);
    ModelAndView modelAndView = codeRouteService.root(request, null);
    Map<String, Object> model = (Map<String, Object>) modelAndView.getModel();
    String viewName = modelAndView.getViewName();
    assertThat(model.get("photoId")).isInstanceOf(Integer.class);
    assertThat((int) model.get("photoId")).isGreaterThanOrEqualTo(0);
    assertThat((int) model.get("photoId")).isLessThanOrEqualTo(42);
    assertThat(model.get("numDocs")).isInstanceOf(Integer.class);
    assertThat((int) model.get("numDocs")).isGreaterThanOrEqualTo(0);
    assertThat(model.get("logoImage")).isNotNull();
    assertThat(model.get("isCommunity")).isEqualTo(App.IS_COMMUNITY);
    assertThat(viewName).isEqualTo("index.ftl");
}
Also used : CodeRouteService(com.searchcode.app.service.route.CodeRouteService) Request(spark.Request) ModelAndView(spark.ModelAndView) Data(com.searchcode.app.dao.Data)

Example 2 with ModelAndView

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

the class SearchcodeRoutes method RegisterSearchcodeRoutes.

public static void RegisterSearchcodeRoutes() {
    get("/", (request, response) -> {
        var codeRouteService = new CodeRouteService();
        var map = codeRouteService.html(request, response);
        if ((Boolean) map.getOrDefault("isIndex", Boolean.TRUE)) {
            return new FreeMarkerEngine().render(new ModelAndView(map, "index.ftl"));
        }
        return new FreeMarkerEngine().render(new ModelAndView(map, "searchcode_searchresults.ftl"));
    });
    get("/healthcheck/", (request, response) -> new JsonTransformer().render(true));
    get("/health-check/", (request, response) -> new JsonTransformer().render(true));
    get("/file/:codeid/*", (request, response) -> {
        var codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(new ModelAndView(codeRouteService.getCode(request, response), "coderesult.ftl"));
    });
    get("/repository/overview/:reponame/:repoid/", (request, response) -> {
        var codeRouteService = new CodeRouteService();
        return new FreeMarkerEngine().render(new ModelAndView(codeRouteService.getProject(request, response), "repository_overview.ftl"));
    });
    // /api/codesearch_I/
    path("/api", () -> {
        // Older endpoints maintained for backwards compatibility
        get("/codesearch_I/", (request, response) -> {
            addJsonHeaders(response);
            var searchRouteService = new SearchRouteService();
            return new JsonTransformer().render(searchRouteService.codeSearch_I(request, response));
        });
        get("/result/:codeid/", (request, response) -> {
            addJsonHeaders(response);
            var searchRouteService = new SearchRouteService();
            return new JsonTransformer().render(searchRouteService.codeResult(request, response));
        });
        // All new API endpoints should go in here to allow public exposure and versioning
        path("/v1", () -> {
            get("/version/", (request, response) -> {
                addJsonHeaders(response);
                return new JsonTransformer().render("");
            });
            get("/health-check/", (request, response) -> {
                addJsonHeaders(response);
                return new JsonTransformer().render("");
            });
        });
    });
}
Also used : FreeMarkerEngine(spark.template.freemarker.FreeMarkerEngine) CodeRouteService(com.searchcode.app.service.route.CodeRouteService) SearchRouteService(com.searchcode.app.service.route.SearchRouteService) ModelAndView(spark.ModelAndView) JsonTransformer(com.searchcode.app.util.JsonTransformer)

Example 3 with ModelAndView

use of spark.ModelAndView in project SpringStepByStep by JavaProgrammerLB.

the class WebConfig method setupRoutes.

private void setupRoutes() {
    /*
		 * Shows a users timeline or if no user is logged in,
		 *  it will redirect to the public timeline.
		 *  This timeline shows the user's messages as well
		 *  as all the messages of followed users.
		 */
    get("/", (req, res) -> {
        User user = getAuthenticatedUser(req);
        Map<String, Object> map = new HashMap<>();
        map.put("pageTitle", "Timeline");
        map.put("user", user);
        List<Message> messages = service.getUserFullTimelineMessages(user);
        map.put("messages", messages);
        return new ModelAndView(map, "timeline.ftl");
    }, new FreeMarkerEngine());
    before("/", (req, res) -> {
        User user = getAuthenticatedUser(req);
        if (user == null) {
            res.redirect("/public");
            halt();
        }
    });
    /*
		 * Displays the latest messages of all users.
		 */
    get("/public", (req, res) -> {
        User user = getAuthenticatedUser(req);
        Map<String, Object> map = new HashMap<>();
        map.put("pageTitle", "Public Timeline");
        map.put("user", user);
        List<Message> messages = service.getPublicTimelineMessages();
        map.put("messages", messages);
        return new ModelAndView(map, "timeline.ftl");
    }, new FreeMarkerEngine());
    /*
		 * Displays a user's tweets.
		 */
    get("/t/:username", (req, res) -> {
        String username = req.params(":username");
        User profileUser = service.getUserbyUsername(username);
        User authUser = getAuthenticatedUser(req);
        boolean followed = false;
        if (authUser != null) {
            followed = service.isUserFollower(authUser, profileUser);
        }
        List<Message> messages = service.getUserTimelineMessages(profileUser);
        Map<String, Object> map = new HashMap<>();
        map.put("pageTitle", username + "'s Timeline");
        map.put("user", authUser);
        map.put("profileUser", profileUser);
        map.put("followed", followed);
        map.put("messages", messages);
        return new ModelAndView(map, "timeline.ftl");
    }, new FreeMarkerEngine());
    /*
		 * Checks if the user exists
		 */
    before("/t/:username", (req, res) -> {
        String username = req.params(":username");
        User profileUser = service.getUserbyUsername(username);
        if (profileUser == null) {
            halt(404, "User not Found");
        }
    });
    /*
		 * Adds the current user as follower of the given user.
		 */
    get("/t/:username/follow", (req, res) -> {
        String username = req.params(":username");
        User profileUser = service.getUserbyUsername(username);
        User authUser = getAuthenticatedUser(req);
        service.followUser(authUser, profileUser);
        res.redirect("/t/" + username);
        return null;
    });
    /*
		 * Checks if the user is authenticated and the user to follow exists
		 */
    before("/t/:username/follow", (req, res) -> {
        String username = req.params(":username");
        User authUser = getAuthenticatedUser(req);
        User profileUser = service.getUserbyUsername(username);
        if (authUser == null) {
            res.redirect("/login");
            halt();
        } else if (profileUser == null) {
            halt(404, "User not Found");
        }
    });
    /*
		 * Removes the current user as follower of the given user.
		 */
    get("/t/:username/unfollow", (req, res) -> {
        String username = req.params(":username");
        User profileUser = service.getUserbyUsername(username);
        User authUser = getAuthenticatedUser(req);
        service.unfollowUser(authUser, profileUser);
        res.redirect("/t/" + username);
        return null;
    });
    /*
		 * Checks if the user is authenticated and the user to unfollow exists
		 */
    before("/t/:username/unfollow", (req, res) -> {
        String username = req.params(":username");
        User authUser = getAuthenticatedUser(req);
        User profileUser = service.getUserbyUsername(username);
        if (authUser == null) {
            res.redirect("/login");
            halt();
        } else if (profileUser == null) {
            halt(404, "User not Found");
        }
    });
    /*
		 * Presents the login form or redirect the user to
		 * her timeline if it's already logged in
		 */
    get("/login", (req, res) -> {
        Map<String, Object> map = new HashMap<>();
        if (req.queryParams("r") != null) {
            map.put("message", "You were successfully registered and can login now");
        }
        return new ModelAndView(map, "login.ftl");
    }, new FreeMarkerEngine());
    /*
		 * Logs the user in.
		 */
    post("/login", (req, res) -> {
        Map<String, Object> map = new HashMap<>();
        User user = new User();
        try {
            MultiMap<String> params = new MultiMap<String>();
            UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
            BeanUtils.populate(user, params);
        } catch (Exception e) {
            halt(501);
            return null;
        }
        LoginResult result = service.checkUser(user);
        if (result.getUser() != null) {
            addAuthenticatedUser(req, result.getUser());
            res.redirect("/");
            halt();
        } else {
            map.put("error", result.getError());
        }
        map.put("username", user.getUsername());
        return new ModelAndView(map, "login.ftl");
    }, new FreeMarkerEngine());
    /*
		 * Checks if the user is already authenticated
		 */
    before("/login", (req, res) -> {
        User authUser = getAuthenticatedUser(req);
        if (authUser != null) {
            res.redirect("/");
            halt();
        }
    });
    /*
		 * Presents the register form or redirect the user to
		 * her timeline if it's already logged in
		 */
    get("/register", (req, res) -> {
        Map<String, Object> map = new HashMap<>();
        return new ModelAndView(map, "register.ftl");
    }, new FreeMarkerEngine());
    /*
		 * Registers the user.
		 */
    post("/register", (req, res) -> {
        Map<String, Object> map = new HashMap<>();
        User user = new User();
        try {
            MultiMap<String> params = new MultiMap<String>();
            UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
            BeanUtils.populate(user, params);
        } catch (Exception e) {
            halt(501);
            return null;
        }
        String error = user.validate();
        if (StringUtils.isEmpty(error)) {
            User existingUser = service.getUserbyUsername(user.getUsername());
            if (existingUser == null) {
                service.registerUser(user);
                res.redirect("/login?r=1");
                halt();
            } else {
                error = "The username is already taken";
            }
        }
        map.put("error", error);
        map.put("username", user.getUsername());
        map.put("email", user.getEmail());
        return new ModelAndView(map, "register.ftl");
    }, new FreeMarkerEngine());
    /*
		 * Checks if the user is already authenticated
		 */
    before("/register", (req, res) -> {
        User authUser = getAuthenticatedUser(req);
        if (authUser != null) {
            res.redirect("/");
            halt();
        }
    });
    /*
		 * Registers a new message for the user.
		 */
    post("/message", (req, res) -> {
        User user = getAuthenticatedUser(req);
        MultiMap<String> params = new MultiMap<String>();
        UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
        Message m = new Message();
        m.setUserId(user.getId());
        m.setPubDate(new Date());
        BeanUtils.populate(m, params);
        service.addMessage(m);
        res.redirect("/");
        return null;
    });
    /*
		 * Checks if the user is authenticated
		 */
    before("/message", (req, res) -> {
        User authUser = getAuthenticatedUser(req);
        if (authUser == null) {
            res.redirect("/login");
            halt();
        }
    });
    /*
		 * Logs the user out and redirects to the public timeline
		 */
    get("/logout", (req, res) -> {
        removeAuthenticatedUser(req);
        res.redirect("/public");
        return null;
    });
}
Also used : FreeMarkerEngine(spark.template.freemarker.FreeMarkerEngine) User(com.minitwit.model.User) Message(com.minitwit.model.Message) HashMap(java.util.HashMap) LoginResult(com.minitwit.model.LoginResult) ModelAndView(spark.ModelAndView) Date(java.util.Date) MultiMap(org.eclipse.jetty.util.MultiMap)

Example 4 with ModelAndView

use of spark.ModelAndView in project gocd by gocd.

the class StatusReportsController method agentStatusReport.

public ModelAndView agentStatusReport(Request request, Response response) throws Exception {
    String pluginId = request.params("plugin_id");
    String elasticAgentId = parseElasticAgentId(request);
    String jobIdString = request.queryParams("job_id");
    long jobId;
    try {
        jobId = Long.parseLong(jobIdString);
    } catch (NumberFormatException e) {
        return errorPage(response, HttpStatus.UNPROCESSABLE_ENTITY.value(), "Agent Status Report", "Please provide a valid job_id for Agent Status Report.");
    }
    try {
        JobInstance jobInstance = jobInstanceService.buildById(jobId);
        String agentStatusReport = elasticAgentPluginService.getAgentStatusReport(pluginId, jobInstance.getIdentifier(), elasticAgentId);
        Map<Object, Object> object = new HashMap<>();
        object.put("viewTitle", "Agent Status Report");
        object.put("viewFromPlugin", agentStatusReport);
        return new ModelAndView(object, "status_reports/index.ftlh");
    } catch (RecordNotFoundException e) {
        return errorPage(response, 404, "Agent Status Report", e.getMessage());
    } catch (DataRetrievalFailureException | UnsupportedOperationException e) {
        String message = String.format("Status Report for plugin with id: '%s' for agent '%s' is not found.", pluginId, elasticAgentId);
        return errorPage(response, 404, "Agent Status Report", message);
    } catch (RulesViolationException | SecretResolutionFailureException e) {
        LOGGER.error(e.getMessage(), e);
        return errorPage(response, 500, "Agent Status Report", e.getMessage());
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return errorPage(response, 500, "Agent Status Report", UNKNOWN_ERROR_MESSAGE);
    }
}
Also used : JobInstance(com.thoughtworks.go.domain.JobInstance) HashMap(java.util.HashMap) ModelAndView(spark.ModelAndView) RulesViolationException(com.thoughtworks.go.server.exceptions.RulesViolationException) RecordNotFoundException(com.thoughtworks.go.config.exceptions.RecordNotFoundException) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) SecretResolutionFailureException(com.thoughtworks.go.plugin.access.exceptions.SecretResolutionFailureException) RulesViolationException(com.thoughtworks.go.server.exceptions.RulesViolationException) RecordNotFoundException(com.thoughtworks.go.config.exceptions.RecordNotFoundException) SecretResolutionFailureException(com.thoughtworks.go.plugin.access.exceptions.SecretResolutionFailureException) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException)

Example 5 with ModelAndView

use of spark.ModelAndView in project gocd by gocd.

the class ClickyPipelineConfigController method index.

public ModelAndView index(Request request, Response response) {
    String pipelineName = request.params("pipeline_name");
    Map<Object, Object> object = new HashMap<>() {

        {
            put("viewTitle", "Pipeline");
            put("meta", meta(pipelineName));
        }
    };
    return new ModelAndView(object, null);
}
Also used : HashMap(java.util.HashMap) ModelAndView(spark.ModelAndView) CaseInsensitiveString(com.thoughtworks.go.config.CaseInsensitiveString)

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