Search in sources :

Example 6 with Response

use of spark.Response in project spark by perwendel.

the class FilterExample method main.

public static void main(String[] args) {
    usernamePasswords.put("foo", "bar");
    usernamePasswords.put("admin", "admin");
    before(new Filter() {

        @Override
        public void handle(Request request, Response response) {
            String user = request.queryParams("user");
            String password = request.queryParams("password");
            String dbPassword = usernamePasswords.get(user);
            if (!(password != null && password.equals(dbPassword))) {
                halt(401, "You are not welcome here!!!");
            }
        }
    });
    before("/hello", (request, response) -> {
        response.header("Foo", "Set by second before filter");
    });
    get("/hello", (request, response) -> {
        return "Hello World!";
    });
    after("/hello", (request, response) -> {
        response.header("spark", "added by after-filter");
    });
}
Also used : Response(spark.Response) Filter(spark.Filter) Request(spark.Request)

Example 7 with Response

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

the class CodeRouteServiceTest method testGetCodeWithParamsWithMatch.

public void testGetCodeWithParamsWithMatch() {
    Request request = Mockito.mock(Request.class);
    Response response = Mockito.mock(Response.class);
    CodeSearcher codeSearcher = Mockito.mock(CodeSearcher.class);
    CodeRouteService codeRouteService = new CodeRouteService(codeSearcher);
    CodeResult codeResult = new CodeResult(new ArrayList<String>(), new ArrayList<CodeMatchResult>());
    codeResult.setCodeLines("100");
    codeResult.setLanguageName("LanguageName");
    codeResult.setMd5hash("md5hash");
    codeResult.setRepoName("myRepo");
    codeResult.setRepoLocation("repoLocation");
    codeResult.setCodeOwner("codeOwner");
    when(request.params(":codeid")).thenReturn("MATCH-MOCK");
    when(codeSearcher.getByCodeId("MATCH-MOCK")).thenReturn(codeResult);
    Map<String, Object> map = codeRouteService.getCode(request, response);
    assertThat(map.get("codePath")).isEqualTo("/");
    assertThat(map.get("codeLength")).isEqualTo("100");
    assertThat(map.get("languageName")).isEqualTo("LanguageName");
    assertThat(map.get("md5Hash")).isEqualTo("md5hash");
    assertThat(map.get("repoName")).isEqualTo("myRepo");
    assertThat(map.get("highlight")).isEqualTo(true);
    assertThat(map.get("repoLocation")).isEqualTo("repoLocation");
    assertThat(map.get("codeValue")).isEqualTo("");
    assertThat(map.get("highligher")).isNotNull();
    assertThat(map.get("codeOwner")).isEqualTo("codeOwner");
    assertThat(map.get("owaspResults")).isNotNull();
    assertThat(map.get("logoImage")).isNotNull();
    assertThat(map.get("isCommunity")).isEqualTo(App.ISCOMMUNITY);
    assertThat(map.get("estimatedCost")).isNull();
}
Also used : Response(spark.Response) CodeRouteService(com.searchcode.app.service.route.CodeRouteService) Request(spark.Request) CodeResult(com.searchcode.app.dto.CodeResult) CodeMatchResult(com.searchcode.app.dto.CodeMatchResult)

Example 8 with Response

use of spark.Response 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 Response

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

the class SearchRouteService method codeSearch.

