com.datastax.driver.core.exceptions.DriverException Java Examples

The following examples show how to use com.datastax.driver.core.exceptions.DriverException. 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: CassandraStore.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a cluster object.
 */
public void buildCluster()
{
  try {
    if (protocolVersion != null && protocolVersion.length() != 0) {
      ProtocolVersion version = getCassandraProtocolVersion();
      cluster = Cluster.builder().addContactPoint(node).withCredentials(userName, password).withProtocolVersion(version).build();
    } else {
      cluster = Cluster.builder().addContactPoint(node).withCredentials(userName, password).build();
    }
  } catch (DriverException ex) {
    throw new RuntimeException("closing database resource", ex);
  } catch (Throwable t) {
    DTThrowable.rethrow(t);
  }
}
 
Example #2
Source File: BatchHandlerTest.java    From scalardb with Apache License 2.0 6 votes vote down vote up
@Test
public void handle_DriverExceptionThrownInExecution_ShouldThrowRetriableExecutionException() {
  // Arrange
  configureBehavior();
  mutations = prepareConditionalPuts();
  DriverException e = mock(DriverException.class);
  when(session.execute(any(Statement.class))).thenThrow(e);

  // Act Assert
  assertThatThrownBy(
          () -> {
            batch.handle(mutations);
          })
      .isInstanceOf(RetriableExecutionException.class)
      .hasCause(e);
}
 
Example #3
Source File: InsertStatementHandlerTest.java    From scalardb with Apache License 2.0 6 votes vote down vote up
@Test
public void handle_DriverExceptionThrown_ShouldThrowProperExecutionException()
    throws ExecutionException {
  // Arrange
  put = preparePutWithClusteringKey();
  spy = prepareSpiedInsertStatementHandler();

  DriverException toThrow = mock(DriverException.class);
  doThrow(toThrow).when(spy).handleInternal(put);

  // Act Assert
  assertThatThrownBy(
          () -> {
            spy.handle(put);
          })
      .isInstanceOf(ExecutionException.class)
      .hasCause(toThrow);
}
 
Example #4
Source File: CassandraConnectorDatabaseService.java    From metacat with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DatabaseInfo get(
    @Nonnull @NonNull final ConnectorRequestContext context,
    @Nonnull @NonNull final QualifiedName name
) {
    final String keyspace = name.getDatabaseName();
    log.debug("Attempting to get keyspace metadata for keyspace {} for request {}", keyspace, context);
    try {
        final KeyspaceMetadata keyspaceMetadata = this.getCluster().getMetadata().getKeyspace(keyspace);
        if (keyspaceMetadata == null) {
            throw new DatabaseNotFoundException(name);
        }

        log.debug("Successfully found the keyspace metadata for {} for request {}", name, context);
        return DatabaseInfo.builder().name(name).build();
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, name);
    }
}
 
Example #5
Source File: CassandraCqlIncrementalState.java    From storm-cassandra-cql with Apache License 2.0 6 votes vote down vote up
@Override
public void commit(Long txid) {
    DriverException lastException = null;
    // Read current value.
    //if we failed to apply the update , maybe the state has change already , we need to calculate the new state and apply it again
    for (Map.Entry<K, V> entry : aggregateValues.entrySet()) {
        int attempts = 0;
        boolean applied = false;
        while (!applied && attempts < maxAttempts) {
            try{
                applied = updateState(entry, txid);
            } catch(QueryExecutionException e) {
                lastException = e;
                LOG.warn("Catching {} attempt {}"+txid+"-"+partitionIndex, e.getMessage(), attempts);
            }
            attempts++;
        }
        if(!applied) {
            if(lastException != null) {
                throw new CassandraCqlIncrementalStateException("Ran out of attempts ["+attempts+"] max of ["+maxAttempts+"] "+txid+"-"+ partitionIndex, lastException);
            } else {
                throw new CassandraCqlIncrementalStateException("Ran out of attempts ["+attempts+"] max of ["+maxAttempts+"] "+txid+"-"+ partitionIndex);
            }
        }
    }
}
 
Example #6
Source File: CassandraConnectorTableService.java    From metacat with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public TableInfo get(@Nonnull @NonNull final ConnectorRequestContext context,
                     @Nonnull @NonNull final QualifiedName name) {
    final String keyspace = name.getDatabaseName();
    final String table = name.getTableName();
    log.debug("Attempting to get metadata for Cassandra table {}.{} for request {}", keyspace, table, context);
    try {
        final KeyspaceMetadata keyspaceMetadata = this.getCluster().getMetadata().getKeyspace(keyspace);
        if (keyspaceMetadata == null) {
            throw new DatabaseNotFoundException(name);
        }
        final TableMetadata tableMetadata = keyspaceMetadata.getTable(table);
        if (tableMetadata == null) {
            throw new TableNotFoundException(name);
        }

        final TableInfo tableInfo = this.getTableInfo(name, tableMetadata);
        log.debug("Successfully got metadata for Cassandra table {}.{} for request {}", keyspace, table, context);
        return tableInfo;
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, name);
    }
}
 
