Search in sources :

Example 11 with APIResponses

use of org.eclipse.microprofile.openapi.annotations.responses.APIResponses in project automatiko-engine by automatiko-io.

the class ProcessInstanceManagementResource method getInstanceImage.

@APIResponses(value = { @APIResponse(responseCode = "404", description = "In case of instance with given id was not found", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "200", description = "List of available processes", content = @Content(mediaType = "application/json")) })
@Operation(summary = "Returns process instance image with annotated active nodes")
@SuppressWarnings("unchecked")
@GET()
@Path("/{processId}/instances/{instanceId}/image")
@Produces(MediaType.APPLICATION_SVG_XML)
public Response getInstanceImage(@Parameter(description = "Unique identifier of the process", required = true) @PathParam("processId") String processId, @Parameter(description = "Unique identifier of the instance", required = true) @PathParam("instanceId") String instanceId, @Parameter(description = "Status of the process instance", required = false, schema = @Schema(enumeration = { "active", "completed", "aborted", "error" })) @QueryParam("status") @DefaultValue("active") final String status, @Parameter(description = "User identifier as alternative autroization info", required = false, hidden = true) @QueryParam("user") final String user, @Parameter(description = "Groups as alternative autroization info", required = false, hidden = true) @QueryParam("group") final List<String> groups) {
    try {
        identitySupplier.buildIdentityProvider(user, groups);
        return UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            Process<?> process = processData.get(processId);
            String image = process.image();
            if (image == null) {
                throw new ProcessImageNotFoundException(process.id());
            }
            Optional<ProcessInstance<?>> instance = (Optional<ProcessInstance<?>>) process.instances().findById(instanceId, mapStatus(status), ProcessInstanceReadMode.READ_ONLY);
            if (instance.isEmpty()) {
                throw new ProcessInstanceNotFoundException(instanceId);
            }
            String path = ((AbstractProcess<?>) process).process().getId() + "/" + instanceId;
            if (process.version() != null) {
                path = "/v" + process.version().replaceAll("\\.", "_") + "/" + path;
            }
            ResponseBuilder builder = Response.ok().entity(instance.get().image(path));
            return builder.header("Content-Type", "image/svg+xml").build();
        });
    } finally {
        IdentityProvider.set(null);
    }
}
Also used : Optional(java.util.Optional) ProcessImageNotFoundException(io.automatiko.engine.api.workflow.ProcessImageNotFoundException) JsonExportedProcessInstance(io.automatiko.engine.addons.process.management.model.JsonExportedProcessInstance) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) ArchivedProcessInstance(io.automatiko.engine.api.workflow.ArchivedProcessInstance) ProcessInstanceNotFoundException(io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 12 with APIResponses

use of org.eclipse.microprofile.openapi.annotations.responses.APIResponses in project policies-ui-backend by RedHatInsights.

the class PolicyCrudService method storePolicy.

@Operation(summary = "Validate (and possibly persist) a passed policy for the given account")
@Parameter(name = "alsoStore", description = "If passed and set to true, the passed policy is also persisted (if it is valid)")
@APIResponses({ @APIResponse(responseCode = "500", description = "Internal error"), @APIResponse(responseCode = "400", description = "No policy provided or policy validation failed", content = @Content(schema = @Schema(implementation = Msg.class))), @APIResponse(responseCode = "409", description = "Persisting failed", content = @Content(schema = @Schema(implementation = Msg.class))), @APIResponse(responseCode = "403", description = "Individual permissions missing to complete action"), @APIResponse(responseCode = "201", description = "Policy persisted", content = @Content(schema = @Schema(implementation = Policy.class))), @APIResponse(responseCode = "200", description = "Policy validated") })
@POST
@Path("/")
@Transactional
public Response storePolicy(@QueryParam("alsoStore") boolean alsoStore, @NotNull @Valid Policy policy) {
    if (!user.canReadPolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_VERIFY_POLICY)).build();
    }
    // We use the indirection, so that for testing we can produce known UUIDs
    policy.id = uuidHelper.getUUID();
    policy.customerid = user.getAccount();
    Response invalidNameResponse = isNameUnique(policy);
    if (invalidNameResponse != null) {
        return invalidNameResponse;
    }
    try {
        FullTrigger trigger = new FullTrigger(policy, true);
        engine.storeTrigger(trigger, true, user.getAccount());
    } catch (Exception e) {
        return Response.status(400, e.getMessage()).entity(getEngineExceptionMsg(e)).build();
    }
    if (!alsoStore) {
        return Response.status(200).entity(new Msg("Policy validated")).build();
    }
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg("Missing permissions to store policy")).build();
    }
    // Basic validation was successful, so try to persist.
    // This may still fail du to unique name violation, so
    // we need to check for that.
    UUID id;
    try {
        FullTrigger trigger = new FullTrigger(policy);
        try {
            engine.storeTrigger(trigger, false, user.getAccount());
            id = policy.store(user.getAccount(), policy);
        } catch (Exception e) {
            Msg engineExceptionMsg = getEngineExceptionMsg(e);
            log.warning("Storing policy in engine failed: " + engineExceptionMsg.msg);
            return Response.status(400, e.getMessage()).entity(engineExceptionMsg).build();
        }
    } catch (Throwable t) {
        return getResponseSavingPolicyThrowable(t);
    }
    // Policy is persisted. Return its location.
    URI location = UriBuilder.fromResource(PolicyCrudService.class).path(PolicyCrudService.class, "getPolicy").build(id);
    ResponseBuilder builder = Response.created(location).entity(policy);
    return builder.build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) FullTrigger(com.redhat.cloud.policies.app.model.engine.FullTrigger) UUID(java.util.UUID) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URI(java.net.URI) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) NotFoundException(javax.ws.rs.NotFoundException) PersistenceException(javax.persistence.PersistenceException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectException(java.net.ConnectException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SystemException(javax.transaction.SystemException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Operation(org.eclipse.microprofile.openapi.annotations.Operation) Transactional(javax.transaction.Transactional)

Example 13 with APIResponses

use of org.eclipse.microprofile.openapi.annotations.responses.APIResponses in project policies-ui-backend by RedHatInsights.

the class PolicyCrudService method validateName.

@Operation(summary = "Validates the Policy.name and verifies if it is unique.")
@POST
@Path("/validate-name")
@RequestBody(content = { @Content(schema = @Schema(type = SchemaType.STRING)) })
@APIResponses({ @APIResponse(responseCode = "200", description = "Name validated", content = @Content(schema = @Schema(implementation = Msg.class))), @APIResponse(responseCode = "400", description = "Policy validation failed", content = @Content(schema = @Schema(implementation = Msg.class))), @APIResponse(responseCode = "403", description = "Individual permissions missing to complete action", content = @Content(schema = @Schema(implementation = Msg.class))), @APIResponse(responseCode = "409", description = "Name not unique"), @APIResponse(responseCode = "500", description = "Internal error") })
@Parameter(name = "id", description = "UUID of the policy")
public Response validateName(@NotNull JsonString policyName, @QueryParam("id") UUID id) {
    if (!user.canReadPolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_VERIFY_POLICY)).build();
    }
    Policy policy = new Policy();
    policy.id = id;
    policy.name = policyName.getString();
    Set<ConstraintViolation<Policy>> result = validator.validateProperty(policy, "name");
    if (result.size() > 0) {
        String error = String.join(";", result.stream().map(ConstraintViolation::getMessage).collect(Collectors.toSet()));
        return Response.status(400).entity(new Msg(error)).build();
    }
    Response isNameValid = isNameUnique(policy);
    if (isNameValid != null) {
        return isNameValid;
    }
    return Response.status(200).entity(new Msg("Policy.name validated")).build();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) ConstraintViolation(javax.validation.ConstraintViolation) JsonString(javax.json.JsonString) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Operation(org.eclipse.microprofile.openapi.annotations.Operation) RequestBody(org.eclipse.microprofile.openapi.annotations.parameters.RequestBody)

Example 14 with APIResponses

use of org.eclipse.microprofile.openapi.annotations.responses.APIResponses in project trellis by trellis-ldp.

the class TrellisHttpResource method updateResource.

/**
 * Perform a PATCH operation on an LDP Resource.
 *
 * @param body the body
 * @return the async response
 */
@PATCH
@Timed
@Operation(summary = "Create or update a linked data resource")
@APIResponses(value = { @APIResponse(responseCode = "201", description = "The linked data resource was successfully created", content = {}), @APIResponse(responseCode = "204", description = "The linked data resource was successfully updated", content = {}) })
public CompletionStage<Response> updateResource(@RequestBody(description = "The update request for RDF resources, typically as SPARQL-Update", required = true, content = @Content(mediaType = "application/sparql-update")) final String body) {
    final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
    final String urlBase = getBaseUrl(req);
    final IRI identifier = services.getResourceService().getResourceIdentifier(urlBase, req.getPath());
    final PatchHandler patchHandler = new PatchHandler(req, body, services, extensions, supportsCreateOnPatch, defaultJsonLdProfile, urlBase);
    return getParent(identifier).thenCombine(services.getResourceService().get(identifier), patchHandler::initialize).thenCompose(patchHandler::updateResource).thenCompose(patchHandler::updateMemento).thenApply(ResponseBuilder::build).exceptionally(this::handleException);
}
Also used : IRI(org.apache.commons.rdf.api.IRI) TrellisRequest(org.trellisldp.common.TrellisRequest) PatchHandler(org.trellisldp.http.impl.PatchHandler) Timed(org.eclipse.microprofile.metrics.annotation.Timed) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Operation(org.eclipse.microprofile.openapi.annotations.Operation) PATCH(javax.ws.rs.PATCH)

Example 15 with APIResponses

use of org.eclipse.microprofile.openapi.annotations.responses.APIResponses in project smallrye-open-api by smallrye.

the class FilteredIndexViewTest method testGetAnnotationsWithRepeatable.

@Test
void testGetAnnotationsWithRepeatable() {
    class Target {

        @APIResponses({ @APIResponse(), @APIResponse() })
        void test1(@Parameter() String value1, @Parameter() String value2) {
        }

        @APIResponse
        void test2(@Parameter() String value1, @Parameter() String value2) {
        }
    }
    IndexView index = AugmentedIndexView.augment(IndexScannerTestBase.indexOf(APIResponse.class, APIResponses.class, Parameter.class, Target.class));
    OpenApiConfig config = IndexScannerTestBase.emptyConfig();
    FilteredIndexView view = new FilteredIndexView(index, config);
    Collection<AnnotationInstance> container = view.getAnnotationsWithRepeatable(DotName.createSimple(APIResponses.class.getName()), index);
    assertEquals(1, container.size());
    Collection<AnnotationInstance> responses = view.getAnnotationsWithRepeatable(DotName.createSimple(APIResponse.class.getName()), index);
    assertEquals(3, responses.size());
    Collection<AnnotationInstance> params = view.getAnnotationsWithRepeatable(DotName.createSimple(Parameter.class.getName()), index);
    assertEquals(4, params.size());
}
Also used : APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) OpenApiConfig(io.smallrye.openapi.api.OpenApiConfig) IndexView(org.jboss.jandex.IndexView) AugmentedIndexView(io.smallrye.openapi.runtime.scanner.dataobject.AugmentedIndexView) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) AnnotationInstance(org.jboss.jandex.AnnotationInstance) Test(org.junit.jupiter.api.Test)

