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

The following examples show how to use com.datastax.driver.core.exceptions.AlreadyExistsException. 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: 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 #2
Source File: CassandraCluster.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private void createPolygeneStateTable( String tableName )
{
    try
    {
        session.execute( "CREATE TABLE " + tableName + "(\n"
                         + "   " + IDENTITY_COLUMN + " text,\n"
                         + "   " + VERSION_COLUMN + " text,\n"
                         + "   " + TYPE_COLUMN + " text,\n"
                         + "   " + APP_VERSION_COLUMN + " text,\n"
                         + "   " + STORE_VERSION_COLUMN + " text,\n"
                         + "   " + LASTMODIFIED_COLUMN + " timestamp,\n"
                         + "   " + USECASE_COLUMN + " text,\n"
                         + "   " + PROPERTIES_COLUMN + " map<text,text>,\n"
                         + "   " + ASSOCIATIONS_COLUMN + " map<text,text>,\n"
                         + "   " + MANYASSOCIATIONS_COLUMN + " map<text,text>,\n"
                         + "   " + NAMEDASSOCIATIONS_COLUMN + " map<text,text>,\n"
                         + "   PRIMARY KEY ( " + IDENTITY_COLUMN + " )\n"
                         + "   )" );
    }
    catch( AlreadyExistsException e )
    {
        // This is OK, as we try to create on every connect().
    }
}
 
Example #3
Source File: SaveToCassandraOperationsService.java    From Decision with Apache License 2.0 6 votes vote down vote up
public void createTable(String tableName, List<ColumnNameTypeValue> columns, String timestampColumnName) {
    StringBuilder sb = new StringBuilder();

    for (Entry<String, String> entry : getStreamFieldsAndTypes(columns).entrySet()) {
        sb.append(addQuotes(entry.getKey()));
        sb.append(" ");
        sb.append(entry.getValue());
        sb.append(",");
    }
    try {
        session.execute(String
                .format("CREATE TABLE %s.%s (%s timeuuid, %s PRIMARY KEY (%s)) WITH compression = {'sstable_compression': ''}",
                        STREAMING.STREAMING_KEYSPACE_NAME, addQuotes(tableName), addQuotes(timestampColumnName),
                        sb.toString(), addQuotes(timestampColumnName)));
    } catch (AlreadyExistsException e) {
        log.info("Stream table {} already exists", tableName);
    }
}
 
Example #4
Source File: ErrorResultIntegrationTest.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldReturnAlreadyExistsKeyspace() throws Exception {
  String keyspace = "ks";
  server.prime(when(query).then(alreadyExists(keyspace)));

  thrown.expect(AlreadyExistsException.class);
  thrown.expectMessage(containsString(keyspace));
  query();
}
 
Example #5
Source File: ErrorResultIntegrationTest.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldReturnAlreadyExistsTable() throws Exception {
  String keyspace = "ks";
  String table = "tbl";
  server.prime(when(query).then(alreadyExists(keyspace, table)));

  thrown.expect(AlreadyExistsException.class);
  thrown.expectMessage(containsString(keyspace + "." + table));
  query();
}
 
Example #6
Source File: BasicSteps.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static void createKeyspace(String keyspaceName) {
  try (Cluster cluster = buildCluster(); Session tmpSession = cluster.connect()) {
    VersionNumber lowestNodeVersion = getCassandraVersion(tmpSession);

    try {
      if (null == tmpSession.getCluster().getMetadata().getKeyspace(keyspaceName)) {
        tmpSession.execute(
            "CREATE KEYSPACE "
                + (VersionNumber.parse("2.0").compareTo(lowestNodeVersion) <= 0 ? "IF NOT EXISTS " : "")
                + keyspaceName
              + " WITH replication = {" + buildNetworkTopologyStrategyString(cluster) + "}");
      }
    } catch (AlreadyExistsException ignore) { }
  }
}
 
Example #7
Source File: BasicSteps.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static void createTable(String keyspaceName, String tableName) {
  try (Cluster cluster = buildCluster(); Session tmpSession = cluster.connect()) {
    VersionNumber lowestNodeVersion = getCassandraVersion(tmpSession);

    String createTableStmt
        = "CREATE TABLE "
            + (VersionNumber.parse("2.0").compareTo(lowestNodeVersion) <= 0 ? "IF NOT EXISTS " : "")
            + keyspaceName
            + "."
            + tableName
            + "(id int PRIMARY KEY, value text)";

    if (tableName.endsWith("twcs")) {
      if (((VersionNumber.parse("3.0.8").compareTo(lowestNodeVersion) <= 0
          && VersionNumber.parse("3.0.99").compareTo(lowestNodeVersion) >= 0)
          || VersionNumber.parse("3.8").compareTo(lowestNodeVersion) <= 0)) {
        // TWCS is available by default
        createTableStmt
            += " WITH compaction = {'class':'TimeWindowCompactionStrategy',"
                + "'compaction_window_size': '1', "
                + "'compaction_window_unit': 'MINUTES'}";
      } else if (VersionNumber.parse("2.0.11").compareTo(lowestNodeVersion) <= 0) {
        createTableStmt += " WITH compaction = {'class':'DateTieredCompactionStrategy'}";
      }
    }

    try {
      if (null == tmpSession.getCluster().getMetadata().getKeyspace(keyspaceName).getTable(tableName)) {
        tmpSession.execute(createTableStmt);
      }
    } catch (AlreadyExistsException ignore) { }

    for (int i = 0; i < 100; i++) {
      tmpSession.execute(
          "INSERT INTO " + keyspaceName + "." + tableName + "(id, value) VALUES(" + i + ",'" + i + "')");
    }
  }
}
 
