Search in sources :

Example 11 with Context

use of io.javalin.http.Context in project teku by ConsenSys.

the class PostVoluntaryExit method handle.

@OpenApi(path = ROUTE, method = HttpMethod.POST, summary = "Submit signed voluntary exit", tags = { TAG_BEACON }, description = "Submits signed voluntary exit object to node's pool and if it passes validation node MUST broadcast it to network.", requestBody = @OpenApiRequestBody(content = { @OpenApiContent(from = SignedVoluntaryExit.class) }), responses = { @OpenApiResponse(status = RES_OK, description = "Signed voluntary exit has been successfully validated, added to the pool, and broadcast."), @OpenApiResponse(status = RES_BAD_REQUEST, description = "Invalid voluntary exit, it will never pass validation so it's rejected"), @OpenApiResponse(status = RES_INTERNAL_ERROR) })
@Override
public void handle(final Context ctx) throws Exception {
    try {
        final SignedVoluntaryExit exit = parseRequestBody(ctx.body(), SignedVoluntaryExit.class);
        ctx.future(nodeDataProvider.postVoluntaryExit(exit).thenApplyChecked(result -> handleResponseContext(ctx, result)));
    } catch (final IllegalArgumentException e) {
        LOG.debug("Voluntary exit failed", e);
        ctx.json(BadRequest.badRequest(jsonProvider, e.getMessage()));
        ctx.status(SC_BAD_REQUEST);
    }
}
Also used : SC_BAD_REQUEST(tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_BAD_REQUEST) HttpMethod(io.javalin.plugin.openapi.annotations.HttpMethod) SignedVoluntaryExit(tech.pegasys.teku.api.schema.SignedVoluntaryExit) AbstractHandler(tech.pegasys.teku.beaconrestapi.handlers.AbstractHandler) BadRequest(tech.pegasys.teku.beaconrestapi.schema.BadRequest) TAG_BEACON(tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_BEACON) OpenApiContent(io.javalin.plugin.openapi.annotations.OpenApiContent) ValidationResultCode(tech.pegasys.teku.statetransition.validation.ValidationResultCode) RES_INTERNAL_ERROR(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_INTERNAL_ERROR) Logger(org.apache.logging.log4j.Logger) RES_BAD_REQUEST(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_BAD_REQUEST) Context(io.javalin.http.Context) OpenApiResponse(io.javalin.plugin.openapi.annotations.OpenApiResponse) RES_OK(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_OK) JsonProvider(tech.pegasys.teku.provider.JsonProvider) NodeDataProvider(tech.pegasys.teku.api.NodeDataProvider) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi) OpenApiRequestBody(io.javalin.plugin.openapi.annotations.OpenApiRequestBody) LogManager(org.apache.logging.log4j.LogManager) DataProvider(tech.pegasys.teku.api.DataProvider) InternalValidationResult(tech.pegasys.teku.statetransition.validation.InternalValidationResult) SC_OK(tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_OK) SignedVoluntaryExit(tech.pegasys.teku.api.schema.SignedVoluntaryExit) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi)

Example 12 with Context

use of io.javalin.http.Context in project emfcloud-modelserver by eclipse-emfcloud.

the class DefaultModelControllerTest method getOneXmiFormat.

