Java Code Examples for org.apache.cassandra.exceptions.ConfigurationException

The following are top voted examples for showing how to use org.apache.cassandra.exceptions.ConfigurationException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: sstable-adaptor   File: CompressionParams.java   View source code 6 votes vote down vote up
/**
 * Parse the chunk length (in KB) and returns it as bytes.
 *
 * @param chLengthKB the length of the chunk to parse
 * @return the chunk length in bytes
 * @throws ConfigurationException if the chunk size is too large
 */
private static Integer parseChunkLength(String chLengthKB) throws ConfigurationException
{
    if (chLengthKB == null)
        return null;

    try
    {
        int parsed = Integer.parseInt(chLengthKB);
        if (parsed > Integer.MAX_VALUE / 1024)
            throw new ConfigurationException(format("Value of %s is too large (%s)", CHUNK_LENGTH_IN_KB,parsed));
        return 1024 * parsed;
    }
    catch (NumberFormatException e)
    {
        throw new ConfigurationException("Invalid value for " + CHUNK_LENGTH_IN_KB, e);
    }
}
 
Example 2
Project: sstable-adaptor   File: CompressionParams.java   View source code 6 votes vote down vote up
public void validate() throws ConfigurationException
{
    // if chunk length was not set (chunkLength == null), this is fine, default will be used
    if (chunkLength != null)
    {
        if (chunkLength <= 0)
            throw new ConfigurationException("Invalid negative or null " + CHUNK_LENGTH_IN_KB);

        int c = chunkLength;
        boolean found = false;
        while (c != 0)
        {
            if ((c & 0x01) != 0)
            {
                if (found)
                    throw new ConfigurationException(CHUNK_LENGTH_IN_KB + " must be a power of 2");
                else
                    found = true;
            }
            c >>= 1;
        }
    }
}
 
Example 3
Project: sstable-adaptor   File: CompressionParams.java   View source code 6 votes vote down vote up
public CompressionParams deserialize(DataInputPlus in, int version) throws IOException
{
    String compressorName = in.readUTF();
    int optionCount = in.readInt();
    Map<String, String> options = new HashMap<>();
    for (int i = 0; i < optionCount; ++i)
    {
        String key = in.readUTF();
        String value = in.readUTF();
        options.put(key, value);
    }
    int chunkLength = in.readInt();
    CompressionParams parameters;
    try
    {
        parameters = new CompressionParams(compressorName, chunkLength, options);
    }
    catch (ConfigurationException e)
    {
        throw new RuntimeException("Cannot create CompressionParams for parameters", e);
    }
    return parameters;
}
 
Example 4
Project: sstable-adaptor   File: LZ4Compressor.java   View source code 6 votes vote down vote up
public static LZ4Compressor create(Map<String, String> args) throws ConfigurationException
{
    String compressorType = validateCompressorType(args.get(LZ4_COMPRESSOR_TYPE));
    Integer compressionLevel = validateCompressionLevel(args.get(LZ4_HIGH_COMPRESSION_LEVEL));

    Pair<String, Integer> compressorTypeAndLevel = Pair.create(compressorType, compressionLevel);
    LZ4Compressor instance = instances.get(compressorTypeAndLevel);
    if (instance == null)
    {
        if (compressorType.equals(LZ4_FAST_COMPRESSOR) && args.get(LZ4_HIGH_COMPRESSION_LEVEL) != null)
            logger.warn("'{}' parameter is ignored when '{}' is '{}'", LZ4_HIGH_COMPRESSION_LEVEL, LZ4_COMPRESSOR_TYPE, LZ4_FAST_COMPRESSOR);
        instance = new LZ4Compressor(compressorType, compressionLevel);
        LZ4Compressor instanceFromMap = instances.putIfAbsent(compressorTypeAndLevel, instance);
        if(instanceFromMap != null)
            instance = instanceFromMap;
    }
    return instance;
}
 
