Search in sources :

Example 86 with BadRequestException

use of javax.ws.rs.BadRequestException in project keywhiz by square.

the class ClientResource method doCreateClient.

private Response doCreateClient(AutomationClient automationClient, CreateClientRequestV2 request) {
    String creator = automationClient.getName();
    String client = request.name();
    setTag("client", client);
    clientDAOReadWrite.getClientByName(client).ifPresent((c) -> {
        logger.info("Automation ({}) - Client {} already exists", creator, client);
        throw new ConflictException("Client name already exists.");
    });
    // Creates new client record
    long clientId;
    try {
        clientId = clientDAOReadWrite.createClient(client, creator, request.description(), new URI(request.spiffeId()));
    } catch (URISyntaxException e) {
        logger.info(format("Automation (%s) - Client %s could not be created because of invalid SPIFFE ID %s", creator, client, request.spiffeId()), e);
        throw new BadRequestException("Invalid SPIFFE ID provided (not a URI)");
    }
    auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_CREATE, creator, client));
    // Enrolls client in any requested groups
    groupsToGroupIds(request.groups()).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEnrollClient(clientId, groupId, auditLog, creator, new HashMap<>())));
    URI uri = UriBuilder.fromResource(ClientResource.class).path(client).build();
    return Response.created(uri).build();
}
Also used : Produces(javax.ws.rs.Produces) Event(keywhiz.log.Event) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) Valid(javax.validation.Valid) ClientDAOFactory(keywhiz.service.daos.ClientDAO.ClientDAOFactory) Consumes(javax.ws.rs.Consumes) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) Tracing.setTag(keywhiz.Tracing.setTag) Group(keywhiz.api.model.Group) Tracing.tagErrors(keywhiz.Tracing.tagErrors) Set(java.util.Set) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) NotImplementedException(org.apache.commons.lang3.NotImplementedException) PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) ClientDAO(keywhiz.service.daos.ClientDAO) GET(javax.ws.rs.GET) ClientDetailResponseV2(keywhiz.api.automation.v2.ClientDetailResponseV2) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) Inject(javax.inject.Inject) AutomationClient(keywhiz.api.model.AutomationClient) CreateClientRequestV2(keywhiz.api.automation.v2.CreateClientRequestV2) AuditLog(keywhiz.log.AuditLog) ModifyClientRequestV2(keywhiz.api.automation.v2.ModifyClientRequestV2) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) EventTag(keywhiz.log.EventTag) PUT(javax.ws.rs.PUT) ConflictException(keywhiz.service.exceptions.ConflictException) BadRequestException(javax.ws.rs.BadRequestException) Event(keywhiz.log.Event) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 87 with BadRequestException

use of javax.ws.rs.BadRequestException in project keywhiz by square.

the class SecretDAO method createSecret.