@Test
public void getOneXmiFormat() throws EncodingException {
    final AtomicReference<JsonNode> response = new AtomicReference<>();
    final EClass brewingUnit = EcoreFactory.eINSTANCE.createEClass();
    Answer<Void> answer = invocation -> {
        response.set(invocation.getArgument(0));
        return null;
    };
    doAnswer(answer).when(context).json(any(JsonNode.class));
    final LinkedHashMap<String, List<String>> queryParams = new LinkedHashMap<>();
    queryParams.put(ModelServerPathParametersV1.FORMAT, Collections.singletonList(ModelServerPathParametersV1.FORMAT_XMI));
    when(context.queryParamMap()).thenReturn(queryParams);
    when(modelRepository.getModel("test")).thenReturn(Optional.of(brewingUnit));
    modelController.getOne(context, "test");
    assertThat(response.get().get(JsonResponseMember.DATA), is(equalTo(new XmiCodec().encode(brewingUnit))));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) EcoreFactory(org.eclipse.emf.ecore.EcoreFactory) CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) CCommandExecutionResult(org.eclipse.emfcloud.modelserver.command.CCommandExecutionResult) PatchCommandHandler(org.eclipse.emfcloud.modelserver.emf.patch.PatchCommandHandler) MockitoHamcrest.argThat(org.mockito.hamcrest.MockitoHamcrest.argThat) Context(io.javalin.http.Context) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) JsonPatchHelper(org.eclipse.emfcloud.modelserver.emf.util.JsonPatchHelper) JsonNode(com.fasterxml.jackson.databind.JsonNode) Json(org.eclipse.emfcloud.modelserver.jsonschema.Json) CCommandFactory(org.eclipse.emfcloud.modelserver.command.CCommandFactory) ServerConfiguration(org.eclipse.emfcloud.modelserver.emf.configuration.ServerConfiguration) JsonResource(org.eclipse.emfcloud.jackson.resource.JsonResource) EObject(org.eclipse.emf.ecore.EObject) Collectors(java.util.stream.Collectors) List(java.util.List) EcoreResourceFactoryImpl(org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl) Entry(java.util.Map.Entry) Resource(org.eclipse.emf.ecore.resource.Resource) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) DecodingException(org.eclipse.emfcloud.modelserver.common.codecs.DecodingException) EMFCommandType(org.eclipse.emfcloud.modelserver.edit.EMFCommandType) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) ResourceImpl(org.eclipse.emf.ecore.resource.impl.ResourceImpl) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) URI(org.eclipse.emf.common.util.URI) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) EMFModule(org.eclipse.emfcloud.jackson.module.EMFModule) CommandExecutionType(org.eclipse.emfcloud.modelserver.edit.CommandExecutionType) CodecsManager(org.eclipse.emfcloud.modelserver.emf.common.codecs.CodecsManager) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) CustomTypeSafeMatcher(org.hamcrest.CustomTypeSafeMatcher) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) CCommand(org.eclipse.emfcloud.modelserver.command.CCommand) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) LinkedHashMap(java.util.LinkedHashMap) TypeSafeDiagnosingMatcher(org.hamcrest.TypeSafeDiagnosingMatcher) Json.prop(org.eclipse.emfcloud.modelserver.jsonschema.Json.prop) Answer(org.mockito.stubbing.Answer) EAttribute(org.eclipse.emf.ecore.EAttribute) EClass(org.eclipse.emf.ecore.EClass) Suppliers(com.google.common.base.Suppliers) EMFMatchers.eEqualTo(org.eclipse.emfcloud.modelserver.tests.util.EMFMatchers.eEqualTo) EncodingException(org.eclipse.emfcloud.modelserver.common.codecs.EncodingException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) XmiCodec(org.eclipse.emfcloud.modelserver.common.codecs.XmiCodec) Before(org.junit.Before) InjectMocks(org.mockito.InjectMocks) Description(org.hamcrest.Description) MockitoHamcrest.intThat(org.mockito.hamcrest.MockitoHamcrest.intThat) EcoreUtil(org.eclipse.emf.ecore.util.EcoreUtil) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) ResourceSetImpl(org.eclipse.emf.ecore.resource.impl.ResourceSetImpl) File(java.io.File) Mockito.verify(org.mockito.Mockito.verify) DICodecsManager(org.eclipse.emfcloud.modelserver.emf.common.codecs.DICodecsManager) ModelServerPathParametersV2(org.eclipse.emfcloud.modelserver.common.ModelServerPathParametersV2) FeatureMatcher(org.hamcrest.FeatureMatcher) ModelServerPathParametersV1(org.eclipse.emfcloud.modelserver.common.ModelServerPathParametersV1) Matcher(org.hamcrest.Matcher) OSUtil.osLineSeparator(org.eclipse.emfcloud.modelserver.tests.util.OSUtil.osLineSeparator) Collections(java.util.Collections) JsonCodec(org.eclipse.emfcloud.modelserver.emf.common.codecs.JsonCodec) EClass(org.eclipse.emf.ecore.EClass) JsonNode(com.fasterxml.jackson.databind.JsonNode) AtomicReference(java.util.concurrent.atomic.AtomicReference) List(java.util.List) XmiCodec(org.eclipse.emfcloud.modelserver.common.codecs.XmiCodec) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 13 with Context