Example 5
Project: sstable-adaptor   File: LZ4Compressor.java   View source code 6 votes vote down vote up
public static String validateCompressorType(String compressorType) throws ConfigurationException
{
    if (compressorType == null)
        return DEFAULT_LZ4_COMPRESSOR_TYPE;

    if (!VALID_COMPRESSOR_TYPES.contains(compressorType))
    {
        throw new ConfigurationException(String.format("Invalid compressor type '%s' specified for LZ4 parameter '%s'. "
                                                       + "Valid options are %s.", compressorType, LZ4_COMPRESSOR_TYPE,
                                                       VALID_COMPRESSOR_TYPES.toString()));
    }
    else
    {
        return compressorType;
    }
}
 
Example 6
Project: sstable-adaptor   File: LZ4Compressor.java   View source code 6 votes vote down vote up
public static Integer validateCompressionLevel(String compressionLevel) throws ConfigurationException
{
    if (compressionLevel == null)
        return DEFAULT_HIGH_COMPRESSION_LEVEL;

    ConfigurationException ex = new ConfigurationException("Invalid value [" + compressionLevel + "] for parameter '"
                                                             + LZ4_HIGH_COMPRESSION_LEVEL + "'. Value must be between 1 and 17.");

    Integer level;
    try
    {
        level = Integer.valueOf(compressionLevel);
    }
    catch (NumberFormatException e)
    {
        throw ex;
    }

    if (level < 1 || level > 17)
    {
        throw ex;
    }

    return level;
}
 
Example 7
Project: jhipster-ribbon-hystrix   File: _AbstractCassandraTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void startServer() throws InterruptedException, TTransportException, ConfigurationException, IOException {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    Cluster cluster = new Cluster.Builder().addContactPoints("127.0.0.1").withPort(9142).build();
    Session session = cluster.connect();
    CQLDataLoader dataLoader = new CQLDataLoader(session);
    dataLoader.load(new ClassPathCQLDataSet("config/cql/create-tables.cql", true, "cassandra_unit_keyspace"));
}
 
Example 8
Project: Docussandra   File: Fixtures.java   View source code 6 votes vote down vote up
/**
 * Ensures that the Mock Cassandra instance is up and running. Will reinit
 * the database every time it is called.
 *
 * @param cassandraKeyspace Cassandra keyspace to setup.
 * @return A cluster object.
 * @throws ConfigurationException
 * @throws IOException
 * @throws InterruptedException
 * @throws TTransportException
 */
public static Cluster ensureMockCassandraRunningAndEstablished(String cassandraKeyspace) throws ConfigurationException, IOException, InterruptedException, TTransportException
{
    Cluster cluster;
    long timeout = 60000;
    EmbeddedCassandraServerHelper.startEmbeddedCassandra(timeout);
    cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
    //Thread.sleep(20000);//time to let cassandra startup
    final Metadata metadata = cluster.getMetadata();

    Session session = cluster.connect();
    Utils.initDatabase(DB_CQL, session);
    session = cluster.connect(cassandraKeyspace);

    logger.info("Connected to cluster: " + metadata.getClusterName() + '\n');
    return cluster;
}
 
Example 9
Project: ACaZoo   File: CompressionParameters.java   View source code 6 votes vote down vote up
/**
 * Parse the chunk length (in KB) and returns it as bytes.
 */
public static Integer parseChunkLength(String chLengthKB) throws ConfigurationException
{
    if (chLengthKB == null)
        return null;

    try
    {
        int parsed = Integer.parseInt(chLengthKB);
        if (parsed > Integer.MAX_VALUE / 1024)
            throw new ConfigurationException("Value of " + CHUNK_LENGTH_KB + " is too large (" + parsed + ")");
        return 1024 * parsed;
    }
    catch (NumberFormatException e)
    {
        throw new ConfigurationException("Invalid value for " + CHUNK_LENGTH_KB, e);
    }
}
 
Example 10
Project: ACaZoo   File: CFMetaData.java   View source code 6 votes vote down vote up
private void validateCompactionThresholds() throws ConfigurationException
{
    if (maxCompactionThreshold == 0)
    {
        logger.warn("Disabling compaction by setting max or min compaction has been deprecated, " +
                "set the compaction strategy option 'enabled' to 'false' instead");
        return;
    }

    if (minCompactionThreshold <= 1)
        throw new ConfigurationException(String.format("Min compaction threshold cannot be less than 2 (got %d).", minCompactionThreshold));

    if (minCompactionThreshold > maxCompactionThreshold)
        throw new ConfigurationException(String.format("Min compaction threshold (got %d) cannot be greater than max compaction threshold (got %d)",
                                                        minCompactionThreshold, maxCompactionThreshold));
}
 
