Search in sources :

Example 1 with Parameter

use of org.eclipse.microprofile.openapi.annotations.parameters.Parameter in project automatiko-engine by automatiko-io.

the class $Type$Resource method create_$name$.

@APIResponses(value = { @APIResponse(responseCode = "400", description = "In case request given does not meet expectations", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "500", description = "In case of processing errors", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "409", description = "In case an instance already exists with given business key", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "403", description = "In case an instance cannot be created due to access policy by the caller", content = @Content(mediaType = "application/json")), @APIResponse(responseCode = "200", description = "Successfully created instance", content = @Content(mediaType = "application/json", schema = @Schema(implementation = $Type$Output.class))), @APIResponse(responseCode = "202", description = "Successfully accepted request to create instance (applies only to async execution mode)", content = @Content(mediaType = "application/json", schema = @Schema(implementation = $Type$Output.class))) })
@Operation(summary = "Creates new instance of $name$")
@POST()
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response create_$name$(@Context HttpHeaders httpHeaders, @QueryParam("businessKey") @Parameter(description = "Alternative id to be assigned to the instance", required = false) String businessKey, @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, @Parameter(description = "Indicates if instance metadata should be included", required = false) @QueryParam("metadata") @DefaultValue("false") final boolean metadata, @Parameter(description = "The input model for $name$ instance") $Type$Input resource) {
    if (resource == null) {
        resource = new $Type$Input();
    }
    final $Type$Input value = resource;
    String execMode = httpHeaders.getHeaderString("X-ATK-Mode");
    if ("async".equalsIgnoreCase(execMode)) {
        String callbackUrl = httpHeaders.getHeaderString("X-ATK-Callback");
        String startFromNode = httpHeaders.getHeaderString("X-ATK-StartFromNode");
        ProcessInstance<$Type$> pi = process.createInstance(businessKey, mapInput(value, new $Type$()));
        ((AbstractProcessInstance<$Type$>) pi).unlock(true);
        $Type$Output output = mapOutput(new $Type$Output(), pi.variables(), businessKey, pi.metadata());
        Map<String, String> headers = httpHeaders.getRequestHeaders().entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().get(0)));
        IdentityProvider identity = identitySupplier.buildIdentityProvider(user, groups);
        IdentityProvider.set(null);
        CompletableFuture.runAsync(() -> {
            IdentityProvider.set(identity);
            io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
                if (startFromNode != null) {
                    pi.startFrom(startFromNode);
                } else {
                    pi.start();
                }
                tracing(pi);
                $Type$Output result = getModel(pi, metadata);
                io.automatiko.engine.workflow.http.HttpCallbacks.get().post(callbackUrl, result, httpAuth.produce(headers), pi.status());
                return null;
            });
        });
        ResponseBuilder builder = Response.accepted().entity(output);
        return builder.build();
    } else {
        identitySupplier.buildIdentityProvider(user, groups);
        return io.automatiko.engine.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
            ProcessInstance<$Type$> pi = process.createInstance(businessKey, mapInput(value, new $Type$()));
            String startFromNode = httpHeaders.getHeaderString("X-ATK-StartFromNode");
            if (startFromNode != null) {
                pi.startFrom(startFromNode);
            } else {
                pi.start();
            }
            tracing(pi);
            ResponseBuilder builder = Response.ok().entity(getModel(pi, metadata));
            return builder.build();
        });
    }
}
Also used : Produces(javax.ws.rs.Produces) SecurityPolicy(io.automatiko.engine.api.auth.SecurityPolicy) Path(javax.ws.rs.Path) WorkItemNotFoundException(io.automatiko.engine.api.runtime.process.WorkItemNotFoundException) TagInstance(io.automatiko.engine.workflow.base.instance.TagInstance) ProcessInstanceExecutionException(io.automatiko.engine.api.workflow.ProcessInstanceExecutionException) MediaType(javax.ws.rs.core.MediaType) Application(io.automatiko.engine.api.Application) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ProcessImageNotFoundException(io.automatiko.engine.api.workflow.ProcessImageNotFoundException) SchemaType(org.eclipse.microprofile.openapi.annotations.enums.SchemaType) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Collection(java.util.Collection) Tag(io.automatiko.engine.api.workflow.Tag) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) StreamingOutput(javax.ws.rs.core.StreamingOutput) Operation(org.eclipse.microprofile.openapi.annotations.Operation) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) Policy(io.automatiko.engine.api.workflow.workitem.Policy) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Sig(io.automatiko.engine.workflow.Sig) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Entry(java.util.Map.Entry) WebApplicationException(javax.ws.rs.WebApplicationException) UriInfo(javax.ws.rs.core.UriInfo) ProcessInstanceNotFoundException(io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException) WorkItem(io.automatiko.engine.api.workflow.WorkItem) PathParam(javax.ws.rs.PathParam) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) GET(javax.ws.rs.GET) CompletableFuture(java.util.concurrent.CompletableFuture) IdentitySupplier(io.automatiko.engine.api.auth.IdentitySupplier) InstanceMetadata(io.automatiko.engine.api.workflow.InstanceMetadata) Process(io.automatiko.engine.api.workflow.Process) Content(org.eclipse.microprofile.openapi.annotations.media.Content) Status(javax.ws.rs.core.Response.Status) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) OutputStream(java.io.OutputStream) POST(javax.ws.rs.POST) Schema(org.eclipse.microprofile.openapi.annotations.media.Schema) IOException(java.io.IOException) HttpAuthSupport(io.automatiko.engine.service.auth.HttpAuthSupport) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Collections(java.util.Collections) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 2 with Parameter

