Search in sources :

Example 66 with Request

use of spark.Request in project gocd by gocd.

the class ConfigReposControllerV4 method index.

String index(Request req, Response res) {
    ConfigReposConfig repos = allRepos();
    ConfigReposConfig userSpecificRepos = repos.stream().filter(configRepoConfig -> authHelper.doesUserHasPermissions(currentUsername(), getAction(req), CONFIG_REPO, configRepoConfig.getId())).collect(toCollection(ConfigReposConfig::new));
    String etag = entityHashingService.hashForEntity(userSpecificRepos);
    setEtagHeader(res, etag);
    if (fresh(req, etag)) {
        return notModified(res);
    }
    return jsonizeAsTopLevelObject(req, w -> ConfigReposConfigRepresenterV4.toJSON(w, userSpecificRepos));
}
Also used : CrudController(com.thoughtworks.go.api.CrudController) EntityType(com.thoughtworks.go.config.exceptions.EntityType) MaterialConfigConverter(com.thoughtworks.go.server.service.MaterialConfigConverter) Autowired(org.springframework.beans.factory.annotation.Autowired) MessageJson(com.thoughtworks.go.api.util.MessageJson) MaterialConfig(com.thoughtworks.go.domain.materials.MaterialConfig) ConfigRepoConfig(com.thoughtworks.go.config.remote.ConfigRepoConfig) EntityHashingService(com.thoughtworks.go.server.service.EntityHashingService) Collectors.toCollection(java.util.stream.Collectors.toCollection) JsonReader(com.thoughtworks.go.api.representers.JsonReader) Request(spark.Request) SparkSpringController(com.thoughtworks.go.spark.spring.SparkSpringController) ApiVersion(com.thoughtworks.go.api.ApiVersion) MaterialUpdateService(com.thoughtworks.go.server.materials.MaterialUpdateService) Routes(com.thoughtworks.go.spark.Routes) RecordNotFoundException(com.thoughtworks.go.config.exceptions.RecordNotFoundException) ApiController(com.thoughtworks.go.api.ApiController) GsonTransformer(com.thoughtworks.go.api.util.GsonTransformer) HaltApiResponses.haltBecauseEntityAlreadyExists(com.thoughtworks.go.api.util.HaltApiResponses.haltBecauseEntityAlreadyExists) PartialConfigRepresenter(com.thoughtworks.go.apiv4.configrepos.representers.PartialConfigRepresenter) ConfigRepoService(com.thoughtworks.go.server.service.ConfigRepoService) PartialConfig(com.thoughtworks.go.config.remote.PartialConfig) ApiAuthenticationHelper(com.thoughtworks.go.api.spring.ApiAuthenticationHelper) Consumer(java.util.function.Consumer) HttpStatus(org.springframework.http.HttpStatus) OutputWriter(com.thoughtworks.go.api.base.OutputWriter) Component(org.springframework.stereotype.Component) ConfigReposConfig(com.thoughtworks.go.config.remote.ConfigReposConfig) Response(spark.Response) HttpLocalizedOperationResult(com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult) CONFIG_REPO(com.thoughtworks.go.config.policy.SupportedEntity.CONFIG_REPO) HaltApiResponses.haltBecauseEtagDoesNotMatch(com.thoughtworks.go.api.util.HaltApiResponses.haltBecauseEtagDoesNotMatch) ConfigReposConfigRepresenterV4(com.thoughtworks.go.apiv4.configrepos.representers.ConfigReposConfigRepresenterV4) Spark(spark.Spark) ConfigRepoConfigRepresenterV4(com.thoughtworks.go.apiv4.configrepos.representers.ConfigRepoConfigRepresenterV4) CachedDigestUtils.sha512_256Hex(com.thoughtworks.go.util.CachedDigestUtils.sha512_256Hex) ConfigReposConfig(com.thoughtworks.go.config.remote.ConfigReposConfig)

Example 67 with Request

use of spark.Request in project gocd by gocd.

the class StageInstanceControllerV3 method rerunSelectedJobs.