@VisibleForTesting
public long createSecret(String name, String ownerName, String encryptedSecret, String hmac, String creator, Map<String, String> metadata, long expiry, String description, @Nullable String type, @Nullable Map<String, String> generationOptions) {
    return dslContext.transactionResult(configuration -> {
        // check is here because this is where all APIs converge on secret creation
        if (name.startsWith(".")) {
            throw new BadRequestException(format("secret cannot be created with name `%s` - secret " + "names cannot begin with a period", name));
        }
        // enforce a shorter max length than the db to ensure secrets renamed on deletion still fit
        if (name.length() > SECRET_NAME_MAX_LENGTH) {
            throw new BadRequestException(format("secret cannot be created with name `%s` - secret " + "names must be %d characters or less", name, SECRET_NAME_MAX_LENGTH));
        }
        long now = OffsetDateTime.now().toEpochSecond();
        SecretContentDAO secretContentDAO = secretContentDAOFactory.using(configuration);
        SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(configuration);
        Long ownerId = getOwnerId(configuration, ownerName);
        Optional<SecretSeries> secretSeries = secretSeriesDAO.getSecretSeriesByName(name);
        long secretId;
        if (secretSeries.isPresent()) {
            SecretSeries secretSeries1 = secretSeries.get();
            if (secretSeries1.currentVersion().isPresent()) {
                throw new DataAccessException(format("secret already present: %s", name));
            } else {
                // Unreachable unless the implementation of getSecretSeriesByName is changed
                throw new IllegalStateException(format("secret %s retrieved without current version set", name));
            }
        } else {
            secretId = secretSeriesDAO.createSecretSeries(name, ownerId, creator, description, type, generationOptions, now);
        }
        long secretContentId = secretContentDAO.createSecretContent(secretId, encryptedSecret, hmac, creator, metadata, expiry, now);
        secretSeriesDAO.setCurrentVersion(secretId, secretContentId, creator, now);
        return secretId;
    });
}
Also used : SecretSeries(keywhiz.api.model.SecretSeries) BadRequestException(javax.ws.rs.BadRequestException) DataAccessException(org.jooq.exception.DataAccessException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 88 with BadRequestException

use of javax.ws.rs.BadRequestException in project syndesis-qe by syndesisio.

the class StepDescriptorEndpoint method getStepDescriptor.

public StepDescriptor getStepDescriptor(String stepKind, DataShape in, DataShape out) {
    super.setEndpointName("/steps/" + stepKind + "/descriptor");
    log.debug("POST, destination : {}", getEndpointUrl());
    final Invocation.Builder invocation = createInvocation(null);
    DynamicActionMetadata metadata = new DynamicActionMetadata.Builder().inputShape(in).outputShape(out).build();
    JsonNode response;
    try {
        response = invocation.post(Entity.entity(metadata, MediaType.APPLICATION_JSON), JsonNode.class);
    } catch (BadRequestException ex) {
        log.error("Bad request, trying again in 15 seconds");
        try {
            Thread.sleep(15000L);
        } catch (InterruptedException ignore) {
        // ignore
        }
        response = invocation.post(Entity.entity(metadata, MediaType.APPLICATION_JSON), JsonNode.class);
    }
    return transformJsonNode(response, StepDescriptor.class);
}
Also used : Invocation(javax.ws.rs.client.Invocation) DynamicActionMetadata(io.syndesis.common.model.connection.DynamicActionMetadata) BadRequestException(javax.ws.rs.BadRequestException) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 89 with BadRequestException

use of javax.ws.rs.BadRequestException in project verify-hub by alphagov.

the class SoapRequestClientTest method makePost_checkSOAPRequestErrorIsThrownWhenNotValidXML.

@Test
public void makePost_checkSOAPRequestErrorIsThrownWhenNotValidXML() throws Exception {
    when(webResourceBuilder.post(any(Entity.class))).thenReturn(response);
    when(response.readEntity(Document.class)).thenThrow(new BadRequestException());
    when(response.getStatus()).thenReturn(200);
    Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>");
    URI matchingServiceUri = new URI("http://heyyeyaaeyaaaeyaeyaa.com/abc1");
    try {
        soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri);
        fail("Exception should have been thrown");
    } catch (SOAPRequestError ignored) {
    } finally {
        verify(response).readEntity(Document.class);
    }
}
Also used : Entity(javax.ws.rs.client.Entity) Element(org.w3c.dom.Element) BadRequestException(javax.ws.rs.BadRequestException) URI(java.net.URI) Test(org.junit.jupiter.api.Test)

Example 90 with BadRequestException

use of javax.ws.rs.BadRequestException in project cxf by apache.

the class ExceptionUtilsTest method testConvertFaultToResponseWAESubClassWithResponse.

@Test
public void testConvertFaultToResponseWAESubClassWithResponse() {
    Message m = createMessage();
    BadRequestException wae = new BadRequestException(Response.status(400).type(MediaType.TEXT_HTML).entity("<em>fromBRE</em>").build());
    Response r = ExceptionUtils.convertFaultToResponse(wae, m);
    assertEquals(400, r.getStatus());
    assertEquals(MediaType.TEXT_HTML_TYPE, r.getMediaType());
    assertEquals("<em>fromBRE</em>", r.readEntity(String.class));
}
Also used : Response(javax.ws.rs.core.Response) Message(org.apache.cxf.message.Message) BadRequestException(javax.ws.rs.BadRequestException) Test(org.junit.Test)

Aggregations

BadRequestException (javax.ws.rs.BadRequestException)238 Path (javax.ws.rs.Path)92 ApiOperation (io.swagger.annotations.ApiOperation)80 POST (javax.ws.rs.POST)65 Consumes (javax.ws.rs.Consumes)61 Produces (javax.ws.rs.Produces)55 AuditEvent (org.graylog2.audit.jersey.AuditEvent)52 NotFoundException (javax.ws.rs.NotFoundException)42 Timed (com.codahale.metrics.annotation.Timed)40 PUT (javax.ws.rs.PUT)40 ApiResponses (io.swagger.annotations.ApiResponses)38 Test (org.junit.Test)34 GET (javax.ws.rs.GET)32 IOException (java.io.IOException)30 Response (javax.ws.rs.core.Response)27 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)27 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)26 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)26 URI (java.net.URI)24 HashMap (java.util.HashMap)22