use of org.eclipse.microprofile.openapi.annotations.parameters.Parameter in project automatiko-engine by automatiko-io.

the class ProcessInstanceManagementResource method getInstance.

@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 = "Process instance details", content = @Content(mediaType = "application/json")) })
@Operation(summary = "Returns process instance details for given instance id")
@SuppressWarnings("unchecked")
@GET
@Path("/{processId}/instances/{instanceId}")
@Produces(MediaType.APPLICATION_JSON)
public ProcessInstanceDetailsDTO getInstance(@Context UriInfo uriInfo, @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);
            Optional<ProcessInstance<?>> instance = (Optional<ProcessInstance<?>>) process.instances().findById(instanceId, mapStatus(status), ProcessInstanceReadMode.READ_ONLY);
            if (instance.isEmpty()) {
                throw new ProcessInstanceNotFoundException(instanceId);
            }
            ProcessInstance<?> pi = instance.get();
            ProcessInstanceDetailsDTO details = new ProcessInstanceDetailsDTO();
            String id = pi.id();
            if (pi.parentProcessInstanceId() != null) {
                id = pi.parentProcessInstanceId() + ":" + id;
            }
            details.setId(id);
            details.setProcessId(processId);
            details.setBusinessKey(pi.businessKey() == null ? "" : pi.businessKey());
            details.setDescription(pi.description());
            details.setState(pi.status());
            details.setFailed(pi.errors().isPresent());
            if (pi.errors().isPresent()) {
                details.setErrors(pi.errors().get().errors().stream().map(e -> new ErrorInfoDTO(e.failedNodeId(), e.errorId(), e.errorMessage(), e.errorDetails())).collect(Collectors.toList()));
            }
            details.setImage(uriInfo.getBaseUri().toString() + "management/processes/" + processId + "/instances/" + instanceId + "/image?status=" + reverseMapStatus(pi.status()));
            details.setTags(pi.tags().values());
            details.setVariables(pi.variables());
            details.setSubprocesses(pi.subprocesses().stream().map(spi -> new ProcessInstanceDTO(spi.id(), spi.businessKey(), spi.description(), spi.tags().values(), spi.errors().isPresent(), spi.process().id(), spi.status())).collect(Collectors.toList()));
            VariableScope variableScope = (VariableScope) ((ContextContainer) ((AbstractProcess<?>) process).process()).getDefaultContext(VariableScope.VARIABLE_SCOPE);
            details.setVersionedVariables(variableScope.getVariables().stream().filter(v -> v.hasTag(Variable.VERSIONED_TAG)).map(v -> v.getName()).collect(Collectors.toList()));
            return details;
        });
    } finally {
        IdentityProvider.set(null);
    }
}
Also used : Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) ProcessInstanceExporter(io.automatiko.engine.addons.process.management.export.ProcessInstanceExporter) MediaType(javax.ws.rs.core.MediaType) Application(io.automatiko.engine.api.Application) QueryParam(javax.ws.rs.QueryParam) ProcessImageNotFoundException(io.automatiko.engine.api.workflow.ProcessImageNotFoundException) ContextContainer(io.automatiko.engine.workflow.base.core.ContextContainer) SchemaType(org.eclipse.microprofile.openapi.annotations.enums.SchemaType) VariableNotFoundException(io.automatiko.engine.api.workflow.VariableNotFoundException) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Instance(javax.enterprise.inject.Instance) DELETE(javax.ws.rs.DELETE) JsonExportedProcessInstance(io.automatiko.engine.addons.process.management.model.JsonExportedProcessInstance) IoUtils(io.automatiko.engine.services.utils.IoUtils) Context(javax.ws.rs.core.Context) Model(io.automatiko.engine.api.Model) IdentityProvider(io.automatiko.engine.api.auth.IdentityProvider) Operation(org.eclipse.microprofile.openapi.annotations.Operation) ProcessInstance(io.automatiko.engine.api.workflow.ProcessInstance) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) ProcessInstanceDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDTO) ProcessInstanceReadMode(io.automatiko.engine.api.workflow.ProcessInstanceReadMode) Optional(java.util.Optional) Tag(org.eclipse.microprofile.openapi.annotations.tags.Tag) Variable(io.automatiko.engine.workflow.base.core.context.variable.Variable) UriInfo(javax.ws.rs.core.UriInfo) ProcessInstanceNotFoundException(io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException) PathParam(javax.ws.rs.PathParam) AbstractProcessInstance(io.automatiko.engine.workflow.AbstractProcessInstance) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GET(javax.ws.rs.GET) ProcessInstanceDetailsDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDetailsDTO) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ArchivedProcessInstance(io.automatiko.engine.api.workflow.ArchivedProcessInstance) JsonArchiveBuilder(io.automatiko.engine.workflow.json.JsonArchiveBuilder) IdentitySupplier(io.automatiko.engine.api.auth.IdentitySupplier) ErrorInfoDTO(io.automatiko.engine.addons.process.management.model.ErrorInfoDTO) WorkflowProcess(io.automatiko.engine.workflow.process.core.WorkflowProcess) Process(io.automatiko.engine.api.workflow.Process) ProcessDTO(io.automatiko.engine.addons.process.management.model.ProcessDTO) Content(org.eclipse.microprofile.openapi.annotations.media.Content) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) Status(javax.ws.rs.core.Response.Status) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) UnitOfWorkExecutor(io.automatiko.engine.services.uow.UnitOfWorkExecutor) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Schema(org.eclipse.microprofile.openapi.annotations.media.Schema) IOException(java.io.IOException) ExternalDocumentation(org.eclipse.microprofile.openapi.annotations.ExternalDocumentation) APIResponses(org.eclipse.microprofile.openapi.annotations.responses.APIResponses) Collections(java.util.Collections) ProcessInstanceDetailsDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDetailsDTO) Optional(java.util.Optional) ErrorInfoDTO(io.automatiko.engine.addons.process.management.model.ErrorInfoDTO) AbstractProcess(io.automatiko.engine.workflow.AbstractProcess) ProcessInstanceDTO(io.automatiko.engine.addons.process.management.model.ProcessInstanceDTO) ProcessInstanceNotFoundException(io.automatiko.engine.api.workflow.ProcessInstanceNotFoundException) 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) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope) 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 3 with Parameter

