org.skife.jdbi.v2.exceptions.DBIException Java Examples

The following examples show how to use org.skife.jdbi.v2.exceptions.DBIException. 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: MonitorResultService.java    From SAPNetworkMonitor with GNU General Public License v3.0 6 votes vote down vote up
public Optional<Map<Integer, Map<Boolean, Long>>> getUsable(String accountId, String taskId, String monitorId, long time) throws NiPingException {

        Map<Integer, Map<Boolean, Long>> map = null;
        List<MonitorNiPingResult> results = null;
        try {
            results = monitorNiPingResultDao.getMonitorNiPingResult(accountId, taskId, monitorId, time(time), ">=");
        } catch (DBIException e) {
            log.error("getUsable accountId {} taskId {} monitorId {} time {} error: {}",
                    accountId, taskId, monitorId, time, ExceptionUtils.getMessage(e));
            throw new NiPingException(DBError);
        }
        if (CollectionUtils.isNotEmpty(results)) {
            map = results.stream().collect(groupingBy(MonitorNiPingResult::getType, partitioningBy(MonitorNiPingResult::isUsable, counting())));
        }
        return Optional.ofNullable(map);
    }
 
Example #2
Source File: MonitorResultService.java    From SAPNetworkMonitor with GNU General Public License v3.0 6 votes vote down vote up
public Page<MonitorNiPingResult> list(String accountId, String taskId, String monitorId, long time, Integer type, Long pageNo, Long pageSize) throws NiPingException {
    Page<MonitorNiPingResult> page = new Page<>(pageNo, pageSize);
    try {
        if (pageNo != null || pageSize != null) {
            long totalCount = monitorNiPingResultDao.count(accountId, taskId, monitorId, time(time), condition(null, null, null, type), ">=");
            if (totalCount > 0) {
                page.setTotalCount(totalCount);
                page.setData(monitorNiPingResultDao.select(accountId, taskId, monitorId, time(time), condition(null, null, null, type), this.page(page.getOffset(), page.getPageSize()), ">="));
            }
        }
        else {
            page.setData(monitorNiPingResultDao.selectAll(accountId, taskId, monitorId, time(time), condition(null, null, null, type), ">="));
        }

    } catch (DBIException e) {
        log.error("list results accountId {} taskId {} monitorId {} time {} type {} pageNo {} pageSize" +
                        " {} error: {}",
                accountId, taskId, monitorId, time, type, pageNo, pageSize, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
    return page;
}
 
Example #3
Source File: MonitorService.java    From SAPNetworkMonitor with GNU General Public License v3.0 6 votes vote down vote up
public void saveMonitor(Monitor monitor) throws NiPingException {
    String monitorId = monitor.getMonitorId();

    Date currentDate = new Date();
    String nipingT = monitor.getNipingT();
    monitor.setModifiedTime(currentDate);

    try {
        if (monitorDao.countMonitor(monitorId) == 0) {
            monitor.setCreationTime(currentDate);
            monitor.setStatus(Monitor.Status.active.getStatus());
            monitorDao.insertMonitor(monitor);
            log.debug("monitor {} saved", monitor);

        } else if (StringUtils.isNoneBlank(nipingT)) {
            monitorDao.updateMonitorNiping(monitor);
            log.debug("monitor {} modified", monitor);
        }
    } catch (DBIException e) {
        log.error("monitors: save monitor {} error: {}", monitor, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
}
 
Example #4
Source File: TaskService.java    From SAPNetworkMonitor with GNU General Public License v3.0 6 votes vote down vote up
public void saveMonitorNiPingResult(MonitorNiPingResult monitorNiPingResult) throws NiPingException {
    Date currentDate = new Date();
    monitorNiPingResult.setCreationTime(currentDate);
    monitorNiPingResult.setModifiedTime(currentDate);
    monitorNiPingResult.setCollectedTime(currentDate.getTime());
    monitorNiPingResult.setStartTime(monitorNiPingResult.getStartTime() * 1000);
    monitorNiPingResult.setEndTime(monitorNiPingResult.getEndTime() * 1000);

    try {
        monitorNiPingResultDao.saveMonitorNiPingResult(monitorNiPingResult);
        log.debug("monitor NiPing result {} saved", monitorNiPingResult);
    } catch (DBIException e) {
        log.error("save monitor niping result {} error: {}", monitorNiPingResult, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
}
 
Example #5
Source File: AuthService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public String getTokenByAccountId(String accountId) throws NiPingException {
    String token = null;
    try {
        token = accessCredentialsDao.getTokenByAccountId(accountId);
    } catch (DBIException e) {
        log.error("user auth: get token by account id {} error: {}", accountId, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
    return token;
}
 
Example #6
Source File: MonitorResultService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public List<Metrics> listAVMetrics(String accountId, String taskId, String monitorId, long time) throws NiPingException {
    try {
        return monitorNiPingResultDao.selectAVMetrics(accountId, taskId, monitorId, MonitorNiPingResult.Type.PERFORMANCE.getValue(), time(time), ">=");
    } catch (DBIException e) {
        log.error("list tr metrics accountId {} taskId {} monitorId {} time {} error: {}",
                accountId, taskId, monitorId, time, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
}
 
Example #7
Source File: MonitorService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public boolean inactiveAllMonitors() throws NiPingException {
    try {
        monitorDao.updateAllMonitorsStatus(Monitor.Status.inactive.getStatus(), new Date(System.currentTimeMillis()));
        log.debug("all monitors setted to inactive");
    } catch (DBIException e) {
        log.error("inactive all monitors error: {}", ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
    return true;
}
 
Example #8
Source File: MonitorService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public boolean modifyMonitorsStatus(List<String> monitorIds, Monitor.Status status) throws NiPingException {
    if (CollectionUtils.isNotEmpty(monitorIds)) {
        try {
            monitorDao.updateMonitorsStatus(monitorIds, status.getStatus(), new Date(System.currentTimeMillis()));
            log.error("modify monitors {} status {}", Arrays.toString(monitorIds.toArray(new String[]{})), status);
        } catch (DBIException e) {
            log.error("modify monitors {} status {} error: {}", Arrays.toString(monitorIds.toArray(new String[]{})), status,
                    ExceptionUtils.getMessage(e));
            throw new NiPingException(DBError);
        }
    }
    return true;
}
 
Example #9
Source File: MonitorService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public Optional<List<Monitor>> listActiveMonitors(String accountId) throws NiPingException {
    Optional<List<Monitor>> monitors = Optional.empty();
    try {
        monitors = Optional.ofNullable(monitorDao.selectByAccountId(accountId, Monitor.Status.active.getStatus()));
        log.debug("select account {} monitors {}", accountId, Arrays.toString(monitors.get().toArray(new Monitor[]{})));
    }
    catch (DBIException e) {
        log.error("list monitors error: {}", ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
    return monitors;
}
 
Example #10
Source File: MonitorService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public Optional<List<Monitor>> listAllMonitors(String accountId) throws NiPingException {
    Optional<List<Monitor>> monitors = Optional.empty();
    try {
        monitors = Optional.ofNullable(monitorDao.selectAllByAccountId(accountId));
        log.debug("select account {} monitors {}", accountId, Arrays.toString(monitors.get().toArray(new Monitor[]{})));
    }
    catch (DBIException e) {
        log.error("list monitors error: {}", ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
    return monitors;
}
 
Example #11
Source File: MonitorService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public List<Monitor> listMonitors(String accountId, String taskId, String country, String province, String city) throws NiPingException {
    try {
        return monitorDao.selectMonitors(accountId, taskId, condition(country, province, city));
    } catch (DBIException e) {
        log.error("list monitors by accountId {} taskId {} country {} province {} city {} error: {}", accountId, taskId, country, province, city, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
}
 
Example #12
Source File: AuthService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public Optional<AccessCredentials> getCredentialsByToken(String credentials) {
    AccessCredentials accessCredentials = null;
    try {
        accessCredentials = accessCredentialsDao.getCredentialsByToken(credentials);
    } catch (DBIException e) {
        log.error("user auth: get credentials by token {} database error: {}", credentials, ExceptionUtils.getMessage(e));
    }
    return Optional.ofNullable(accessCredentials);
}
 
Example #13
Source File: MonitorResultService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public List<Metrics> listTRMetrics(String accountId, String taskId, String monitorId, long time) throws NiPingException {
    try {
        return monitorNiPingResultDao.selectTRMetrics(accountId, taskId, monitorId, MonitorNiPingResult.Type.PERFORMANCE.getValue(), time(time), ">=");
    } catch (DBIException e) {
        log.error("list tr metrics accountId {} taskId {} monitorId {} time {} error: {}",
                accountId, taskId, monitorId, time, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
}
 
Example #14
Source File: PostgresStorage.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<RepairRun> deleteRepairRun(UUID id) {
  RepairRun result = null;
  Handle handle = null;
  try {
    handle = jdbi.open();
    handle.begin();
    IStoragePostgreSql pg = getPostgresStorage(handle);
    RepairRun runToDelete = pg.getRepairRun(UuidUtil.toSequenceId(id));
    if (runToDelete != null) {
      int segmentsRunning
          = pg.getSegmentAmountForRepairRunWithState(UuidUtil.toSequenceId(id), RepairSegment.State.RUNNING);
      if (segmentsRunning == 0) {
        pg.deleteRepairSegmentsForRun(UuidUtil.toSequenceId(runToDelete.getId()));
        pg.deleteRepairRun(UuidUtil.toSequenceId(id));
        result = runToDelete.with()
            .runState(RepairRun.RunState.DELETED)
            .endTime(DateTime.now())
            .build(id);
      } else {
        LOG.warn("not deleting RepairRun \"{}\" as it has segments running: {}", id, segmentsRunning);
      }
    }
    handle.commit();
  } catch (DBIException ex) {
    LOG.warn("DELETE failed", ex);
    if (handle != null) {
      handle.rollback();
    }
  } finally {
    if (handle != null) {
      handle.close();
    }
  }
  return Optional.ofNullable(result);
}
 
Example #15
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean store(DependencyModel dependencyModel) {
    try {
        final Optional<DependencyModel> storedModel = retrieve(dependencyModel.getDependencyId(), dependencyModel.getDateTime());
        return (storedModel.isPresent() && storedModel.get().equals(dependencyModel)) || dependencyDB.insert(dependencyModel) == 1;
    } catch (DBIException err) {
        LOGGER.warn("Failed to store: {}", dependencyModel, err);
    }
    return false;
}
 
Example #16
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean store(ServiceModel serviceModel) {
    try {
        return retrieve(serviceModel.getServiceId(), serviceModel.getDependencyId()).isPresent() ||
               serviceDB.insert(serviceModel) == 1;
    } catch (DBIException err) {
        LOGGER.warn("Failed to store: {}", serviceModel, err);
    }
    return false;
}
 
Example #17
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(ServiceModel serviceModel) {
    try {
        return serviceDB.delete(serviceModel) >= 0;
    } catch (DBIException err) {
        LOGGER.warn("Failed to delete: {}", serviceModel, err);
        return false;
    }
}
 
Example #18
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(DependencyModel dependencyModel) {
    try {
        return dependencyDB.delete(dependencyModel.getDependencyId(), dependencyModel.getDateTime()) >= 0;
    } catch (DBIException err) {
        LOGGER.warn("Failed to delete: {}", dependencyModel, err);
        return false;
    }
}
 
Example #19
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(DependencyId dependencyId, DateTime dateTime) {
    try {
        return dependencyDB.delete(dependencyId, dateTime) >= 0;
    } catch (DBIException err) {
        LOGGER.warn("Failed to delete: {}, {}", dependencyId, dateTime, err);
        return false;
    }
}
 
Example #20
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ServiceModel> retrieve(ServiceId serviceId, DependencyId dependencyId) {
    try {
        return Optional.ofNullable(serviceDB.find(new ServiceModel(serviceId, dependencyId)));
    } catch (DBIException err) {
        LOGGER.warn("Failed to retrieve {}:{}", serviceId, dependencyId, err);
        return Optional.empty();
    }
}
 
Example #21
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<DependencyModel> retrieve(DependencyId dependencyId, DateTime dateTime) {
    try {
        return Optional.ofNullable(dependencyDB.find(dependencyId, dateTime));
    } catch (DBIException err) {
        LOGGER.warn("Failed to retrieve {}, {}", dependencyId, dateTime.getMillis(), err);
        return Optional.empty();
    }
}
 
Example #22
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<DependencyModel> retrieveLatest(DependencyId dependencyId, ServiceId serviceId) {
    try {
        return Optional.ofNullable(dependencyDB.findLatest(dependencyId, serviceId));
    } catch (DBIException err) {
        LOGGER.warn("Failed to retrieve {}, {}", dependencyId, serviceId, err);
        return Optional.empty();
    }
}
 
Example #23
Source File: DBIExceptionLogger.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Override
protected <T> void logException(DBIException exception, HystrixInvokableInfo<T> command) {
    DBI_ERRORS.mark();
    final Throwable cause = Throwables.getRootCause(exception);
    if (cause instanceof SQLException) {
        sqlExceptionLogger.logSQLException((SQLException) cause, command);
    } else {
        logger.error("DBI problem running command: {}:{}", command.getCommandKey(), command.getClass().getSimpleName(), exception);
    }
}
 
Example #24
Source File: MonitorResultService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public List<String> listCities(String accountId, String country, String province) throws NiPingException {
    try {
        return monitorNiPingResultDao.selectCities(accountId, country, province);
    } catch (DBIException e) {
        log.error("list city accountId {} country {} province {} error: {}", accountId, country, province, ExceptionUtils.getMessage
                (e));
        throw new NiPingException(DBError);
    }
}
 
Example #25
Source File: ShardMetadataRecordCursor.java    From presto with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static Iterator<Long> getTableIds(IDBI dbi, TupleDomain<Integer> tupleDomain)
{
    Map<Integer, Domain> domains = tupleDomain.getDomains().get();
    Domain schemaNameDomain = domains.get(getColumnIndex(SHARD_METADATA, SCHEMA_NAME));
    Domain tableNameDomain = domains.get(getColumnIndex(SHARD_METADATA, TABLE_NAME));

    List<String> values = new ArrayList<>();
    StringBuilder sql = new StringBuilder("SELECT table_id FROM tables ");
    if (schemaNameDomain != null || tableNameDomain != null) {
        sql.append("WHERE ");
        List<String> predicates = new ArrayList<>();
        if (tableNameDomain != null && tableNameDomain.isSingleValue()) {
            predicates.add("table_name = ?");
            values.add(getStringValue(tableNameDomain.getSingleValue()));
        }
        if (schemaNameDomain != null && schemaNameDomain.isSingleValue()) {
            predicates.add("schema_name = ?");
            values.add(getStringValue(schemaNameDomain.getSingleValue()));
        }
        sql.append(Joiner.on(" AND ").join(predicates));
    }

    ImmutableList.Builder<Long> tableIds = ImmutableList.builder();
    try (Connection connection = dbi.open().getConnection();
            PreparedStatement statement = connection.prepareStatement(sql.toString())) {
        for (int i = 0; i < values.size(); i++) {
            statement.setString(i + 1, values.get(i));
        }
        try (ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                tableIds.add(resultSet.getLong("table_id"));
            }
        }
    }
    catch (SQLException | DBIException e) {
        throw metadataError(e);
    }
    return tableIds.build().iterator();
}
 
Example #26
Source File: DatabaseShardManager.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public void dropTable(long tableId)
{
    runTransaction(dbi, (handle, status) -> {
        lockTable(handle, tableId);

        ShardDao shardDao = shardDaoSupplier.attach(handle);
        shardDao.insertDeletedShards(tableId);
        shardDao.dropShardNodes(tableId);
        shardDao.dropShards(tableId);

        handle.attach(ShardOrganizerDao.class).dropOrganizerJobs(tableId);

        MetadataDao dao = handle.attach(MetadataDao.class);
        dao.dropColumns(tableId);
        dao.dropTable(tableId);
        return null;
    });

    // TODO: add a cleanup process for leftover index tables
    // It is not possible to drop the index tables in a transaction.
    try (Handle handle = dbi.open()) {
        handle.execute("DROP TABLE " + shardIndexTable(tableId));
    }
    catch (DBIException e) {
        log.warn(e, "Failed to drop index table %s", shardIndexTable(tableId));
    }
}
 
Example #27
Source File: DatabaseShardManager.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public void addColumn(long tableId, ColumnInfo column)
{
    String columnType = sqlColumnType(column.getType());
    if (columnType == null) {
        return;
    }

    String sql = format("ALTER TABLE %s ADD COLUMN (%s %s, %s %s)",
            shardIndexTable(tableId),
            minColumn(column.getColumnId()), columnType,
            maxColumn(column.getColumnId()), columnType);

    int attempts = 0;
    while (true) {
        attempts++;
        try (Handle handle = dbi.open()) {
            handle.execute(sql);
        }
        catch (DBIException e) {
            if (isSyntaxOrAccessError(e)) {
                // exit when column already exists
                return;
            }
            if (attempts >= MAX_ADD_COLUMN_ATTEMPTS) {
                throw metadataError(e);
            }
            log.warn(e, "Failed to alter table on attempt %s, will retry. SQL: %s", attempts, sql);
            try {
                SECONDS.sleep(3);
            }
            catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw metadataError(ie);
            }
        }
    }
}
 
Example #28
Source File: DatabaseShardManager.java    From presto with Apache License 2.0 5 votes vote down vote up
private void runCommit(long transactionId, HandleConsumer callback)
{
    int maxAttempts = 5;
    for (int attempt = 1; attempt <= maxAttempts; attempt++) {
        try {
            dbi.useTransaction((handle, status) -> {
                ShardDao dao = shardDaoSupplier.attach(handle);
                if (commitTransaction(dao, transactionId)) {
                    callback.useHandle(handle);
                    dao.deleteCreatedShards(transactionId);
                }
            });
            return;
        }
        catch (DBIException e) {
            if (isTransactionCacheFullError(e)) {
                throw metadataError(e, "Transaction too large");
            }

            if (e.getCause() != null) {
                throwIfInstanceOf(e.getCause(), PrestoException.class);
            }

            if (attempt == maxAttempts) {
                throw metadataError(e);
            }
            log.warn(e, "Failed to commit shards on attempt %d, will retry.", attempt);
            try {
                SECONDS.sleep(multiplyExact(attempt, 2));
            }
            catch (InterruptedException ie) {
                throw metadataError(ie);
            }
        }
    }
}
 
Example #29
Source File: DatabaseUtil.java    From presto with Apache License 2.0 5 votes vote down vote up
public static <T> T runTransaction(IDBI dbi, TransactionCallback<T> callback)
{
    try {
        return dbi.inTransaction(callback);
    }
    catch (DBIException e) {
        if (e.getCause() != null) {
            throwIfInstanceOf(e.getCause(), PrestoException.class);
        }
        throw metadataError(e);
    }
}
 
Example #30
Source File: TaskService.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
public void modifyTaskRedispatcher(String taskId)  throws NiPingException {
    try {
        monitorTaskDao.updateMonitorTaskRedispatcher(taskId, MonitorTask.Redispatcher.NeedRedispatcher.getRedispatcher());
        log.debug("update task {} redispatcher", taskId);
    } catch (DBIException e) {
        log.error("update task {} redispatcher error: {}", taskId, ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
}