public String rerunSelectedJobs(Request req, Response res) throws IOException {
    HttpOperationResult result = new HttpOperationResult();
    haltIfRequestBodyDoesNotContainPropertyJobs(req);
    JsonReader requestBody = GsonTransformer.getInstance().jsonReaderFrom(req.body());
    List<String> requestedJobs = requestBody.readStringArrayIfPresent(JOB_NAMES_PROPERTY).get();
    Optional<Stage> optionalStage = getStageFromRequestParam(req, result);
    optionalStage.ifPresent(stage -> {
        HealthStateType healthStateType = HealthStateType.general(HealthStateScope.forStage(stage.getIdentifier().getPipelineName(), stage.getName()));
        Set<String> jobsInStage = stage.getJobInstances().stream().map(JobInstance::getName).collect(Collectors.toSet());
        List<String> unknownJobs = requestedJobs.stream().filter(jobToRun -> !jobsInStage.contains(jobToRun)).collect(Collectors.toList());
        if (unknownJobs.isEmpty()) {
            scheduleService.rerunJobs(stage, requestedJobs, result);
        } else {
            String msg = String.format("Job(s) %s does not exist in stage '%s'.", unknownJobs, stage.getIdentifier().getStageLocator());
            result.notFound(msg, "", healthStateType);
        }
    });
    return renderHTTPOperationResult(result, req, res);
}
Also used : HealthStateType(com.thoughtworks.go.serverhealth.HealthStateType) HttpOperationResult(com.thoughtworks.go.server.service.result.HttpOperationResult) Autowired(org.springframework.beans.factory.annotation.Autowired) JsonReader(com.thoughtworks.go.api.representers.JsonReader) Request(spark.Request) SparkSpringController(com.thoughtworks.go.spark.spring.SparkSpringController) NullStage(com.thoughtworks.go.domain.NullStage) ApiVersion(com.thoughtworks.go.api.ApiVersion) Routes(com.thoughtworks.go.spark.Routes) Stage(com.thoughtworks.go.domain.Stage) ApiController(com.thoughtworks.go.api.ApiController) GsonTransformer(com.thoughtworks.go.api.util.GsonTransformer) StageInstancesRepresenter(com.thoughtworks.go.apiv3.stageinstance.representers.StageInstancesRepresenter) StageRepresenter(com.thoughtworks.go.apiv3.stageinstance.representers.StageRepresenter) JobInstance(com.thoughtworks.go.domain.JobInstance) PipelineRunIdInfo(com.thoughtworks.go.domain.PipelineRunIdInfo) HaltApiResponses(com.thoughtworks.go.api.util.HaltApiResponses) Set(java.util.Set) IOException(java.io.IOException) StageInstanceModels(com.thoughtworks.go.presentation.pipelinehistory.StageInstanceModels) Collectors(java.util.stream.Collectors) ApiAuthenticationHelper(com.thoughtworks.go.api.spring.ApiAuthenticationHelper) Component(org.springframework.stereotype.Component) List(java.util.List) HealthStateScope(com.thoughtworks.go.serverhealth.HealthStateScope) Response(spark.Response) Optional(java.util.Optional) HttpLocalizedOperationResult(com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult) ScheduleService(com.thoughtworks.go.server.service.ScheduleService) StageService(com.thoughtworks.go.server.service.StageService) Spark(spark.Spark) HttpOperationResult(com.thoughtworks.go.server.service.result.HttpOperationResult) JsonReader(com.thoughtworks.go.api.representers.JsonReader) NullStage(com.thoughtworks.go.domain.NullStage) Stage(com.thoughtworks.go.domain.Stage) HealthStateType(com.thoughtworks.go.serverhealth.HealthStateType)

Example 68 with Request

use of spark.Request in project gocd by gocd.

the class WebhookRequestTest method mockRequest.

private Request mockRequest(String body) {
    final Request req = mock(Request.class);
    when(req.body()).thenReturn(body);
    when(req.contentType()).thenReturn(APPLICATION_JSON_VALUE);
    return req;
}
Also used : Request(spark.Request)

Example 69 with Request

use of spark.Request in project gocd by gocd.

the class RoutesHelperTest method shouldSendHttpExceptionResponseBasedOnAcceptHeader.

@ParameterizedTest
@MethodSource("data")
void shouldSendHttpExceptionResponseBasedOnAcceptHeader(Data data) {
    Request request = mock(Request.class);
    Response response = mock(Response.class);
    when(request.headers("Accept")).thenReturn(data.mimeType);
    new RoutesHelper(mock(SparkController.class)).httpException(new RecordNotFoundException("Boom!!"), request, response);
    verify(response).body(data.responseText);
}
Also used : Response(spark.Response) RecordNotFoundException(com.thoughtworks.go.config.exceptions.RecordNotFoundException) Request(spark.Request) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 70 with Request

use of spark.Request in project MtgDesktopCompanion by nicho92.

the class JSONHttpServer method start.