Example 11
Project: ACaZoo   File: CompressionParameters.java   View source code 6 votes vote down vote up
public void validate() throws ConfigurationException
{
    // if chunk length was not set (chunkLength == null), this is fine, default will be used
    if (chunkLength != null)
    {
        if (chunkLength <= 0)
            throw new ConfigurationException("Invalid negative or null " + CHUNK_LENGTH_KB);

        int c = chunkLength;
        boolean found = false;
        while (c != 0)
        {
            if ((c & 0x01) != 0)
            {
                if (found)
                    throw new ConfigurationException(CHUNK_LENGTH_KB + " must be a power of 2");
                else
                    found = true;
            }
            c >>= 1;
        }
    }

    validateCrcCheckChance(crcCheckChance);
}
 
Example 12
Project: scylla-tools-java   File: LeveledCompactionStrategy.java   View source code 6 votes vote down vote up
public static Map<String, String> validateOptions(Map<String, String> options) throws ConfigurationException
{
    Map<String, String> uncheckedOptions = AbstractCompactionStrategy.validateOptions(options);

    String size = options.containsKey(SSTABLE_SIZE_OPTION) ? options.get(SSTABLE_SIZE_OPTION) : "1";
    try
    {
        int ssSize = Integer.parseInt(size);
        if (ssSize < 1)
        {
            throw new ConfigurationException(String.format("%s must be larger than 0, but was %s", SSTABLE_SIZE_OPTION, ssSize));
        }
    }
    catch (NumberFormatException ex)
    {
        throw new ConfigurationException(String.format("%s is not a parsable int (base10) for %s", size, SSTABLE_SIZE_OPTION), ex);
    }

    uncheckedOptions.remove(SSTABLE_SIZE_OPTION);

    uncheckedOptions = SizeTieredCompactionStrategyOptions.validateOptions(options, uncheckedOptions);

    return uncheckedOptions;
}
 
Example 13
Project: ACaZoo   File: CompressionParameters.java   View source code 6 votes vote down vote up
public CompressionParameters deserialize(DataInput in, int version) throws IOException
{
    String compressorName = in.readUTF();
    int optionCount = in.readInt();
    Map<String, String> options = new HashMap<String, String>();
    for (int i = 0; i < optionCount; ++i)
    {
        String key = in.readUTF();
        String value = in.readUTF();
        options.put(key, value);
    }
    int chunkLength = in.readInt();
    CompressionParameters parameters;
    try
    {
        parameters = new CompressionParameters(compressorName, chunkLength, options);
    }
    catch (ConfigurationException e)
    {
        throw new RuntimeException("Cannot create CompressionParameters for parameters", e);
    }
    return parameters;
}
 
Example 14
Project: ACaZoo   File: MerkleTree.java   View source code 6 votes vote down vote up
public MerkleTree deserialize(DataInput in, int version) throws IOException
{
    byte hashdepth = in.readByte();
    long maxsize = in.readLong();
    long size = in.readLong();
    IPartitioner partitioner;
    try
    {
        partitioner = FBUtilities.newPartitioner(in.readUTF());
    }
    catch (ConfigurationException e)
    {
        throw new IOException(e);
    }

    // full range
    Token left = Token.serializer.deserialize(in);
    Token right = Token.serializer.deserialize(in);
    Range<Token> fullRange = new Range<>(left, right, partitioner);

    MerkleTree mt = new MerkleTree(partitioner, fullRange, hashdepth, maxsize);
    mt.size = size;
    mt.root = Hashable.serializer.deserialize(in, version);
    return mt;
}
 
Example 15
Project: cassandra-kmean   File: CreateKeyspaceStatement.java   View source code 6 votes vote down vote up
/**
 * The <code>CqlParser</code> only goes as far as extracting the keyword arguments
 * from these statements, so this method is responsible for processing and
 * validating.
 *
 * @throws InvalidRequestException if arguments are missing or unacceptable
 */