use of org.eclipse.microprofile.openapi.annotations.parameters.Parameter 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 4 with Parameter

use of org.eclipse.microprofile.openapi.annotations.parameters.Parameter 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 5 with Parameter

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

the class PolicyCrudService method setEnabledStateForPolicies.

@Operation(summary = "Enable/disable policies identified by list of uuid in body")
@Parameter(name = "uuids", schema = @Schema(type = SchemaType.ARRAY, implementation = UUID.class))
@APIResponse(responseCode = "200", description = "Policy updated", content = @Content(schema = @Schema(type = SchemaType.ARRAY, implementation = UUID.class)))
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@POST
@Path("/ids/enabled")
@Transactional
public Response setEnabledStateForPolicies(@QueryParam("enabled") boolean shouldBeEnabled, @NotEmpty List<UUID> uuids) {
    if (!user.canWritePolicies()) {
        return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_UPDATE_POLICY)).build();
    }
    List<UUID> changed = new ArrayList<>(uuids.size());
    try {
        for (UUID uuid : uuids) {
            Policy storedPolicy = Policy.findById(user.getAccount(), uuid);
            boolean wasChanged = false;
            if (storedPolicy != null) {
                try {
                    if (shouldBeEnabled) {
                        engine.enableTrigger(storedPolicy.id, user.getAccount());
                    } else {
                        engine.disableTrigger(storedPolicy.id, user.getAccount());
                    }
                    wasChanged = true;
                } catch (Exception e) {
                    log.warning("Changing state in engine failed: " + e.getMessage());
                }
                if (wasChanged) {
                    storedPolicy.isEnabled = shouldBeEnabled;
                    storedPolicy.setMtimeToNow();
                    storedPolicy.persist();
                    changed.add(uuid);
                }
            }
        }
        return Response.ok(changed).build();
    } catch (Throwable e) {
        log.severe("Enabling failed: " + e.getMessage());
        return Response.serverError().build();
    }
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) ArrayList(java.util.ArrayList) UUID(java.util.UUID) 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) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) POST(javax.ws.rs.POST) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Operation(org.eclipse.microprofile.openapi.annotations.Operation) Transactional(javax.transaction.Transactional)

Aggregations

Parameter (org.eclipse.microprofile.openapi.annotations.parameters.Parameter)10 APIResponse (org.eclipse.microprofile.openapi.annotations.responses.APIResponse)10 Path (javax.ws.rs.Path)9 Operation (org.eclipse.microprofile.openapi.annotations.Operation)9 POST (javax.ws.rs.POST)7 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)7 Msg (com.redhat.cloud.policies.app.model.Msg)6 Policy (com.redhat.cloud.policies.app.model.Policy)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 APIResponses (org.eclipse.microprofile.openapi.annotations.responses.APIResponses)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 ConnectException (java.net.ConnectException)4 PersistenceException (javax.persistence.PersistenceException)4 SystemException (javax.transaction.SystemException)4 Transactional (javax.transaction.Transactional)4 DELETE (javax.ws.rs.DELETE)4 NotFoundException (javax.ws.rs.NotFoundException)4 ProcessingException (javax.ws.rs.ProcessingException)4 Application (io.automatiko.engine.api.Application)3 IdentityProvider (io.automatiko.engine.api.auth.IdentityProvider)3