Example #8
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 #9
Source File: ConnectionManager.java    From Rhombus with MIT License 5 votes vote down vote up
/**
 *
 * @param keyspaceName Name of keyspace to get/create
 * @param keyspace The keyspace to use as a template for replication information
 * @return true if keyspace existed previously, false if it was created
 */
private boolean createKeyspaceIfNotExists(String keyspaceName, CKeyspaceDefinition keyspace, boolean alterIfExists) {
	Preconditions.checkNotNull(keyspace, "A template keyspace must be supplied for replication information");
	Session session = cluster.connect();
	//First try to create the new keyspace
	StringBuilder sb = new StringBuilder();
	sb.append(keyspaceName);
	sb.append(" WITH replication = { 'class' : '");
	sb.append(keyspace.getReplicationClass());
	sb.append("'");
	for(String key : keyspace.getReplicationFactors().keySet()) {
		sb.append(", '");
		sb.append(key);
		sb.append("' : ");
		sb.append(keyspace.getReplicationFactors().get(key));
	}
	sb.append("};");
	try {
		String cql = "CREATE KEYSPACE " + sb.toString();
		session.execute(cql);
		session.close();
		logger.debug("Successfully created keyspace {}", keyspaceName);
		return false;
	} catch(AlreadyExistsException e) {
		logger.debug("Keyspace {} already exists", keyspaceName);
		// If the keyspace already existed, alter it to match the definition
		if(alterIfExists) {
			try {
				session.execute("ALTER KEYSPACE " + sb.toString());
			} catch(Exception e2) {
				logger.error("Unable to alter keyspace {}", keyspaceName, e2);
			}
		}
		session.close();
		return true;
	}
}
 
Example #10
Source File: CassandraSessionImpl.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Creates Cassandra keyspace.
 *
 * @param settings Persistence settings.
 */
private void createKeyspace(KeyValuePersistenceSettings settings) {
    int attempt = 0;
    Throwable error = null;
    String errorMsg = "Failed to create Cassandra keyspace '" + settings.getKeyspace() + "'";

    while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) {
        WrappedSession ses = null;

        try {
            ses = session();

            if (log.isInfoEnabled()) {
                log.info("-----------------------------------------------------------------------");
                log.info("Creating Cassandra keyspace '" + settings.getKeyspace() + "'");
                log.info("-----------------------------------------------------------------------\n\n" +
                    settings.getKeyspaceDDLStatement() + "\n");
                log.info("-----------------------------------------------------------------------");
            }

            ses.execute(settings.getKeyspaceDDLStatement());

            if (log.isInfoEnabled())
                log.info("Cassandra keyspace '" + settings.getKeyspace() + "' was successfully created");

            return;
        }
        catch (AlreadyExistsException ignored) {
            if (log.isInfoEnabled())
                log.info("Cassandra keyspace '" + settings.getKeyspace() + "' already exist");

            return;
        }
        catch (Throwable e) {
            if (!CassandraHelper.isHostsAvailabilityError(e))
                throw new IgniteException(errorMsg, e);

            handleHostsAvailabilityError(ses == null ? 0 : ses.generation, e, attempt, errorMsg);

            error = e;
        }

        attempt++;
    }

    throw new IgniteException(errorMsg, error);
}
 
Example #11
Source File: CassandraSessionImpl.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Creates Cassandra table.
 *
 * @param settings Persistence settings.
 */
private void createTable(String table, KeyValuePersistenceSettings settings) {
    int attempt = 0;
    Throwable error = null;
    String tableFullName = settings.getKeyspace() + "." + table;
    String errorMsg = "Failed to create Cassandra table '" + tableFullName + "'";

    while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) {
        WrappedSession ses = null;

        try {
            ses = session();

            if (log.isInfoEnabled()) {
                log.info("-----------------------------------------------------------------------");
                log.info("Creating Cassandra table '" + tableFullName + "'");
                log.info("-----------------------------------------------------------------------\n\n" +
                    settings.getTableDDLStatement(table) + "\n");
                log.info("-----------------------------------------------------------------------");
            }

            ses.execute(settings.getTableDDLStatement(table));

            if (log.isInfoEnabled())
                log.info("Cassandra table '" + tableFullName + "' was successfully created");

            return;
        }
        catch (AlreadyExistsException ignored) {
            if (log.isInfoEnabled())
                log.info("Cassandra table '" + tableFullName + "' already exist");

            return;
        }
        catch (Throwable e) {
            if (!CassandraHelper.isHostsAvailabilityError(e) && !CassandraHelper.isKeyspaceAbsenceError(e))
                throw new IgniteException(errorMsg, e);

            if (CassandraHelper.isKeyspaceAbsenceError(e)) {
                log.warning("Failed to create Cassandra table '" + tableFullName +
                    "' cause appropriate keyspace doesn't exist", e);
                createKeyspace(settings);
            }
            else if (CassandraHelper.isHostsAvailabilityError(e))
                handleHostsAvailabilityError(ses == null ? 0 : ses.generation, e, attempt, errorMsg);

            error = e;
        }

        attempt++;
    }

    throw new IgniteException(errorMsg, error);
}