Search in sources :

Example 1 with Msg

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;
}
Also used : Response(javax.ws.rs.core.Response) Msg(com.redhat.cloud.policies.app.model.Msg) NotFoundException(javax.ws.rs.NotFoundException) JsonParsingException(javax.json.stream.JsonParsingException)

Example 2 with Msg

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();
}
Also used : Response(javax.ws.rs.core.Response) Msg(com.redhat.cloud.policies.app.model.Msg) StuffHolder(com.redhat.cloud.policies.app.StuffHolder) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 3 with Msg

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

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

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

Aggregations

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