Search in sources :

Example 1 with Policy

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();
}
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 2 with Policy

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();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) Pager(com.redhat.cloud.policies.app.model.pager.Pager) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Parameters(org.eclipse.microprofile.openapi.annotations.parameters.Parameters) GET(javax.ws.rs.GET) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 3 with Policy

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

Example 4 with Policy

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();
}
Also used : Msg(com.redhat.cloud.policies.app.model.Msg) Policy(com.redhat.cloud.policies.app.model.Policy) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) GET(javax.ws.rs.GET) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Example 5 with Policy

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"));
}
Also used : Policy(com.redhat.cloud.policies.app.model.Policy) JsonObject(io.vertx.core.json.JsonObject)

Aggregations

Policy (com.redhat.cloud.policies.app.model.Policy)21 Msg (com.redhat.cloud.policies.app.model.Msg)11 FullTrigger (com.redhat.cloud.policies.app.model.engine.FullTrigger)11 Path (javax.ws.rs.Path)11 Operation (org.eclipse.microprofile.openapi.annotations.Operation)9 APIResponse (org.eclipse.microprofile.openapi.annotations.responses.APIResponse)9 NotFoundException (javax.ws.rs.NotFoundException)8 Test (org.junit.jupiter.api.Test)8 Transactional (javax.transaction.Transactional)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 ConnectException (java.net.ConnectException)6 PersistenceException (javax.persistence.PersistenceException)6 SystemException (javax.transaction.SystemException)6 ProcessingException (javax.ws.rs.ProcessingException)6 WebApplicationException (javax.ws.rs.WebApplicationException)6 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)6 POST (javax.ws.rs.POST)5 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)5 Parameter (org.eclipse.microprofile.openapi.annotations.parameters.Parameter)5 GET (javax.ws.rs.GET)4