@Override
public void start() throws IOException {
    port(getInt("SERVER-PORT"));
    exception(Exception.class, new ExceptionHandler<Exception>() {

        @Override
        public void handle(Exception exception, Request req, Response res) {
            res.status(500);
            res.body("{\"error\":\"" + exception + "\"}");
        }
    });
    notFound((req, res) -> {
        res.status(404);
        return "{\"error\":\"not found\"}";
    });
    before("/*", (request, response) -> {
        response.type(getString("MIME"));
        logger.info("Received api call from " + request.ip());
    });
    get("/cards/search/:att/:val", getString("MIME"), (request, response) -> {
        return MTGControler.getInstance().getEnabledProviders().searchCardByCriteria(request.params(":att"), request.params(":val"), null, false);
    }, transformer);
    post("/cards/move/:from/:to/:id", getString("MIME"), (request, response) -> {
        MagicCollection from = new MagicCollection(request.params(":from"));
        MagicCollection to = new MagicCollection(request.params(":to"));
        MagicCard mc = MTGControler.getInstance().getEnabledProviders().getCardById(request.params(":id"));
        MTGControler.getInstance().getEnabledDAO().removeCard(mc, from);
        MTGControler.getInstance().getEnabledDAO().saveCard(mc, to);
        return "OK";
    }, transformer);
    get("/cards/list/:col/:idEd", getString("MIME"), (request, response) -> {
        MagicCollection col = new MagicCollection(request.params(":col"));
        MagicEdition ed = new MagicEdition();
        ed.setId(request.params(":idEd"));
        ed.setSet(request.params(":idEd"));
        return MTGControler.getInstance().getEnabledDAO().listCardsFromCollection(col, ed);
    }, transformer);
    get("/cards/:id", getString("MIME"), (request, response) -> {
        return MTGControler.getInstance().getEnabledProviders().getCardById(request.params(":id"));
    }, transformer);
    get("/collections/list", getString("MIME"), (request, response) -> {
        return MTGControler.getInstance().getEnabledDAO().getCollections();
    }, transformer);
    get("/collections/:name", getString("MIME"), (request, response) -> {
        return MTGControler.getInstance().getEnabledDAO().getCollection(request.params(":name"));
    }, transformer);
    get("/editions/list", getString("MIME"), (request, response) -> {
        return MTGControler.getInstance().getEnabledProviders().loadEditions();
    }, transformer);
    get("/editions/:idSet", getString("MIME"), (request, response) -> {
        return MTGControler.getInstance().getEnabledProviders().getSetById(request.params(":idSet"));
    }, transformer);
    get("/editions/list/:colName", getString("MIME"), (request, response) -> {
        List<MagicEdition> eds = new ArrayList<>();
        List<String> list = MTGControler.getInstance().getEnabledDAO().getEditionsIDFromCollection(new MagicCollection(request.params(":colName")));
        for (String s : list) eds.add(MTGControler.getInstance().getEnabledProviders().getSetById(s));
        Collections.sort(eds);
        return eds;
    }, transformer);
    get("/prices/:idSet/:name", getString("MIME"), (request, response) -> {
        MagicCard mc = MTGControler.getInstance().getEnabledProviders().searchCardByCriteria("name", request.params(":name"), null, false).get(0);
        MagicEdition ed = MTGControler.getInstance().getEnabledProviders().getSetById(request.params(":idSet"));
        List<MagicPrice> pricesret = new ArrayList<>();
        for (MTGPricesProvider prices : MTGControler.getInstance().getEnabledPricers()) pricesret.addAll(prices.getPrice(ed, mc));
        return pricesret;
    }, transformer);
    if (getBoolean("ENABLE_GZIP")) {
        after((request, response) -> {
            response.header("Content-Encoding", "gzip");
        });
    }
    Spark.init();
    logger.info("Server start on port " + getString("SERVER-PORT"));
    running = true;
}
Also used : MTGPricesProvider(org.magic.api.interfaces.MTGPricesProvider) MagicPrice(org.magic.api.beans.MagicPrice) Request(spark.Request) MagicEdition(org.magic.api.beans.MagicEdition) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Response(spark.Response) MagicCard(org.magic.api.beans.MagicCard) MagicCollection(org.magic.api.beans.MagicCollection)

Aggregations

Request (spark.Request)70 ApiRouteService (com.searchcode.app.service.route.ApiRouteService)35 RepoResultApiResponse (com.searchcode.app.dto.api.RepoResultApiResponse)33 Helpers (com.searchcode.app.util.Helpers)31 LoggerWrapper (com.searchcode.app.util.LoggerWrapper)31 SQLiteRepo (com.searchcode.app.dao.SQLiteRepo)28 ApiResponse (com.searchcode.app.dto.api.ApiResponse)28 Response (spark.Response)17 RepoResult (com.searchcode.app.model.RepoResult)11 AdminRouteService (com.searchcode.app.service.route.AdminRouteService)8 CodeRouteService (com.searchcode.app.service.route.CodeRouteService)7 Collectors (java.util.stream.Collectors)5 IndexService (com.searchcode.app.service.index.IndexService)4 IOException (java.io.IOException)4 Autowired (org.springframework.beans.factory.annotation.Autowired)4 Spark (spark.Spark)4 ValidatorResult (com.searchcode.app.model.ValidatorResult)3 ApiController (com.thoughtworks.go.api.ApiController)3 ApiVersion (com.thoughtworks.go.api.ApiVersion)3 JsonReader (com.thoughtworks.go.api.representers.JsonReader)3