public void validate(ClientState state) throws RequestValidationException
{
    ThriftValidation.validateKeyspaceNotSystem(name);

    // keyspace name
    if (!name.matches("\\w+"))
        throw new InvalidRequestException(String.format("\"%s\" is not a valid keyspace name", name));
    if (name.length() > Schema.NAME_LENGTH)
        throw new InvalidRequestException(String.format("Keyspace names shouldn't be more than %s characters long (got \"%s\")", Schema.NAME_LENGTH, name));

    attrs.validate();

    if (attrs.getReplicationStrategyClass() == null)
        throw new ConfigurationException("Missing mandatory replication strategy class");

    // The strategy is validated through KSMetaData.validate() in announceNewKeyspace below.
    // However, for backward compatibility with thrift, this doesn't validate unexpected options yet,
    // so doing proper validation here.
    AbstractReplicationStrategy.validateReplicationStrategy(name,
                                                            AbstractReplicationStrategy.getClass(attrs.getReplicationStrategyClass()),
                                                            StorageService.instance.getTokenMetadata(),
                                                            DatabaseDescriptor.getEndpointSnitch(),
                                                            attrs.getReplicationOptions());
}
 
Example 16
Project: scylla-tools-java   File: LegacySSTableTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void defineSchema() throws ConfigurationException
{
    SchemaLoader.prepareServer();
    StorageService.instance.initServer();
    Keyspace.setInitialized();
    createKeyspace();
    for (String legacyVersion : legacyVersions)
    {
        createTables(legacyVersion);
    }
    String scp = System.getProperty(LEGACY_SSTABLE_PROP);
    assert scp != null;
    LEGACY_SSTABLE_ROOT = new File(scp).getAbsoluteFile();
    assert LEGACY_SSTABLE_ROOT.isDirectory();
}
 
Example 17
Project: scylla-tools-java   File: DefsTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void defineSchema() throws ConfigurationException
{
    SchemaLoader.prepareServer();
    SchemaLoader.startGossiper();
    SchemaLoader.createKeyspace(KEYSPACE1,
                                KeyspaceParams.simple(1),
                                SchemaLoader.standardCFMD(KEYSPACE1, TABLE1),
                                SchemaLoader.standardCFMD(KEYSPACE1, TABLE2));
    SchemaLoader.createKeyspace(KEYSPACE3,
                                KeyspaceParams.simple(5),
                                SchemaLoader.standardCFMD(KEYSPACE1, TABLE1),
                                SchemaLoader.compositeIndexCFMD(KEYSPACE3, TABLE1i, true));
    SchemaLoader.createKeyspace(KEYSPACE6,
                                KeyspaceParams.simple(1),
                                SchemaLoader.compositeIndexCFMD(KEYSPACE6, TABLE1i, true));
}
 
Example 18
Project: scylla-tools-java   File: EC2SnitchTest.java   View source code 6 votes vote down vote up
@Test
public void testRac() throws IOException, ConfigurationException
{
    az = "us-east-1d";
    Ec2Snitch snitch = new TestEC2Snitch();
    InetAddress local = InetAddress.getByName("127.0.0.1");
    InetAddress nonlocal = InetAddress.getByName("127.0.0.7");

    Gossiper.instance.addSavedEndpoint(nonlocal);
    Map<ApplicationState, VersionedValue> stateMap = new EnumMap<>(ApplicationState.class);
    stateMap.put(ApplicationState.DC, StorageService.instance.valueFactory.datacenter("us-west"));
    stateMap.put(ApplicationState.RACK, StorageService.instance.valueFactory.datacenter("1a"));
    Gossiper.instance.getEndpointStateForEndpoint(nonlocal).addApplicationStates(stateMap);

    assertEquals("us-west", snitch.getDatacenter(nonlocal));
    assertEquals("1a", snitch.getRack(nonlocal));

    assertEquals("us-east", snitch.getDatacenter(local));
    assertEquals("1d", snitch.getRack(local));
}
 