Example #7
Source File: MetricsServiceImpl.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
private <T> Observable.Transformer<T, T> applyRetryPolicy() {
    return tObservable -> tObservable
            .retryWhen(observable -> {
                Observable<Integer> range = Observable.range(1, Integer.MAX_VALUE);
                Observable<Observable<?>> zipWith = observable.zipWith(range, (t, i) -> {
                    log.debug("Attempt #" + i + " to retry the operation after Cassandra client" +
                            " exception");
                    if (t instanceof DriverException) {
                        return Observable.timer(i, TimeUnit.SECONDS).onBackpressureDrop();
                    } else {
                        return Observable.error(t);
                    }
                });

                return Observable.merge(zipWith);
            })
            .doOnError(t -> log.error("Failure while trying to apply compression, skipping block", t))
            .onErrorResumeNext(Observable.empty());
}
 
Example #8
Source File: ClusterManagerTest.java    From scalardb with Apache License 2.0 6 votes vote down vote up
@Test
public void getSession_CalledOnceAndDriverExceptionThrown_ShouldThrowConnectionException() {
  // Arrange
  DriverException toThrow = mock(DriverException.class);
  when(cluster.connect()).thenThrow(toThrow);

  // Act Assert
  assertThatThrownBy(
          () -> {
            manager.getSession();
          })
      .isInstanceOf(ConnectionException.class)
      .hasCause(toThrow);

  // Assert
  verify(manager).build();
  verify(cluster).connect();
}
 
Example #9
Source File: CassandraConnectorDatabaseService.java    From metacat with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void create(
    @Nonnull @NonNull final ConnectorRequestContext context,
    @Nonnull @NonNull final DatabaseInfo resource
) {
    final String keyspace = resource.getName().getDatabaseName();
    log.debug("Attempting to create a Cassandra Keyspace named {} for request {}", keyspace, context);
    try {
        // TODO: Make this take parameters for replication and the class
        this.executeQuery(
            "CREATE KEYSPACE "
                + keyspace
                + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3};"
        );
        log.debug("Successfully created Cassandra Keyspace named {} for request {}", keyspace, context);
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, resource.getName());
    }
}
 
Example #10
Source File: DataAccessImpl.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
private <T> Observable.Transformer<T, T> applyInsertRetryPolicy() {
    return tObservable -> tObservable
            .retryWhen(errors -> {
                Observable<Integer> range = Observable.range(1, 2);
                return errors
                        .zipWith(range, (t, i) -> {
                            if (t instanceof DriverException) {
                                return i;
                            }
                            throw Exceptions.propagate(t);
                        })
                        .flatMap(retryCount -> {
                            long delay = (long) Math.min(Math.pow(2, retryCount) * 1000, 3000);
                            log.debug("Retrying batch insert in " + delay + " ms");
                            return Observable.timer(delay, TimeUnit.MILLISECONDS);
                        });
            });
}
 
Example #11
Source File: CassandraRepo.java    From monasca-persister with Apache License 2.0 6 votes vote down vote up
private void retryQuery(String id, Statement query, final long startTime, int retryCount,
    DriverException e) throws DriverException {
  if (retryCount >= maxWriteRetries) {
    logger.error("[{}]: Query aborted after {} retry: ", id, retryCount, e.getMessage());
    metricFailed.inc(((BatchStatement) query).size());
    commitTimer.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
    throw e;
  } else {
    logger.warn("[{}]: Query failed, retrying {} of {}: {} ", id, retryCount, maxWriteRetries,
        e.getMessage());

    try {
      Thread.sleep(1000 * (1 << retryCount));
    } catch (InterruptedException ie) {
      logger.debug("[{}]: Interrupted: {}", id, ie);
    }
    _executeQuery(id, query, startTime, retryCount++);
  }
}
 
Example #12
Source File: DatastaxMapperBuilder.java    From SimpleFlatMapper with MIT License 6 votes vote down vote up
/**
 * @param classMeta                  the meta for the target class.
 * @param mapperConfig               the mapperConfig.
 * @param getterFactory              the Getter factory.
 * @param parentBuilder              the parent builder, null if none.
 */