use of io.javalin.http.Context in project emfcloud-modelserver by eclipse-emfcloud.

the class DefaultModelControllerTest method getOneJsonFormat.

@Test
public void getOneJsonFormat() throws EncodingException {
    final AtomicReference<JsonNode> response = new AtomicReference<>();
    final EClass brewingUnit = EcoreFactory.eINSTANCE.createEClass();
    Answer<Void> answer = invocation -> {
        response.set(invocation.getArgument(0));
        return null;
    };
    doAnswer(answer).when(context).json(any(JsonNode.class));
    when(modelRepository.getModel("test")).thenReturn(Optional.of(brewingUnit));
    modelController.getOne(context, "test");
    assertThat(response.get().get(JsonResponseMember.DATA), is(equalTo(new JsonCodec().encode(brewingUnit))));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) EcoreFactory(org.eclipse.emf.ecore.EcoreFactory) CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) CCommandExecutionResult(org.eclipse.emfcloud.modelserver.command.CCommandExecutionResult) PatchCommandHandler(org.eclipse.emfcloud.modelserver.emf.patch.PatchCommandHandler) MockitoHamcrest.argThat(org.mockito.hamcrest.MockitoHamcrest.argThat) Context(io.javalin.http.Context) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) JsonPatchHelper(org.eclipse.emfcloud.modelserver.emf.util.JsonPatchHelper) JsonNode(com.fasterxml.jackson.databind.JsonNode) Json(org.eclipse.emfcloud.modelserver.jsonschema.Json) CCommandFactory(org.eclipse.emfcloud.modelserver.command.CCommandFactory) ServerConfiguration(org.eclipse.emfcloud.modelserver.emf.configuration.ServerConfiguration) JsonResource(org.eclipse.emfcloud.jackson.resource.JsonResource) EObject(org.eclipse.emf.ecore.EObject) Collectors(java.util.stream.Collectors) List(java.util.List) EcoreResourceFactoryImpl(org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl) Entry(java.util.Map.Entry) Resource(org.eclipse.emf.ecore.resource.Resource) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) DecodingException(org.eclipse.emfcloud.modelserver.common.codecs.DecodingException) EMFCommandType(org.eclipse.emfcloud.modelserver.edit.EMFCommandType) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) ResourceImpl(org.eclipse.emf.ecore.resource.impl.ResourceImpl) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) URI(org.eclipse.emf.common.util.URI) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) EMFModule(org.eclipse.emfcloud.jackson.module.EMFModule) CommandExecutionType(org.eclipse.emfcloud.modelserver.edit.CommandExecutionType) CodecsManager(org.eclipse.emfcloud.modelserver.emf.common.codecs.CodecsManager) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) CustomTypeSafeMatcher(org.hamcrest.CustomTypeSafeMatcher) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) CCommand(org.eclipse.emfcloud.modelserver.command.CCommand) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) LinkedHashMap(java.util.LinkedHashMap) TypeSafeDiagnosingMatcher(org.hamcrest.TypeSafeDiagnosingMatcher) Json.prop(org.eclipse.emfcloud.modelserver.jsonschema.Json.prop) Answer(org.mockito.stubbing.Answer) EAttribute(org.eclipse.emf.ecore.EAttribute) EClass(org.eclipse.emf.ecore.EClass) Suppliers(com.google.common.base.Suppliers) EMFMatchers.eEqualTo(org.eclipse.emfcloud.modelserver.tests.util.EMFMatchers.eEqualTo) EncodingException(org.eclipse.emfcloud.modelserver.common.codecs.EncodingException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) XmiCodec(org.eclipse.emfcloud.modelserver.common.codecs.XmiCodec) Before(org.junit.Before) InjectMocks(org.mockito.InjectMocks) Description(org.hamcrest.Description) MockitoHamcrest.intThat(org.mockito.hamcrest.MockitoHamcrest.intThat) EcoreUtil(org.eclipse.emf.ecore.util.EcoreUtil) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) ResourceSetImpl(org.eclipse.emf.ecore.resource.impl.ResourceSetImpl) File(java.io.File) Mockito.verify(org.mockito.Mockito.verify) DICodecsManager(org.eclipse.emfcloud.modelserver.emf.common.codecs.DICodecsManager) ModelServerPathParametersV2(org.eclipse.emfcloud.modelserver.common.ModelServerPathParametersV2) FeatureMatcher(org.hamcrest.FeatureMatcher) ModelServerPathParametersV1(org.eclipse.emfcloud.modelserver.common.ModelServerPathParametersV1) Matcher(org.hamcrest.Matcher) OSUtil.osLineSeparator(org.eclipse.emfcloud.modelserver.tests.util.OSUtil.osLineSeparator) Collections(java.util.Collections) JsonCodec(org.eclipse.emfcloud.modelserver.emf.common.codecs.JsonCodec) EClass(org.eclipse.emf.ecore.EClass) JsonCodec(org.eclipse.emfcloud.modelserver.emf.common.codecs.JsonCodec) JsonNode(com.fasterxml.jackson.databind.JsonNode) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 14 with Context