Example 19
Project: scylla-tools-java   File: CompressionParams.java   View source code 6 votes vote down vote up
public void validate() throws ConfigurationException
{
    // if chunk length was not set (chunkLength == null), this is fine, default will be used
    if (chunkLength != null)
    {
        if (chunkLength <= 0)
            throw new ConfigurationException("Invalid negative or null " + CHUNK_LENGTH_IN_KB);

        int c = chunkLength;
        boolean found = false;
        while (c != 0)
        {
            if ((c & 0x01) != 0)
            {
                if (found)
                    throw new ConfigurationException(CHUNK_LENGTH_IN_KB + " must be a power of 2");
                else
                    found = true;
            }
            c >>= 1;
        }
    }
}
 
Example 20
Project: ACaZoo   File: YamlConfigurationLoader.java   View source code 6 votes vote down vote up
/**
 * Inspect the classpath to find storage configuration file
 */
private URL getStorageConfigURL() throws ConfigurationException
{
    String configUrl = System.getProperty("cassandra.config");
    if (configUrl == null)
        configUrl = DEFAULT_CONFIGURATION;

    URL url;
    try
    {
        url = new URL(configUrl);
        url.openStream().close(); // catches well-formed but bogus URLs
    }
    catch (Exception e)
    {
        ClassLoader loader = DatabaseDescriptor.class.getClassLoader();
        url = loader.getResource(configUrl);
        if (url == null)
            throw new ConfigurationException("Cannot locate " + configUrl);
    }

    return url;
}
 
Example 21
Project: cassandra-kmean   File: MerkleTree.java   View source code 6 votes vote down vote up
public MerkleTree deserialize(DataInput in, int version) throws IOException
{
    byte hashdepth = in.readByte();
    long maxsize = in.readLong();
    long size = in.readLong();
    IPartitioner partitioner;
    try
    {
        partitioner = FBUtilities.newPartitioner(in.readUTF());
    }
    catch (ConfigurationException e)
    {
        throw new IOException(e);
    }

    // full range
    Token left = Token.serializer.deserialize(in);
    Token right = Token.serializer.deserialize(in);
    Range<Token> fullRange = new Range<>(left, right, partitioner);

    MerkleTree mt = new MerkleTree(partitioner, fullRange, hashdepth, maxsize);
    mt.size = size;
    mt.root = Hashable.serializer.deserialize(in, version);
    return mt;
}
 
Example 22
Project: scylla-tools-java   File: BootStrapper.java   View source code 6 votes vote down vote up
/**
 * if initialtoken was specified, use that (split on comma).
 * otherwise, if allocationKeyspace is specified use the token allocation algorithm to generate suitable tokens
 * else choose num_tokens tokens at random
 */
public static Collection<Token> getBootstrapTokens(final TokenMetadata metadata, InetAddress address) throws ConfigurationException
{
    String allocationKeyspace = DatabaseDescriptor.getAllocateTokensForKeyspace();
    Collection<String> initialTokens = DatabaseDescriptor.getInitialTokens();
    if (initialTokens.size() > 0 && allocationKeyspace != null)
        logger.warn("manually specified tokens override automatic allocation");

    // if user specified tokens, use those
    if (initialTokens.size() > 0)
        return getSpecifiedTokens(metadata, initialTokens);

    int numTokens = DatabaseDescriptor.getNumTokens();
    if (numTokens < 1)
        throw new ConfigurationException("num_tokens must be >= 1");

    if (allocationKeyspace != null)
        return allocateTokens(metadata, address, allocationKeyspace, numTokens);

    if (numTokens == 1)
        logger.warn("Picking random token for a single vnode.  You should probably add more vnodes and/or use the automatic token allocation mechanism.");

    return getRandomTokens(metadata, numTokens);
}
 
Example 23
Project: scylla-tools-java   File: SSTableWriterTestBase.java   View source code 6 votes vote down vote up
@BeforeClass
public static void defineSchema() throws ConfigurationException
{
    if (FBUtilities.isWindows())
    {
        standardMode = DatabaseDescriptor.getDiskAccessMode();
        indexMode = DatabaseDescriptor.getIndexAccessMode();

        DatabaseDescriptor.setDiskAccessMode(Config.DiskAccessMode.standard);
        DatabaseDescriptor.setIndexAccessMode(Config.DiskAccessMode.standard);
    }

    SchemaLoader.prepareServer();
    SchemaLoader.createKeyspace(KEYSPACE,
                                KeyspaceParams.simple(1),
                                SchemaLoader.standardCFMD(KEYSPACE, CF),
                                SchemaLoader.standardCFMD(KEYSPACE, CF_SMALL_MAX_VALUE));

    maxValueSize = DatabaseDescriptor.getMaxValueSize();
    DatabaseDescriptor.setMaxValueSize(1024 * 1024); // set max value size to 1MB
}
 