public SearchResult codeSearch(Request request, Response response) {
    CodeSearcher cs = new CodeSearcher();
    CodeMatcher cm = new CodeMatcher(Singleton.getData());
    SearchcodeLib scl = Singleton.getSearchcodeLib(Singleton.getData());
    if (request.queryParams().contains("q") && !request.queryParams("q").trim().equals(Values.EMPTYSTRING)) {
        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;
            }
        }
        String[] repos;
        String[] langs;
        String[] owners;
        String reposFilter = Values.EMPTYSTRING;
        String langsFilter = Values.EMPTYSTRING;
        String ownersFilter = 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.replace(" ", "_"))).collect(Collectors.toList());
                reposFilter = " && (" + StringUtils.join(reposList, " || ") + ")";
            }
        }
        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.replace(" ", "_"))).collect(Collectors.toList());
                langsFilter = " && (" + StringUtils.join(langsList, " || ") + ")";
            }
        }
        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.replace(" ", "_"))).collect(Collectors.toList());
                ownersFilter = " && (" + StringUtils.join(ownersList, " || ") + ")";
            }
        }
        // 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));
        searchResult.setQuery(query);
        for (String altQuery : scl.generateAltQueries(query)) {
            searchResult.addAltQuery(altQuery);
        }
        // Null out code as it isnt required and there is no point in bloating our ajax requests
        for (CodeResult codeSearchResult : searchResult.getCodeResultList()) {
            codeSearchResult.setCode(null);
        }
        return searchResult;
    }
    return null;
}
Also used : Arrays(java.util.Arrays) SearchResult(com.searchcode.app.dto.SearchResult) Singleton(com.searchcode.app.service.Singleton) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) Values(com.searchcode.app.config.Values) CodeMatcher(com.searchcode.app.service.CodeMatcher) SearchcodeLib(com.searchcode.app.util.SearchcodeLib) List(java.util.List) CodeResult(com.searchcode.app.dto.CodeResult) CodeSearcher(com.searchcode.app.service.CodeSearcher) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) Request(spark.Request) Response(spark.Response) SearchcodeLib(com.searchcode.app.util.SearchcodeLib) CodeResult(com.searchcode.app.dto.CodeResult) CodeMatcher(com.searchcode.app.service.CodeMatcher) SearchResult(com.searchcode.app.dto.SearchResult) CodeSearcher(com.searchcode.app.service.CodeSearcher)

Example 10 with Response

use of spark.Response in project waltz by khartec.

the class Main method enableGZIP.

private void enableGZIP() {
    SettingsService settingsService = ctx.getBean(SettingsService.class);
    Boolean gzipEnabled = settingsService.getValue(GZIP_ENABLED_NAME).map(x -> x.equalsIgnoreCase("true")).orElse(false);
    if (gzipEnabled) {
        // now fetch the minimum size
        int minimumLength = settingsService.getValue(GZIP_MIN_SIZE_NAME).map(Integer::parseInt).orElse(8192);
        after(((request, response) -> {
            if (response.body() != null && response.body().length() >= minimumLength) {
                response.header("Content-Encoding", "gzip");
            }
        }));
        LOG.info("Enabled GZIP (size: " + minimumLength + ")");
    } else {
        LOG.info("GZIP not enabled");
    }
}
Also used : Endpoint(com.khartec.waltz.web.endpoints.Endpoint) WebUtilities.reportException(com.khartec.waltz.web.WebUtilities.reportException) Logger(org.slf4j.Logger) StaticResourcesEndpoint(com.khartec.waltz.web.endpoints.api.StaticResourcesEndpoint) LoggerFactory(org.slf4j.LoggerFactory) BaseDataExtractor(com.khartec.waltz.web.endpoints.extracts.BaseDataExtractor) SettingsService(com.khartec.waltz.service.settings.SettingsService) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) DuplicateKeyException(com.khartec.waltz.common.exception.DuplicateKeyException) LoggingUtilities(com.khartec.waltz.common.LoggingUtilities) DIConfiguration(com.khartec.waltz.service.DIConfiguration) InsufficientPrivelegeException(com.khartec.waltz.common.exception.InsufficientPrivelegeException) Request(spark.Request) Map(java.util.Map) Response(spark.Response) Spark(spark.Spark) SettingsService(com.khartec.waltz.service.settings.SettingsService) Endpoint(com.khartec.waltz.web.endpoints.Endpoint) StaticResourcesEndpoint(com.khartec.waltz.web.endpoints.api.StaticResourcesEndpoint)

Aggregations

Response (spark.Response)10 Request (spark.Request)9 CodeRouteService (com.searchcode.app.service.route.CodeRouteService)4 HaltException (spark.HaltException)4 Values (com.searchcode.app.config.Values)2 CodeResult (com.searchcode.app.dto.CodeResult)2 CodeMatcher (com.searchcode.app.service.CodeMatcher)2 CodeSearcher (com.searchcode.app.service.CodeSearcher)2 Singleton (com.searchcode.app.service.Singleton)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 StringUtils (org.apache.commons.lang3.StringUtils)2 QueryParser (org.apache.lucene.queryparser.classic.QueryParser)2 Gson (com.google.gson.Gson)1 LoggingUtilities (com.khartec.waltz.common.LoggingUtilities)1 DuplicateKeyException (com.khartec.waltz.common.exception.DuplicateKeyException)1 InsufficientPrivelegeException (com.khartec.waltz.common.exception.InsufficientPrivelegeException)1 DIConfiguration (com.khartec.waltz.service.DIConfiguration)1 SettingsService (com.khartec.waltz.service.settings.SettingsService)1 WebUtilities.reportException (com.khartec.waltz.web.WebUtilities.reportException)1