public DatastaxMapperBuilder(
        final ClassMeta<T> classMeta,
        MapperConfig<DatastaxColumnKey, Row> mapperConfig,
        ContextualGetterFactory<? super GettableByIndexData, DatastaxColumnKey> getterFactory,
        MappingContextFactoryBuilder<Row, DatastaxColumnKey> parentBuilder) {
    super(KEY_FACTORY, 
            new DefaultSetRowMapperBuilder<Row, ResultSet, T, DatastaxColumnKey, DriverException>(
                    classMeta, parentBuilder, mapperConfig,
                    new MapperSourceImpl<GettableByIndexData, DatastaxColumnKey>(GettableByIndexData.class, getterFactory),
                    KEY_FACTORY, new ResultSetEnumerableFactory(), DatastaxKeySourceGetter.INSTANCE),
            new BiFunction<SetRowMapper<Row, ResultSet, T, DriverException>, List<DatastaxColumnKey>, DatastaxMapper<T>>() {
                @Override
                public DatastaxMapper<T> apply(SetRowMapper<Row, ResultSet, T, DriverException> setRowMapper, List<DatastaxColumnKey> keys) {
                    return new DatastaxMapperImpl<T>(setRowMapper);
                }
            },
            COLUMN_DEFINITION_FACTORY, 0);
}
 
Example #13
Source File: CassandraExceptionMapper.java    From metacat with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the given Cassandra driver exception to a corresponding ConnectorException if possible, otherwise
 * return a generic ConnectorException.
 *
 * @param de   The Cassandra driver exception
 * @param name The fully qualified name of the resource which was attempting to be accessed or modified at time of
 *             error
 * @return A connector exception wrapping the DriverException
 */
public ConnectorException toConnectorException(
    @Nonnull @NonNull final DriverException de,
    @Nonnull @NonNull final QualifiedName name
) {
    if (de instanceof AlreadyExistsException) {
        final AlreadyExistsException ae = (AlreadyExistsException) de;
        if (ae.wasTableCreation()) {
            return new TableAlreadyExistsException(name, ae);
        } else {
            return new DatabaseAlreadyExistsException(name, ae);
        }
    } else {
        return new ConnectorException(de.getMessage(), de);
    }
}
 
Example #14
Source File: CassandraApplicationTest.java    From examples with Apache License 2.0 6 votes vote down vote up
private static void insertEventsInTable(int numEvents)
{
  try {
    Cluster cluster = Cluster.builder().addContactPoint(NODE).build();
    Session session = cluster.connect(KEYSPACE);

    String insert = "INSERT INTO " + KEYSPACE + "." + TABLE_NAME + " (ID,lastname,age)" + " VALUES (?,?,?);";
    PreparedStatement stmt = session.prepare(insert);
    BoundStatement boundStatement = new BoundStatement(stmt);
    for (int i = 0; i < numEvents; i++) {
      ids.add(UUID.randomUUID());
      mapNames.put(i, "test" + i);
      mapAge.put(i, i + 10);
      session.execute(boundStatement.bind(ids.get(i), mapNames.get(i), mapAge.get(i)));
    }
  } catch (DriverException e) {
    throw new RuntimeException(e);
  }
}
 
Example #15
Source File: CustomerEnrichedInfoCassandraOutputOperator.java    From examples with Apache License 2.0 6 votes vote down vote up
@Override
protected Statement setStatementParameters(PreparedStatement updateCommand, SingleRecord tuple) throws DriverException
{
  final BoundStatement boundStmnt = new BoundStatement(updateCommand);
  boundStmnt.setString(0, tuple.id);
  boundStmnt.setString(1, tuple.imsi);
  boundStmnt.setString(2, tuple.isdn);
  boundStmnt.setString(3, tuple.imei);
  boundStmnt.setString(4, tuple.operatorName);
  boundStmnt.setString(5, tuple.operatorCode);
  boundStmnt.setString(6, tuple.deviceBrand);
  boundStmnt.setString(7, tuple.deviceModel);

  //or boundStatement.bind();
  return boundStmnt;
}
 