use of io.javalin.http.Context in project cineast by vitrivr.

the class SelectFromTablePostHandler method performPost.

@Override
public SelectResult performPost(SelectSpecification input, Context ctx) {
    if (input == null || input.getTable().isEmpty() || input.getColumns().isEmpty()) {
        LOGGER.warn("returning empty list, invalid input {}", input);
        return new SelectResult(new ArrayList<>());
    }
    StopWatch watch = StopWatch.createStarted();
    selector.open(input.getTable());
    List<Map<String, PrimitiveTypeProvider>> _result = selector.getAll(input.getColumns(), input.getLimit());
    List<Map<String, String>> stringified = _result.stream().map(el -> {
        Map<String, String> m = new HashMap<>();
        el.forEach((k, v) -> m.put(k, v.getString()));
        return m;
    }).collect(Collectors.toList());
    watch.stop();
    LOGGER.trace("Performed select on {}.{} in {} ms", input.getTable(), input.getColumns(), watch.getTime(TimeUnit.MILLISECONDS));
    return new SelectResult(stringified);
}
Also used : DBSelector(org.vitrivr.cineast.core.db.DBSelector) SelectResult(org.vitrivr.cineast.api.messages.result.SelectResult) HashMap(java.util.HashMap) StopWatch(org.apache.commons.lang3.time.StopWatch) Collectors(java.util.stream.Collectors) OpenApiDocumentation(io.javalin.plugin.openapi.dsl.OpenApiDocumentation) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) SelectSpecification(org.vitrivr.cineast.api.messages.lookup.SelectSpecification) Logger(org.apache.logging.log4j.Logger) PrimitiveTypeProvider(org.vitrivr.cineast.core.data.providers.primitive.PrimitiveTypeProvider) Context(io.javalin.http.Context) Map(java.util.Map) ParsingPostRestHandler(org.vitrivr.cineast.api.rest.handlers.interfaces.ParsingPostRestHandler) LogManager(org.apache.logging.log4j.LogManager) OpenApiBuilder(io.javalin.plugin.openapi.dsl.OpenApiBuilder) Config(org.vitrivr.cineast.standalone.config.Config) SelectResult(org.vitrivr.cineast.api.messages.result.SelectResult) HashMap(java.util.HashMap) Map(java.util.Map) StopWatch(org.apache.commons.lang3.time.StopWatch)