Example 24
Project: scylla-tools-java   File: TriggerExecutorTest.java   View source code 6 votes vote down vote up
@Test
public void sameKeySameCfPartialRowMutations() throws ConfigurationException, InvalidRequestException
{
    CFMetaData metadata = makeCfMetaData("ks1", "cf1", TriggerMetadata.create("test", SameKeySameCfPartialTrigger.class.getName()));
    PartitionUpdate cf1 = makeCf(metadata, "k1", "k1v1", null);
    PartitionUpdate cf2 = makeCf(metadata, "k2", "k2v1", null);
    Mutation rm1 = new Mutation("ks1", cf1.partitionKey()).add(cf1);
    Mutation rm2 = new Mutation("ks1", cf2.partitionKey()).add(cf2);

    List<? extends IMutation> tmutations = new ArrayList<>(TriggerExecutor.instance.execute(Arrays.asList(rm1, rm2)));
    assertEquals(2, tmutations.size());
    Collections.sort(tmutations, new RmComparator());

    List<PartitionUpdate> mutatedCFs = new ArrayList<>(tmutations.get(0).getPartitionUpdates());
    assertEquals(1, mutatedCFs.size());
    Row row = mutatedCFs.get(0).iterator().next();
    assertEquals(bytes("k1v1"), row.getCell(metadata.getColumnDefinition(bytes("c1"))).value());
    assertNull(row.getCell(metadata.getColumnDefinition(bytes("c2"))));

    mutatedCFs = new ArrayList<>(tmutations.get(1).getPartitionUpdates());
    assertEquals(1, mutatedCFs.size());
    row = mutatedCFs.get(0).iterator().next();
    assertEquals(bytes("k2v1"), row.getCell(metadata.getColumnDefinition(bytes("c1"))).value());
    assertEquals(bytes("trigger"), row.getCell(metadata.getColumnDefinition(bytes("c2"))).value());
}
 
Example 25
Project: scylla-tools-java   File: MerkleTree.java   View source code 6 votes vote down vote up
public MerkleTree deserialize(DataInputPlus in, int version) throws IOException
{
    byte hashdepth = in.readByte();
    long maxsize = in.readLong();
    long size = in.readLong();
    IPartitioner partitioner;
    try
    {
        partitioner = FBUtilities.newPartitioner(in.readUTF());
    }
    catch (ConfigurationException e)
    {
        throw new IOException(e);
    }

    // full range
    Token left = Token.serializer.deserialize(in, partitioner, version);
    Token right = Token.serializer.deserialize(in, partitioner, version);
    Range<Token> fullRange = new Range<>(left, right);

    MerkleTree mt = new MerkleTree(partitioner, fullRange, hashdepth, maxsize);
    mt.size = size;
    mt.root = Hashable.serializer.deserialize(in, partitioner, version);
    return mt;
}
 
Example 26
Project: ACaZoo   File: NetworkTopologyStrategyTest.java   View source code 6 votes vote down vote up
@Test
public void testProperties() throws IOException, ConfigurationException
{
    IEndpointSnitch snitch = new PropertyFileSnitch();
    DatabaseDescriptor.setEndpointSnitch(snitch);
    TokenMetadata metadata = new TokenMetadata();
    createDummyTokens(metadata, true);

    Map<String, String> configOptions = new HashMap<String, String>();
    configOptions.put("DC1", "3");
    configOptions.put("DC2", "2");
    configOptions.put("DC3", "1");

    // Set the localhost to the tokenmetadata. Embedded cassandra way?
    NetworkTopologyStrategy strategy = new NetworkTopologyStrategy(keyspaceName, metadata, snitch, configOptions);
    assert strategy.getReplicationFactor("DC1") == 3;
    assert strategy.getReplicationFactor("DC2") == 2;
    assert strategy.getReplicationFactor("DC3") == 1;
    // Query for the natural hosts
    ArrayList<InetAddress> endpoints = strategy.getNaturalEndpoints(new StringToken("123"));
    assert 6 == endpoints.size();
    assert 6 == new HashSet<InetAddress>(endpoints).size(); // ensure uniqueness
}
 
