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();
});
}
}
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);
}
}
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();
}
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();
}
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();
}
}
Aggregations