Example #16
Source File: EnrichedCustomerServiceCassandraOutputOperator.java    From examples with Apache License 2.0 6 votes vote down vote up
@Override
protected Statement setStatementParameters(PreparedStatement updateCommand, EnrichedCustomerService tuple)
    throws DriverException
{
  final BoundStatement boundStmnt = new BoundStatement(updateCommand);
  boundStmnt.setLong(0, ++id);
  boundStmnt.setString(1, tuple.imsi);
  boundStmnt.setInt(2, tuple.totalDuration);
  boundStmnt.setInt(3, tuple.wait);
  boundStmnt.setString(4, tuple.zipCode);
  boundStmnt.setString(5, tuple.issueType.name());
  boundStmnt.setBool(6, tuple.satisfied);
  boundStmnt.setString(7, tuple.operatorCode);
  boundStmnt.setString(8, tuple.deviceBrand);
  boundStmnt.setString(9, tuple.deviceModel);

  //or boundStatement.bind();
  return boundStmnt;

}
 
Example #17
Source File: CustomerServiceCassandraOutputOperator.java    From examples with Apache License 2.0 6 votes vote down vote up
@Override
protected Statement setStatementParameters(PreparedStatement updateCommand, CustomerService tuple)
    throws DriverException
{
  final BoundStatement boundStmnt = new BoundStatement(updateCommand);
  boundStmnt.setLong(0, ++id);
  boundStmnt.setString(1, tuple.imsi);
  boundStmnt.setInt(2, tuple.totalDuration);
  boundStmnt.setInt(3, tuple.wait);
  boundStmnt.setString(4, tuple.zipCode);
  boundStmnt.setString(5, tuple.issueType.name());
  boundStmnt.setBool(6, tuple.satisfied);

  //or boundStatement.bind();
  return boundStmnt;

}
 
Example #18
Source File: SelectStatementHandlerTest.java    From scalardb with Apache License 2.0 6 votes vote down vote up
@Test
public void handle_DriverExceptionThrown_ShouldThrowProperExecutionException()
    throws ExecutionException {
  // Arrange
  get = prepareGetWithClusteringKey();
  SelectStatementHandler spy = Mockito.spy(new SelectStatementHandler(session));
  doReturn(prepared).when(spy).prepare(get);
  doReturn(bound).when(spy).bind(prepared, get);

  DriverException toThrow = mock(DriverException.class);
  doThrow(toThrow).when(spy).handleInternal(get);

  // Act
  assertThatThrownBy(
          () -> {
            spy.handle(get);
          })
      .isInstanceOf(ExecutionException.class)
      .hasCause(toThrow);

  // Assert
}
 
Example #19
Source File: MetricCassandraCollector.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    pendingRequestCounter.decrementAndGet();
    try {
        future.getUninterruptibly();
    } catch (DriverException e) {
        cassandraErrorCount.increment();
        if (event != null) {
            if (event.get(JetstreamReservedKeys.MessageAffinityKey
                    .toString()) == null) {
                event.put(JetstreamReservedKeys.MessageAffinityKey
                        .toString(), (String) event
                        .get(MCConstant.METRIC_NAME));
            }
            getAdviceListener().retry(event, RetryEventCode.MSG_RETRY,
                    e.getMessage());
            eventSentToAdviceListener.increment();
        }
        registerError(e);
    }
}
 
Example #20
Source File: CassandraOperatorTest.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
public void insertEventsInTable(int numEvents)
{
  try {
    Cluster cluster = Cluster.builder().addContactPoint(NODE).build();
    Session session = cluster.connect(KEYSPACE);

    String insert = "INSERT INTO " + TABLE_NAME_INPUT + " (ID,lastname,age)" + " VALUES (?,?,?);";
    PreparedStatement stmt = session.prepare(insert);
    BoundStatement boundStatement = new BoundStatement(stmt);
    for (int i = 0; i < numEvents; i++) {
      ids.add(i);
      mapNames.put(i, "test" + i);
      mapAge.put(i, i + 10);
      session.execute(boundStatement.bind(i, "test" + i, i + 10));
    }
  } catch (DriverException e) {
    throw new RuntimeException(e);
  }
}
 