Example 27
Project: cassandra-kmean   File: StorageService.java   View source code 6 votes vote down vote up
public synchronized void initClient(int ringDelay) throws ConfigurationException
{
    if (initialized)
    {
        if (!isClientMode)
            throw new UnsupportedOperationException("StorageService does not support switching modes.");
        return;
    }
    initialized = true;
    isClientMode = true;
    logger.info("Starting up client gossip");
    setMode(Mode.CLIENT, false);
    Gossiper.instance.register(this);
    Gossiper.instance.start((int) (System.currentTimeMillis() / 1000)); // needed for node-ring gathering.
    Gossiper.instance.addLocalApplicationState(ApplicationState.NET_VERSION, valueFactory.networkVersion());

    if (!MessagingService.instance().isListening())
        MessagingService.instance().listen(FBUtilities.getLocalAddress());
    Uninterruptibles.sleepUninterruptibly(ringDelay, TimeUnit.MILLISECONDS);
}
 
Example 28
Project: ACaZoo   File: ScrubTest.java   View source code 6 votes vote down vote up
@Test
public void testScrubMultiRow() throws IOException, ExecutionException, InterruptedException, ConfigurationException
{
    CompactionManager.instance.disableAutoCompaction();
    Keyspace keyspace = Keyspace.open(KEYSPACE);
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);

    List<Row> rows;

    // insert data and verify we get it back w/ range query
    fillCF(cfs, 10);
    rows = cfs.getRangeSlice(Util.range("", ""), null, new IdentityQueryFilter(), 1000);
    assertEquals(10, rows.size());

    CompactionManager.instance.performScrub(cfs);

    // check data is still there
    rows = cfs.getRangeSlice(Util.range("", ""), null, new IdentityQueryFilter(), 1000);
    assertEquals(10, rows.size());
}
 
Example 29
Project: sstable-adaptor   File: TableAttributes.java   View source code 5 votes vote down vote up
public UUID getId() throws ConfigurationException
{
    String id = getSimple(KW_ID);
    try
    {
        return id != null ? UUID.fromString(id) : null;
    }
    catch (IllegalArgumentException e)
    {
        throw new ConfigurationException("Invalid table id", e);
    }
}
 
Example 30
Project: sstable-adaptor   File: FBUtilities.java   View source code 5 votes vote down vote up
public static String resourceToFile(String filename) throws ConfigurationException
{
    ClassLoader loader = FBUtilities.class.getClassLoader();
    URL scpurl = loader.getResource(filename);
    if (scpurl == null)
        throw new ConfigurationException("unable to locate " + filename);

    return new File(scpurl.getFile()).getAbsolutePath();
}
 
Example 31
Project: sstable-adaptor   File: FBUtilities.java   View source code 5 votes vote down vote up
@VisibleForTesting
static IPartitioner newPartitioner(String partitionerClassName, Optional<AbstractType<?>> comparator) throws ConfigurationException
{
    if (!partitionerClassName.contains("."))
        partitionerClassName = "org.apache.cassandra.dht." + partitionerClassName;

    if (partitionerClassName.equals("org.apache.cassandra.dht.LocalPartitioner"))
    {
        assert comparator.isPresent() : "Expected a comparator for local partitioner";
        return new LocalPartitioner(comparator.get());
    }
    return FBUtilities.instanceOrConstruct(partitionerClassName, "partitioner");
}
 
Example 32
Project: sstable-adaptor   File: FBUtilities.java   View source code 5 votes vote down vote up
/**
 * @return The Class for the given name.
 * @param classname Fully qualified classname.
 * @param readable Descriptive noun for the role the class plays.
 * @throws ConfigurationException If the class cannot be found.
 */
public static <T> Class<T> classForName(String classname, String readable) throws ConfigurationException
{
    try
    {
        return (Class<T>)Class.forName(classname);
    }
    catch (ClassNotFoundException | NoClassDefFoundError e)
    {
        throw new ConfigurationException(String.format("Unable to find %s class '%s'", readable, classname), e);
    }
}
 
