use of com.redhat.cloud.policies.app.model.Msg in project policies-ui-backend by RedHatInsights.
the class CustomExceptionMapper method toResponse.
@Override
public Response toResponse(RuntimeException exception) {
Response.ResponseBuilder builder;
if (exception instanceof NotFoundException) {
builder = Response.status(Response.Status.NOT_FOUND);
} else if (exception instanceof JsonParsingException) {
builder = Response.status(Response.Status.BAD_REQUEST);
} else if (exception.getMessage().contains("RESTEASY003340") || exception.getMessage().contains("RESTEASY008200")) {
builder = Response.status(Response.Status.BAD_REQUEST);
} else {
builder = Response.serverError();
// we only print the stack on something we don't know yet
exception.printStackTrace();
}
builder.type(MediaType.APPLICATION_JSON_TYPE).entity(new Msg("Something went wrong, please check your request"));
Response resp = builder.build();
return resp;
}
use of com.redhat.cloud.policies.app.model.Msg in project policies-ui-backend by RedHatInsights.
the class AdminService method setAdminDown.
/**
* Signal health to outside world. Allowed values for state
* * 'ok': all ok
* * 'degraded': signal instance as degraded on status endpoint
* * 'admin-down': signal health-checks as down. Signals k8s to kill the pod
*/
@Path("/status")
@POST
public Response setAdminDown(@QueryParam("status") Optional<String> status) {
Response.ResponseBuilder builder;
StuffHolder th = StuffHolder.getInstance();
switch(status.orElse("ok")) {
case "ok":
th.setDegraded(false);
th.setAdminDown(false);
builder = Response.ok().entity(new Msg("Reset state to ok"));
break;
case "degraded":
th.setDegraded(true);
builder = Response.ok().entity(new Msg("Set degraded state"));
break;
case "admin-down":
th.setAdminDown(true);
builder = Response.ok().entity(new Msg("Set admin down state"));
break;
default:
builder = Response.status(Response.Status.BAD_REQUEST).entity(new Msg("Unknown status passed"));
}
statusProducer.update();
return builder.build();
}
use of com.redhat.cloud.policies.app.model.Msg 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 com.redhat.cloud.policies.app.model.Msg 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 com.redhat.cloud.policies.app.model.Msg in project policies-ui-backend by RedHatInsights.
the class PolicyCrudService method getPoliciesForCustomer.
@Operation(summary = "Return all policies for a given account")
@GET
@Path("/")
@Parameters({ @Parameter(name = "offset", in = ParameterIn.QUERY, description = "Page number, starts 0, if not specified uses 0.", schema = @Schema(type = SchemaType.INTEGER)), @Parameter(name = "limit", in = ParameterIn.QUERY, description = "Number of items per page, if not specified uses 50. " + Pager.NO_LIMIT + " can be used to specify an unlimited page, when specified it ignores the offset", schema = @Schema(type = SchemaType.INTEGER)), @Parameter(name = "sortColumn", in = ParameterIn.QUERY, description = "Column to sort the results by", schema = @Schema(type = SchemaType.STRING, enumeration = { "name", "description", "is_enabled", "mtime" })), @Parameter(name = "sortDirection", in = ParameterIn.QUERY, description = "Sort direction used", schema = @Schema(type = SchemaType.STRING, enumeration = { "asc", "desc" })), @Parameter(name = "filter[name]", in = ParameterIn.QUERY, description = "Filtering policies by the name depending on the Filter operator used.", schema = @Schema(type = SchemaType.STRING)), @Parameter(name = "filter:op[name]", in = ParameterIn.QUERY, description = "Operations used with the filter", schema = @Schema(type = SchemaType.STRING, enumeration = { "equal", "like", "ilike", "not_equal" }, defaultValue = "equal")), @Parameter(name = "filter[description]", in = ParameterIn.QUERY, description = "Filtering policies by the description depending on the Filter operator used.", schema = @Schema(type = SchemaType.STRING)), @Parameter(name = "filter:op[description]", in = ParameterIn.QUERY, description = "Operations used with the filter", schema = @Schema(type = SchemaType.STRING, enumeration = { "equal", "like", "ilike", "not_equal" }, defaultValue = "equal")), @Parameter(name = "filter[is_enabled]", in = ParameterIn.QUERY, description = "Filtering policies by the is_enabled field." + "Defaults to true if no operand is given.", schema = @Schema(type = SchemaType.STRING, defaultValue = "true", enumeration = { "true", "false" })) })
@APIResponse(responseCode = "400", description = "Bad parameter for sorting was passed")
@APIResponse(responseCode = "404", description = "No policies found for customer")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action")
@APIResponse(responseCode = "200", description = "Policies found", content = @Content(schema = @Schema(implementation = PagedResponseOfPolicy.class)), headers = @Header(name = "TotalCount", description = "Total number of items found", schema = @Schema(type = SchemaType.INTEGER)))
public Response getPoliciesForCustomer() {
if (!user.canReadPolicies()) {
return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_RETRIEVE_POLICIES)).build();
}
Page<Policy> page;
try {
Pager pager = PagingUtils.extractPager(uriInfo);
page = Policy.pagePoliciesForCustomer(entityManager, user.getAccount(), pager);
for (Policy policy : page) {
Long lastTriggerTime = policiesHistoryRepository.getLastTriggerTime(user.getAccount(), policy.id);
if (lastTriggerTime != null) {
policy.setLastTriggered(lastTriggerTime);
}
}
} catch (IllegalArgumentException iae) {
return Response.status(400, iae.getLocalizedMessage()).build();
}
return PagingUtils.responseBuilder(page).build();
}
Aggregations