Example 15 with Context

use of io.javalin.http.Context in project AuthGuard by AuthGuard.

the class ApplicationsRoute method create.

public void create(final Context context) {
    final String idempotentKey = IdempotencyHeader.getKeyOrFail(context);
    final CreateAppRequestDTO request = appRequestRequestBodyHandler.getValidated(context);
    final RequestContextBO requestContext = RequestContextBO.builder().idempotentKey(idempotentKey).source(context.ip()).build();
    final Optional<Object> created = Optional.of(restMapper.toBO(request)).map(appBO -> applicationsService.create(appBO, requestContext)).map(restMapper::toDTO);
    if (created.isPresent()) {
        context.status(201).json(created.get());
    } else {
        context.status(400).json(new Error("400", "Failed to create application"));
    }
}
Also used : ApiKeysService(com.nexblocks.authguard.service.ApiKeysService) AppDTO(com.nexblocks.authguard.api.dto.entities.AppDTO) ApplicationsApi(com.nexblocks.authguard.api.routes.ApplicationsApi) ApiKeyDTO(com.nexblocks.authguard.api.dto.entities.ApiKeyDTO) RequestContextBO(com.nexblocks.authguard.service.model.RequestContextBO) Inject(com.google.inject.Inject) Collectors(java.util.stream.Collectors) List(java.util.List) BodyHandler(com.nexblocks.authguard.rest.util.BodyHandler) Error(com.nexblocks.authguard.api.dto.entities.Error) RestJsonMapper(com.nexblocks.authguard.rest.mappers.RestJsonMapper) RestMapper(com.nexblocks.authguard.rest.mappers.RestMapper) Context(io.javalin.http.Context) Optional(java.util.Optional) CreateAppRequestDTO(com.nexblocks.authguard.api.dto.requests.CreateAppRequestDTO) IdempotencyHeader(com.nexblocks.authguard.rest.util.IdempotencyHeader) ApplicationsService(com.nexblocks.authguard.service.ApplicationsService) CreateAppRequestDTO(com.nexblocks.authguard.api.dto.requests.CreateAppRequestDTO) RequestContextBO(com.nexblocks.authguard.service.model.RequestContextBO) Error(com.nexblocks.authguard.api.dto.entities.Error)

Aggregations

Context (io.javalin.http.Context)16 List (java.util.List)13 Optional (java.util.Optional)10 Map (java.util.Map)9 Collectors (java.util.stream.Collectors)9 Handler (io.javalin.http.Handler)5 HttpMethod (io.javalin.plugin.openapi.annotations.HttpMethod)5 OpenApi (io.javalin.plugin.openapi.annotations.OpenApi)5 OpenApiContent (io.javalin.plugin.openapi.annotations.OpenApiContent)5 OpenApiResponse (io.javalin.plugin.openapi.annotations.OpenApiResponse)5 Inject (com.google.inject.Inject)4 Error (com.nexblocks.authguard.api.dto.entities.Error)4 RestMapper (com.nexblocks.authguard.rest.mappers.RestMapper)4 BodyHandler (com.nexblocks.authguard.rest.util.BodyHandler)4 IdempotencyHeader (com.nexblocks.authguard.rest.util.IdempotencyHeader)4 File (java.io.File)4 IOException (java.io.IOException)4 Collections (java.util.Collections)3 SC_BAD_REQUEST (javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST)3 DataProvider (tech.pegasys.teku.api.DataProvider)3