Example 33
Project: sstable-adaptor   File: FBUtilities.java   View source code 5 votes vote down vote up
/**
 * Constructs an instance of the given class, which must have a no-arg or default constructor.
 * @param classname Fully qualified classname.
 * @param readable Descriptive noun for the role the class plays.
 * @throws ConfigurationException If the class cannot be found.
 */
public static <T> T instanceOrConstruct(String classname, String readable) throws ConfigurationException
{
    Class<T> cls = FBUtilities.classForName(classname, readable);
    try
    {
        Field instance = cls.getField("instance");
        return cls.cast(instance.get(null));
    }
    catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e)
    {
        // Could not get instance field. Try instantiating.
        return construct(cls, classname, readable);
    }
}
 
Example 34
Project: sstable-adaptor   File: Murmur3Partitioner.java   View source code 5 votes vote down vote up
public void validate(String token) throws ConfigurationException
{
    try
    {
        fromString(token);
    }
    catch (NumberFormatException e)
    {
        throw new ConfigurationException(e.getMessage());
    }
}
 
Example 35
Project: sstable-adaptor   File: RandomPartitioner.java   View source code 5 votes vote down vote up
public void validate(String token) throws ConfigurationException
{
    try
    {
        if(!isValidToken(new BigInteger(token)))
            throw new ConfigurationException("Token must be >= 0 and <= 2**127");
    }
    catch (NumberFormatException e)
    {
        throw new ConfigurationException(e.getMessage());
    }
}
 
Example 36
Project: sstable-adaptor   File: ColumnFamilyStore.java   View source code 5 votes vote down vote up
public void setCompressionParameters(Map<String,String> opts)
{
    try
    {
        metadata.compression(CompressionParams.fromMap(opts));
        metadata.params.compression.validate();
    }
    catch (ConfigurationException e)
    {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 37
Project: sstable-adaptor   File: DynamicCompositeType.java   View source code 5 votes vote down vote up
DynamicParsedComparator(String part)
{
    String[] splits = part.split("@");
    if (splits.length != 2)
        throw new IllegalArgumentException("Invalid component representation: " + part);

    comparatorName = splits[0];
    remainingPart = splits[1];

    try
    {
        AbstractType<?> t = null;
        if (comparatorName.length() == 1)
        {
            // try for an alias
            // Note: the char to byte cast is theorically bogus for unicode character. I take full
            // responsibility if someone get hit by this (without making it on purpose)
            t = aliases.get((byte)comparatorName.charAt(0));
        }
        isAlias = t != null;
        if (!isAlias)
        {
            t = TypeParser.parse(comparatorName);
        }
        type = t;
    }
    catch (SyntaxException | ConfigurationException e)
    {
        throw new IllegalArgumentException(e);
    }
}
 
Example 38
Project: sstable-adaptor   File: FrozenType.java   View source code 5 votes vote down vote up
public static AbstractType<?> getInstance(TypeParser parser) throws ConfigurationException, SyntaxException
{
    List<AbstractType<?>> innerTypes = parser.getTypeParameters();
    if (innerTypes.size() != 1)
        throw new SyntaxException("FrozenType() only accepts one parameter");

    AbstractType<?> innerType = innerTypes.get(0);
    return innerType.freeze();
}
 
Example 39
Project: sstable-adaptor   File: SetType.java   View source code 5 votes vote down vote up
public static SetType<?> getInstance(TypeParser parser) throws ConfigurationException, SyntaxException
{
    List<AbstractType<?>> l = parser.getTypeParameters();
    if (l.size() != 1)
        throw new ConfigurationException("SetType takes exactly 1 type parameter");

    return getInstance(l.get(0), true);
}
 
Example 40
Project: sstable-adaptor   File: ListType.java   View source code 5 votes vote down vote up
public static ListType<?> getInstance(TypeParser parser) throws ConfigurationException, SyntaxException
{
    List<AbstractType<?>> l = parser.getTypeParameters();
    if (l.size() != 1)
        throw new ConfigurationException("ListType takes exactly 1 type parameter");

    return getInstance(l.get(0), true);
}