use of com.redhat.cloud.policies.app.model.Policy 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.Policy 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();
}
use of com.redhat.cloud.policies.app.model.Policy 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();
}
}
use of com.redhat.cloud.policies.app.model.Policy in project policies-ui-backend by RedHatInsights.
the class PolicyCrudService method getPolicy.
@Operation(summary = "Retrieve a single policy for a customer by its id")
@GET
@Path("/{id}")
@APIResponse(responseCode = "200", description = "Policy found", content = @Content(schema = @Schema(implementation = Policy.class)))
@APIResponse(responseCode = "404", description = "Policy not found")
@APIResponse(responseCode = "403", description = "Individual permissions missing to complete action", content = @Content(schema = @Schema(implementation = Msg.class)))
@Parameter(name = "id", description = "UUID of the policy")
public Response getPolicy(@PathParam("id") UUID policyId) {
if (!user.canReadPolicies()) {
return Response.status(Response.Status.FORBIDDEN).entity(new Msg(MISSING_PERMISSIONS_TO_RETRIEVE_POLICIES)).build();
}
Policy policy = Policy.findById(user.getAccount(), policyId);
ResponseBuilder builder;
if (policy == null) {
builder = Response.status(Response.Status.NOT_FOUND);
} else {
Long lastTriggerTime = policiesHistoryRepository.getLastTriggerTime(user.getAccount(), policy.id);
if (lastTriggerTime != null) {
policy.setLastTriggered(lastTriggerTime);
}
builder = Response.ok(policy);
EntityTag etag = new EntityTag(String.valueOf(policy.hashCode()));
builder.header("ETag", etag);
}
return builder.build();
}
use of com.redhat.cloud.policies.app.model.Policy in project policies-ui-backend by RedHatInsights.
the class PolicyCrudServiceTest method createPolicy.
private UUID createPolicy() {
Policy policy = new Policy();
policy.name = "my-policy";
policy.conditions = "arch = \"x86_64\"";
String responseBody = given().basePath(API_BASE_V1_0).header(authHeader).contentType(JSON).body(Json.encode(policy)).queryParam("alsoStore", true).when().post("/policies").then().statusCode(201).extract().asString();
JsonObject jsonPolicy = new JsonObject(responseBody);
return UUID.fromString(jsonPolicy.getString("id"));
}
Aggregations