org.jooq.exception.DataAccessException Java Examples
The following examples show how to use
org.jooq.exception.DataAccessException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoggingDataAccessExceptionMapperTest.java From droptools with Apache License 2.0 | 6 votes |
@Test public void logsAllUnderlyingCauses() { SQLException one = new SQLException("a"); SQLException two = new SQLException("b"); SQLException e = new SQLException("fail"); e.setNextException(one); e.setNextException(two); DataAccessException dae = new DataAccessException("moar fail", e); mapper.logException(0, dae); verify(logger).error(anyString(), eq(e)); verify(logger).error(anyString(), eq(one)); verify(logger).error(anyString(), eq(two)); }
Example #2
Source File: SecretDAOTest.java From keywhiz with Apache License 2.0 | 6 votes |
@Test(expected = DataAccessException.class) public void createSecretFailsIfNameMatchesDeletedSecret() { String name = "newSecret"; long firstId = secretDAO.createSecret(name, "content1", cryptographer.computeHmac("content1".getBytes(UTF_8), "hmackey"), "creator1", ImmutableMap.of("foo", "bar"), 1000, "description1", "type1", ImmutableMap.of()); // When a secret is deleted, its name should be changed. However, if the name is not changed // for some reason or a name matching the altered name is used, secret creation will fail. jooqContext.update(SECRETS) .set(SECRETS.CURRENT, (Long) null) .where(SECRETS.ID.eq(firstId)) .execute(); secretDAO.createSecret(name, "content2", cryptographer.computeHmac("content2".getBytes(UTF_8), "hmackey"), "creator2", ImmutableMap.of("foo2", "bar2"), 2000, "description2", "type2", ImmutableMap.of()); }
Example #3
Source File: MetricsDSLContextTest.java From micrometer with Apache License 2.0 | 6 votes |
@Test void timeFaultySelectStatement() throws SQLException { try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:faultySelect")) { MetricsDSLContext jooq = createDatabase(conn); jooq.tag("name", "selectAllAuthors").fetch("SELECT non_existent_field FROM author"); failBecauseExceptionWasNotThrown(DataAccessException.class); } catch (DataAccessException ignored) { } assertThat(meterRegistry.get("jooq.query") .tag("name", "selectAllAuthors") .tag("type", "read") .tag("exception", "c42 syntax error or access rule violation") .tag("exception.subclass", "none") .timer().count()) .isEqualTo(1); }
Example #4
Source File: DatabaseHandler.java From FROST-Server with GNU Lesser General Public License v3.0 | 6 votes |
public boolean isValidUser(String userName, String password) { maybeUpdateDatabase(); try { Record1<Integer> one = getDslContext() .selectOne() .from(TableUsers.USERS) .where( TableUsers.USERS.userName.eq(userName) .and(TableUsers.USERS.userPass.eq(password)) ).fetchOne(); return one != null; } catch (DataAccessException exc) { LOGGER.error("Failed to check user credentials.", exc); return false; } }
Example #5
Source File: DatabaseHandler.java From FROST-Server with GNU Lesser General Public License v3.0 | 6 votes |
/** * This method checks if the given user exists and has the given role. * * @param userName The username of the user to check the role for. * @param userPass The password of the user to check the role for. * @param roleName The role to check. * @return true if the user exists AND has the given password AND has the * given role. */ public boolean userHasRole(String userName, String userPass, String roleName) { maybeUpdateDatabase(); try { Record1<Integer> one = getDslContext() .selectOne() .from(TableUsers.USERS) .leftJoin(TableUsersRoles.USER_ROLES) .on(TableUsers.USERS.userName.eq(TableUsersRoles.USER_ROLES.userName)) .where( TableUsers.USERS.userName.eq(userName) .and(TableUsers.USERS.userPass.eq(userPass)) .and(TableUsersRoles.USER_ROLES.roleName.eq(roleName)) ).fetchOne(); return one != null; } catch (DataAccessException exc) { LOGGER.error("Failed to check user rights.", exc); return false; } finally { connectionProvider.doRollback(); } }
Example #6
Source File: ResultBuilder.java From FROST-Server with GNU Lesser General Public License v3.0 | 6 votes |
private <R extends Record> Cursor<R> timeQuery(ResultQuery<R> query) { if (persistenceSettings.isTimeoutQueries()) { query.queryTimeout(persistenceSettings.getQueryTimeout()); } if (!persistenceSettings.isLogSlowQueries()) { return query.fetchLazy(); } long start = System.currentTimeMillis(); Cursor<R> result; try { result = query.fetchLazy(); } catch (DataAccessException exc) { if (LOGGER.isWarnEnabled()) { LOGGER.info("Failed to run query:\n{}", query.getSQL(ParamType.INLINED)); } throw new IllegalStateException("Failed to run query: " + exc.getMessage()); } long end = System.currentTimeMillis(); long duration = end - start; if (LOGGER.isInfoEnabled() && duration > persistenceSettings.getSlowQueryThreshold()) { LOGGER.info("Slow Query executed in {} ms:\n{}", duration, query.getSQL(ParamType.INLINED)); } return result; }
Example #7
Source File: JooqHealthCheckTest.java From droptools with Apache License 2.0 | 6 votes |
@Test public void isUnhealthyIfTransactionFails() throws Exception { MockDataProvider mockDataProvider = new MockDataProvider() { @Override public MockResult[] execute(MockExecuteContext ctx) throws SQLException { throw new SQLException("BOOM"); } }; try { runHealthCheck(mockDataProvider); assert_().fail(); } catch (DataAccessException e) { assertThat(e.getMessage()).contains(validationQuery); assertThat(e.getMessage()).contains("BOOM"); } }
Example #8
Source File: ClientsResource.java From keywhiz with Apache License 2.0 | 5 votes |
/** * Create Client * * @param user the admin user creating this client * @param createClientRequest the JSON client request used to formulate the Client * @return 200 if the client is created successfully, 409 if it already exists * <p> * description Creates a Client with the name from a valid client request. Used by Keywhiz CLI and * the web ui. * <p> * responseMessage 200 Successfully created Client * <p> * responseMessage 409 Client with given name already exists */ @Timed @ExceptionMetered @POST @Consumes(APPLICATION_JSON) public Response createClient(@Auth User user, @Valid CreateClientRequestV2 createClientRequest) { logger.info("User '{}' creating client '{}'.", user, createClientRequest.name()); long clientId; try { clientId = clientDAO.createClient(createClientRequest.name(), user.getName(), createClientRequest.description(), new URI(createClientRequest.spiffeId())); } catch (DataAccessException | URISyntaxException 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; }
Example #9
Source File: SelectQueryMapper.java From SimpleFlatMapper with MIT License | 5 votes |
public <SET extends TableLike & ResultQuery> AutoCloseableEnumerable<T> enumerate(SET source) throws MappingException { SetRowMapper<ResultSet, ResultSet, T, SQLException> mapper = getMapper(source); try { final ResultSet rs = source.fetchResultSet(); final Enumerable<T> enumerable = new ExceptionTranslatorEnumerable<T>(mapper.enumerate(rs)); return new AutoCloseableEnumerable<T>(enumerable, closer(rs)); } catch (SQLException e) { throw new DataAccessException(e.getMessage(), e); } }
Example #10
Source File: SecretDAOTest.java From keywhiz with Apache License 2.0 | 5 votes |
@Test(expected = DataAccessException.class) public void createSecretFailsIfSecretExists() { String name = "newSecret"; secretDAO.createSecret(name, "some secret", "checksum", "creator", ImmutableMap.of(), 0, "", null, ImmutableMap.of()); secretDAO.createSecret(name, "some secret", "checksum", "creator", ImmutableMap.of(), 0, "", null, ImmutableMap.of()); }
Example #11
Source File: SelectQueryMapper.java From SimpleFlatMapper with MIT License | 5 votes |
private Closer closer(final ResultSet rs) { return new Closer() { @Override public void close() { try { rs.close(); } catch (SQLException e) { throw new DataAccessException(e.getMessage(), e); } } }; }
Example #12
Source File: AutomationSecretResourceTest.java From keywhiz with Apache License 2.0 | 5 votes |
@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); }
Example #13
Source File: SecretsResourceTest.java From keywhiz with Apache License 2.0 | 5 votes |
@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(); CreateSecretRequestV2 req = CreateSecretRequestV2.builder() .name("name") .description("desc") .content("content") .build(); resource.createSecret(user, req); }
Example #14
Source File: LoggingDataAccessExceptionMapper.java From droptools with Apache License 2.0 | 5 votes |
@Override protected void logException(long id, DataAccessException exception) { final Throwable cause = exception.getCause(); if (cause instanceof SQLException) { for (Throwable throwable : (SQLException) cause) { logger.error(formatLogMessage(id, throwable), throwable); } } else { logger.error(formatLogMessage(id, exception), exception); } }
Example #15
Source File: AutomationSecretResource.java From keywhiz with Apache License 2.0 | 5 votes |
/** * Create secret * * @param automationClient the client with automation access performing this operation * @param request JSON request to formulate the secret * @return details on the newly created secret, or 409 if the secret name already exists * * description Creates a secret with the name, content, and metadata from a valid secret request * responseMessage 200 Successfully created secret * responseMessage 409 Secret with given name already exists */ @Timed @ExceptionMetered @POST @Consumes(APPLICATION_JSON) public AutomationSecretResponse createSecret( @Auth AutomationClient automationClient, @Valid CreateSecretRequest request) { SecretController.SecretBuilder builder = secretController.builder(request.name, request.content, automationClient.getName(), request.expiry) .withDescription(nullToEmpty(request.description)); if (request.metadata != null) { builder.withMetadata(request.metadata); } Secret secret; try { secret = builder.create(); } catch (DataAccessException e) { logger.info(format("Cannot create secret %s", request.name), e); throw new ConflictException(format("Cannot create secret %s.", request.name)); } ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(secret)); Map<String, String> extraInfo = new HashMap<>(); extraInfo.put("deprecated", "true"); if (request.description != null) { extraInfo.put("description", request.description); } if (request.metadata != null) { extraInfo.put("metadata", request.metadata.toString()); } extraInfo.put("expiry", Long.toString(request.expiry)); auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATE, automationClient.getName(), request.name, extraInfo)); return AutomationSecretResponse.fromSecret(secret, groups); }
Example #16
Source File: LoggingDataAccessExceptionMapperTest.java From droptools with Apache License 2.0 | 5 votes |
@Test public void logsUnderlyingSQLException() { SQLException cause = new SQLException("BAR"); DataAccessException e = new DataAccessException("FOO", cause); mapper.logException(0, e); verify(logger).error(anyString(), eq(cause)); }
Example #17
Source File: JooqHealthCheck.java From keywhiz with Apache License 2.0 | 5 votes |
@Override protected Result check() throws Exception { try { databaseAgnostic(dataSource).selectOne().execute(); } catch (DataAccessException | SQLException e) { switch (onFailure) { case LOG_ONLY: logger.warn("Unhealthy connection to database."); break; case RETURN_UNHEALTHY: return Result.unhealthy("Unhealthy connection to database."); } } return Result.healthy(); }
Example #18
Source File: JooqRepository.java From datashare with GNU Affero General Public License v3.0 | 5 votes |
@Override public boolean getHealth(){ try { return DSL.using(connectionProvider, dialect).select().fetchOne().toString().contains("1"); } catch (DataAccessException ex){ LoggerFactory.getLogger(getClass()).error("Database Health error : ",ex); return false; } }
Example #19
Source File: JooqExecuteListener.java From micrometer with Apache License 2.0 | 5 votes |
private void stopTimerIfStillRunning(ExecuteContext ctx) { Iterable<Tag> queryTags = queryTagsSupplier.get(); if (queryTags == null) return; Timer.Sample sample; synchronized (sampleLock) { sample = sampleByExecuteContext.remove(ctx); } if (sample == null) return; String exceptionName = "none"; String exceptionSubclass = "none"; Exception exception = ctx.exception(); if (exception != null) { if (exception instanceof DataAccessException) { DataAccessException dae = (DataAccessException) exception; exceptionName = dae.sqlStateClass().name().toLowerCase().replace('_', ' '); exceptionSubclass = dae.sqlStateSubclass().name().toLowerCase().replace('_', ' '); if (exceptionSubclass.contains("no subclass")) { exceptionSubclass = "none"; } } else { String simpleName = exception.getClass().getSimpleName(); exceptionName = StringUtils.isNotBlank(simpleName) ? simpleName : exception.getClass().getName(); } } //noinspection unchecked sample.stop(Timer.builder("jooq.query") .description("Execution time of a SQL query performed with JOOQ") .tags(queryTags) .tag("type", ctx.type().name().toLowerCase()) .tag("exception", exceptionName) .tag("exception.subclass", exceptionSubclass) .tags(tags) .register(registry)); }
Example #20
Source File: LoggingDataAccessExceptionMapperTest.java From droptools with Apache License 2.0 | 5 votes |
@Test public void logsExceptionItselfIfNoSQLException() { DataAccessException e = new DataAccessException("BAZ"); mapper.logException(0, e); verify(logger).error(anyString(), eq(e)); }
Example #21
Source File: SecretDAO.java From keywhiz with Apache License 2.0 | 4 votes |
@VisibleForTesting public long createSecret(String name, 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 -> { // disallow use of a leading period in secret names // 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); 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, creator, description, type, generationOptions, now); } long secretContentId = secretContentDAO.createSecretContent(secretId, encryptedSecret, hmac, creator, metadata, expiry, now); secretSeriesDAO.setCurrentVersion(secretId, secretContentId, creator, now); return secretId; }); }
Example #22
Source File: ApplicationDao.java From waltz with Apache License 2.0 | 4 votes |
public AppRegistrationResponse registerApp(AppRegistrationRequest request) { checkNotEmpty(request.name(), "Cannot register app with no name"); LOG.info("Registering new application: "+request); ApplicationRecord record = dsl.newRecord(APPLICATION); record.setName(request.name()); record.setDescription(request.description().orElse("TBC")); record.setAssetCode(request.assetCode().orElse("")); record.setParentAssetCode(request.parentAssetCode().orElse("")); record.setOrganisationalUnitId(request.organisationalUnitId()); record.setKind(request.applicationKind().name()); record.setLifecyclePhase(request.lifecyclePhase().name()); record.setOverallRating(request.overallRating().name()); record.setUpdatedAt(Timestamp.from(Instant.now())); record.setBusinessCriticality(request.businessCriticality().name()); record.setProvenance(request.provenance().orElse("waltz")); try { int count = record.insert(); if (count == 1) { return ImmutableAppRegistrationResponse.builder() .id(record.getId()) .message("created") .originalRequest(request) .build(); } else { return ImmutableAppRegistrationResponse.builder() .message("Failed") .originalRequest(request) .build(); } } catch (DataAccessException dae) { return ImmutableAppRegistrationResponse.builder() .message("Could not create app because: " + dae.getMessage()) .originalRequest(request) .build(); } }
Example #23
Source File: GroupDAOTest.java From keywhiz with Apache License 2.0 | 4 votes |
@Test(expected = DataAccessException.class) public void willNotCreateDuplicateGroup() throws Exception { groupDAO.createGroup("group1", "creator1", "", ImmutableMap.of()); }
Example #24
Source File: MicronautTransactionProvider.java From micronaut-sql with Apache License 2.0 | 4 votes |
@Override public void begin(TransactionContext context) throws DataAccessException { TransactionDefinition definition = TransactionDefinition.DEFAULT; TransactionStatus<Connection> status = transactionManager.getTransaction(definition); context.transaction(new MicronautTransaction(status)); }
Example #25
Source File: SecretResource.java From keywhiz with Apache License 2.0 | 4 votes |
/** * Creates a secret and assigns to given groups * * @param request JSON request to create a secret * * responseMessage 201 Created secret and assigned to given groups * responseMessage 409 Secret already exists */ @Timed @ExceptionMetered @POST @Consumes(APPLICATION_JSON) public Response createSecret(@Auth AutomationClient automationClient, @Valid CreateSecretRequestV2 request) { // allows new version, return version in resulting path String name = request.name(); String user = automationClient.getName(); SecretBuilder builder = secretController .builder(name, request.content(), automationClient.getName(), request.expiry()) .withDescription(request.description()) .withMetadata(request.metadata()) .withType(request.type()); Secret secret; try { secret = builder.create(); } catch (DataAccessException e) { logger.info(format("Cannot create secret %s", name), e); throw new ConflictException(format("Cannot create secret %s.", name)); } Map<String, String> extraInfo = new HashMap<>(); if (request.description() != null) { extraInfo.put("description", request.description()); } if (request.metadata() != null) { extraInfo.put("metadata", request.metadata().toString()); } extraInfo.put("expiry", Long.toString(request.expiry())); auditLog.recordEvent(new Event(Instant.now(), EventTag.SECRET_CREATE, user, name, extraInfo)); long secretId = secret.getId(); groupsToGroupIds(request.groups()) .forEach((maybeGroupId) -> maybeGroupId.ifPresent( (groupId) -> aclDAO.findAndAllowAccess(secretId, groupId, auditLog, user, new HashMap<>()))); UriBuilder uriBuilder = UriBuilder.fromResource(SecretResource.class).path(name); return Response.created(uriBuilder.build()).build(); }
Example #26
Source File: SecretsResource.java From keywhiz with Apache License 2.0 | 4 votes |
/** * Create Secret * * @param user the admin user performing this operation * @param request the JSON client request used to formulate the Secret * @return 201 on success, 400 if a secret with the given name already exists * <p> * description Creates a Secret with the name from a valid secret request. Used by Keywhiz CLI and * the web ui. * <p> * responseMessage 201 Successfully created Secret * <p> * responseMessage 400 Secret with given name already exists */ @Timed @ExceptionMetered @POST @Consumes(APPLICATION_JSON) public Response createSecret(@Auth User user, @Valid CreateSecretRequestV2 request) { logger.info("User '{}' creating secret '{}'.", user, request.name()); Secret secret; try { SecretController.SecretBuilder builder = secretController.builder(request.name(), request.content(), user.getName(), request.expiry()); if (request.description() != null) { builder.withDescription(request.description()); } if (request.metadata() != null) { builder.withMetadata(request.metadata()); } secret = builder.create(); } catch (DataAccessException e) { logger.info(format("Cannot create secret %s", request.name()), e); throw new ConflictException(format("Cannot create secret %s.", request.name())); } URI uri = UriBuilder.fromResource(SecretsResource.class).path("{secretId}").build(secret.getId()); Response response = Response .created(uri) .entity(secretDetailResponseFromId(secret.getId())) .build(); if (response.getStatus() == HttpStatus.SC_CREATED) { Map<String, String> extraInfo = new HashMap<>(); if (request.description() != null) { extraInfo.put("description", request.description()); } if (request.metadata() != null) { extraInfo.put("metadata", request.metadata().toString()); } extraInfo.put("expiry", Long.toString(request.expiry())); auditLog.recordEvent( new Event(Instant.now(), EventTag.SECRET_CREATE, user.getName(), request.name(), extraInfo)); } // TODO (jessep): Should we also log failures? return response; }
Example #27
Source File: MicronautTransactionProvider.java From micronaut-sql with Apache License 2.0 | 4 votes |
@Override public void rollback(TransactionContext ctx) throws DataAccessException { transactionManager.rollback(getTransactionStatus(ctx)); }
Example #28
Source File: MicronautTransactionProvider.java From micronaut-sql with Apache License 2.0 | 4 votes |
@Override public void commit(TransactionContext ctx) throws DataAccessException { transactionManager.commit(getTransactionStatus(ctx)); }