Aggregations

APIResponses (org.eclipse.microprofile.openapi.annotations.responses.APIResponses)28 Operation (org.eclipse.microprofile.openapi.annotations.Operation)27 Path (javax.ws.rs.Path)25 Produces (javax.ws.rs.Produces)22 GET (javax.ws.rs.GET)15 ProcessInstanceNotFoundException (io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException)8 POST (javax.ws.rs.POST)8 ProcessInstance (io.automatiko.engine.api.workflow.ProcessInstance)7 APIResponse (org.eclipse.microprofile.openapi.annotations.responses.APIResponse)7 AbstractProcessInstance (io.automatiko.engine.workflow.AbstractProcessInstance)6 Optional (java.util.Optional)6 DELETE (javax.ws.rs.DELETE)6 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)6 LogWith (dk.dbc.log.LogWith)5 JsonExportedProcessInstance (io.automatiko.engine.addons.process.management.model.JsonExportedProcessInstance)5 ArchivedProcessInstance (io.automatiko.engine.api.workflow.ArchivedProcessInstance)5 ProcessImageNotFoundException (io.automatiko.engine.api.workflow.ProcessImageNotFoundException)5 URI (java.net.URI)5 Consumes (javax.ws.rs.Consumes)5 WebApplicationException (javax.ws.rs.WebApplicationException)5