Search in sources :

Example 31 with DataAccessException

use of org.jooq.exception.DataAccessException in project keywhiz by square.

the class ClientsResource method createClient.

/**
   * Create Client
   *
   * @excludeParams user
   * @param createClientRequest the JSON client request used to formulate the Client
   *
   * @description Creates a Client with the name from a valid client request.
   * Used by Keywhiz CLI and the web ui.
   * @responseMessage 200 Successfully created Client
   * @responseMessage 409 Client with given name already exists
   */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createClient(@Auth User user, @Valid CreateClientRequest createClientRequest) {
    logger.info("User '{}' creating client '{}'.", user, createClientRequest.name);
    long clientId;
    try {
        clientId = clientDAO.createClient(createClientRequest.name, user.getName(), "");
    } catch (DataAccessException e) {
        logger.warn("Cannot create client {}: {}", createClientRequest.name, e);
        throw new ConflictException("Conflict creating client.");
    }
    URI uri = UriBuilder.fromResource(ClientsResource.class).path("{clientId}").build(clientId);
    Response response = Response.created(uri).entity(clientDetailResponseFromId(clientId)).build();
    if (response.getStatus() == HttpStatus.SC_CREATED) {
        auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_CREATE, user.getName(), createClientRequest.name));
    }
    return response;
}
Also used : ClientDetailResponse(keywhiz.api.ClientDetailResponse) Response(javax.ws.rs.core.Response) ConflictException(keywhiz.service.exceptions.ConflictException) Event(keywhiz.log.Event) URI(java.net.URI) DataAccessException(org.jooq.exception.DataAccessException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 32 with DataAccessException

use of org.jooq.exception.DataAccessException in project keywhiz by square.

the class AutomationSecretResourceTest method triesToCreateDuplicateSecret.

@Test(expected = ConflictException.class)
public void triesToCreateDuplicateSecret() throws Exception {
    DataAccessException exception = new DataAccessException("");
    ImmutableMap<String, String> emptyMap = ImmutableMap.of();
    doThrow(exception).when(secretBuilder).create();
    CreateSecretRequest req = new CreateSecretRequest("name", "desc", "content", emptyMap, 0);
    resource.createSecret(automation, req);
}
Also used : CreateSecretRequest(keywhiz.api.CreateSecretRequest) Matchers.anyString(org.mockito.Matchers.anyString) DataAccessException(org.jooq.exception.DataAccessException) Test(org.junit.Test)

Example 33 with DataAccessException

use of org.jooq.exception.DataAccessException in project keywhiz by square.

the class SecretsResourceTest method triesToCreateDuplicateSecret.

@Test(expected = ConflictException.class)
public void triesToCreateDuplicateSecret() throws Exception {
    SecretController.SecretBuilder secretBuilder = mock(SecretController.SecretBuilder.class);
    when(secretController.builder("name", "content", user.getName(), 0)).thenReturn(secretBuilder);
    DataAccessException exception = new DataAccessException("");
    doThrow(exception).when(secretBuilder).create();
    CreateSecretRequest req = new CreateSecretRequest("name", "desc", "content", emptyMap, 0);
    resource.createSecret(user, req);
}
Also used : CreateSecretRequest(keywhiz.api.CreateSecretRequest) SecretController(keywhiz.service.daos.SecretController) DataAccessException(org.jooq.exception.DataAccessException) Test(org.junit.Test)

Example 34 with DataAccessException

use of org.jooq.exception.DataAccessException in project torodb by torodb.

the class PostgreSqlWriteInterface method insertDocPartData.

@Override
public void insertDocPartData(DSLContext dsl, String schemaName, DocPartData docPartData) throws UserException {
    metrics.insertRows.mark(docPartData.rowCount());
    metrics.insertFields.mark(docPartData.rowCount() * (docPartData.fieldColumnsCount() + docPartData.scalarColumnsCount()));
    if (docPartData.rowCount() == 0) {
        return;
    }
    try (Timer.Context ctx = metrics.insertDocPartDataTimer.time()) {
        int maxCappedSize = 10;
        int cappedSize = Math.min(docPartData.rowCount(), maxCappedSize);
        if (cappedSize < maxCappedSize) {
            //there are not enough elements on the insert => fallback
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("The insert window is not big enough to use copy (the limit is {}, the real " + "size is {}).", maxCappedSize, cappedSize);
            }
            metrics.insertDefault.mark();
            super.insertDocPartData(dsl, schemaName, docPartData);
        } else {
            Connection connection = dsl.configuration().connectionProvider().acquire();
            try {
                if (!connection.isWrapperFor(PGConnection.class)) {
                    LOGGER.warn("It was impossible to use the PostgreSQL way to " + "insert documents. Inserting using the standard " + "implementation");
                    metrics.insertDefault.mark();
                    super.insertDocPartData(dsl, schemaName, docPartData);
                } else {
                    try {
                        metrics.insertCopy.mark();
                        copyInsertDocPartData(connection.unwrap(PGConnection.class), schemaName, docPartData);
                    } catch (DataAccessException ex) {
                        throw errorHandler.handleUserException(Context.INSERT, ex);
                    } catch (SQLException ex) {
                        throw errorHandler.handleUserException(Context.INSERT, ex);
                    } catch (IOException ex) {
                        if (ex instanceof EOFException && ex.getMessage() == null) {
                            LOGGER.debug(ex);
                            ex = new EOFException("End of file while COPYing data");
                        }
                        throw new SystemException(ex);
                    }
                }
            } catch (SQLException ex) {
                throw errorHandler.handleException(Context.INSERT, ex);
            } finally {
                dsl.configuration().connectionProvider().release(connection);
            }
        }
    }
}
Also used : PGConnection(org.postgresql.PGConnection) Timer(com.codahale.metrics.Timer) SystemException(com.torodb.core.exceptions.SystemException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PGConnection(org.postgresql.PGConnection) EOFException(java.io.EOFException) IOException(java.io.IOException) DataAccessException(org.jooq.exception.DataAccessException)

Aggregations

DataAccessException (org.jooq.exception.DataAccessException)34 SQLException (java.sql.SQLException)14 Test (org.junit.Test)5 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)4 Timed (com.codahale.metrics.annotation.Timed)4 Connection (java.sql.Connection)4 Consumes (javax.ws.rs.Consumes)4 POST (javax.ws.rs.POST)4 Event (keywhiz.log.Event)4 SecretController (keywhiz.service.daos.SecretController)4 ConflictException (keywhiz.service.exceptions.ConflictException)4 IOException (java.io.IOException)3 SQLSyntaxErrorException (java.sql.SQLSyntaxErrorException)3 HashMap (java.util.HashMap)3 Response (javax.ws.rs.core.Response)3 SanitizedSecret (keywhiz.api.model.SanitizedSecret)3 Secret (keywhiz.api.model.Secret)3 StringReader (java.io.StringReader)2 URI (java.net.URI)2 Savepoint (java.sql.Savepoint)2