Example #21
Source File: CassandraTransactionalStore.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public long getCommittedWindowId(String appId, int operatorId)
{
  try {
    BoundStatement boundStatement = new BoundStatement(lastWindowFetchCommand);
    lastWindowFetchStatement = boundStatement.bind(appId,operatorId);
    long lastWindow = -1;
    ResultSet resultSet = session.execute(lastWindowFetchStatement);
    if (!resultSet.isExhausted()) {
      lastWindow = resultSet.one().getLong(0);
    }
    lastWindowFetchCommand.disableTracing();
    return lastWindow;
  } catch (DriverException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #22
Source File: CassandraStore.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
/**
 * Create connection with database.
 */
@Override
public void connect()
{
  try {
    if (cluster == null) {
      buildCluster();
    }
    session = cluster.connect();
    logger.debug("Cassandra connection Success");
  } catch (DriverException ex) {
    throw new RuntimeException("closing database resource", ex);
  } catch (Throwable t) {
    DTThrowable.rethrow(t);
  }
}
 
Example #23
Source File: CassandraCqlMapState.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
protected void checkCassandraException(Exception e) {
    _mexceptions.incr();
    if (e instanceof AlreadyExistsException ||
            e instanceof AuthenticationException ||
            e instanceof DriverException ||
            e instanceof DriverInternalError ||
            e instanceof InvalidConfigurationInQueryException ||
            e instanceof InvalidQueryException ||
            e instanceof InvalidTypeException ||
            e instanceof QueryExecutionException ||
            e instanceof QueryValidationException ||
            e instanceof ReadTimeoutException ||
            e instanceof SyntaxError ||
            e instanceof TraceRetrievalException ||
            e instanceof TruncateException ||
            e instanceof UnauthorizedException ||
            e instanceof UnavailableException ||
            e instanceof ReadTimeoutException ||
            e instanceof WriteTimeoutException ||
            e instanceof ReadFailureException ||
            e instanceof WriteFailureException ||
            e instanceof FunctionExecutionException) {
        throw new ReportedFailedException(e);
    } else {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: LogConsistencyAllRetryPolicy.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
    if (cl == ConsistencyLevel.ALL) {
        log(statement);
    }
    return DefaultRetryPolicy.INSTANCE.onRequestError(statement, cl, e, nbRetry);
}
 
Example #25
Source File: DatastaxMapperFactory.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Override
public SetRowMapper<Row, ResultSet, T, DriverException> newInstance(MapperKey<DatastaxColumnKey> datastaxColumnKeyMapperKey) {
    DatastaxMapperBuilder<T> builder = newBuilder(classMeta);

    for(DatastaxColumnKey key : datastaxColumnKeyMapperKey.getColumns()) {
        builder.addMapping(key);
    }

    return builder.mapper();
}
 
Example #26
Source File: CassandraTransactionalStore.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void storeCommittedWindowId(String appId, int operatorId, long windowId)
{
  try {
    BoundStatement boundStatement = new BoundStatement(lastWindowUpdateCommand);
    lastWindowUpdateStatement = boundStatement.bind(windowId,appId,operatorId);
    batchCommand.add(lastWindowUpdateStatement);
  } catch (DriverException e) {
    throw new RuntimeException(e);
  }
}
 
Example #27
Source File: CassandraTransactionalStore.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void disconnect()
{
  if (lastWindowUpdateCommand != null) {
    try {
      lastWindowUpdateCommand.disableTracing();
    } catch (DriverException e) {
      throw new RuntimeException(e);
    }
  }
  super.disconnect();
}
 
Example #28
Source File: CassandraStore.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
/**
 * Close connection.
 */
@Override
public void disconnect()
{
  try {
    session.close();
    cluster.close();
  } catch (DriverException ex) {
    throw new RuntimeException("closing database resource", ex);
  } catch (Throwable t) {
    DTThrowable.rethrow(t);
  }
}
 
Example #29
Source File: CassandraStore.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isConnected()
{
  try {
    return !session.isClosed();
  } catch (DriverException ex) {
    throw new RuntimeException("closing database resource", ex);
  }
}
 
Example #30
Source File: TestCassandraSink.java    From ingestion with Apache License 2.0 5 votes vote down vote up
@Ignore @Test
public void processDriverException() throws EventDeliveryException {
  final CassandraSink sink = new CassandraSink();
  final Channel channel = mock(Channel.class);
  final Transaction tx = mock(Transaction.class);
  final CassandraTable table = mock(CassandraTable.class);
  final Context ctx = new Context();
  ctx.put("tables", "keyspace.table");
  sink.configure(ctx);
  sink.tables = Collections.singletonList(table);
  sink.setChannel(channel);
  when(channel.getTransaction()).thenReturn(tx);
  final Event event = EventBuilder.withBody(new byte[0], ImmutableMap.of("id", "1", "col", "text"));
  when(channel.take()).thenReturn(event).thenReturn(null);
  doThrow(DriverException.class).when(table).save(anyListOf(Event.class));
  boolean hasThrown = false;
  try {
    sink.process();
  } catch (EventDeliveryException ex) {
    hasThrown = true;
    if (!(ex.getCause() instanceof DriverException)) {
      fail("Did not throw inner DriverException: " + ex);
    }
  }
  verify(tx).begin();
  verify(tx).rollback();
  verify(tx).close();
  verifyNoMoreInteractions(tx);
  if (!hasThrown) {
    fail("Did not throw exception");
  }
}