org.apache.cassandra.exceptions.SyntaxException Java Examples

The following examples show how to use org.apache.cassandra.exceptions.SyntaxException. 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: CassSSTableReducer.java    From aegisthus with Apache License 2.0 6 votes vote down vote up
@Override protected void setup(
        Context context)
        throws IOException, InterruptedException {
    super.setup(context);

    maxRowSize = context.getConfiguration().getLong(Aegisthus.Feature.CONF_MAXCOLSIZE, Long.MAX_VALUE);

    String columnType = context.getConfiguration().get(Aegisthus.Feature.CONF_COLUMNTYPE, "BytesType");
    String rowKeyType = context.getConfiguration().get(Aegisthus.Feature.CONF_KEYTYPE, "BytesType");

    try {
        columnComparator = TypeParser.parse(columnType);
        rowKeyComparator = TypeParser.parse(rowKeyType);
    } catch (SyntaxException | ConfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: CassandraUtils.java    From sstable-tools with Apache License 2.0 6 votes vote down vote up
public static Cluster loadTablesFromRemote(String host, int port, String cfidOverrides) throws IOException {
    Map<String, UUID> cfs = parseOverrides(cfidOverrides);
    Cluster.Builder builder = Cluster.builder().addContactPoints(host).withPort(port);
    Cluster cluster = builder.build();
    Metadata metadata = cluster.getMetadata();
    IPartitioner partitioner = FBUtilities.newPartitioner(metadata.getPartitioner());
    if (DatabaseDescriptor.getPartitioner() == null)
        DatabaseDescriptor.setPartitionerUnsafe(partitioner);
    for (com.datastax.driver.core.KeyspaceMetadata ksm : metadata.getKeyspaces()) {
        if (!ksm.getName().equals("system")) {
            for (TableMetadata tm : ksm.getTables()) {
                String name = ksm.getName()+"."+tm.getName();
                try {
                    CassandraUtils.tableFromCQL(
                            new ByteArrayInputStream(tm.asCQLQuery().getBytes()),
                            cfs.get(name) != null ? cfs.get(name) : tm.getId());
                } catch(SyntaxException e) {
                    // ignore tables that we cant parse (probably dse)
                    logger.debug("Ignoring table " + name + " due to syntax exception " + e.getMessage());
                }
            }
        }
    }
    return cluster;
}
 
Example #3
Source File: PropertyDefinitions.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public static Integer toInt(String key, String value, Integer defaultValue) throws SyntaxException
{
    if (value == null)
    {
        return defaultValue;
    }
    else
    {
        try
        {
            return Integer.valueOf(value);
        }
        catch (NumberFormatException e)
        {
            throw new SyntaxException(String.format("Invalid integer value %s for '%s'", value, key));
        }
    }
}
 
Example #4
Source File: PropertyDefinitions.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public Double getDouble(String key, Double defaultValue) throws SyntaxException
{
    String value = getSimple(key);
    if (value == null)
    {
        return defaultValue;
    }
    else
    {
        try
        {
            return Double.valueOf(value);
        }
        catch (NumberFormatException e)
        {
            throw new SyntaxException(String.format("Invalid double value %s for '%s'", value, key));
        }
    }
}
 
Example #5
Source File: MapType.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static MapType<?, ?> getInstance(TypeParser parser) throws ConfigurationException, SyntaxException
{
    List<AbstractType<?>> l = parser.getTypeParameters();
    if (l.size() != 2)
        throw new ConfigurationException("MapType takes exactly 2 type parameters");

    return getInstance(l.get(0), l.get(1), true);
}
 
Example #6
Source File: CFPropDefs.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public void applyToCFMetadata(CFMetaData cfm) throws ConfigurationException, SyntaxException
{
    if (hasProperty(KW_COMMENT))
        cfm.comment(getString(KW_COMMENT, ""));

    cfm.readRepairChance(getDouble(KW_READREPAIRCHANCE, cfm.getReadRepairChance()));
    cfm.dcLocalReadRepairChance(getDouble(KW_DCLOCALREADREPAIRCHANCE, cfm.getDcLocalReadRepair()));
    cfm.gcGraceSeconds(getInt(KW_GCGRACESECONDS, cfm.getGcGraceSeconds()));
    int minCompactionThreshold = toInt(KW_MINCOMPACTIONTHRESHOLD, getCompactionOptions().get(KW_MINCOMPACTIONTHRESHOLD), cfm.getMinCompactionThreshold());
    int maxCompactionThreshold = toInt(KW_MAXCOMPACTIONTHRESHOLD, getCompactionOptions().get(KW_MAXCOMPACTIONTHRESHOLD), cfm.getMaxCompactionThreshold());
    if (minCompactionThreshold <= 0 || maxCompactionThreshold <= 0)
        throw new ConfigurationException("Disabling compaction by setting compaction thresholds to 0 has been deprecated, set the compaction option 'enabled' to false instead.");
    cfm.minCompactionThreshold(minCompactionThreshold);
    cfm.maxCompactionThreshold(maxCompactionThreshold);
    cfm.defaultTimeToLive(getInt(KW_DEFAULT_TIME_TO_LIVE, cfm.getDefaultTimeToLive()));
    cfm.speculativeRetry(CFMetaData.SpeculativeRetry.fromString(getString(KW_SPECULATIVE_RETRY, cfm.getSpeculativeRetry().toString())));
    cfm.memtableFlushPeriod(getInt(KW_MEMTABLE_FLUSH_PERIOD, cfm.getMemtableFlushPeriod()));
    cfm.minIndexInterval(getInt(KW_MIN_INDEX_INTERVAL, cfm.getMinIndexInterval()));
    cfm.maxIndexInterval(getInt(KW_MAX_INDEX_INTERVAL, cfm.getMaxIndexInterval()));

    if (compactionStrategyClass != null)
    {
        cfm.compactionStrategyClass(compactionStrategyClass);
        cfm.compactionStrategyOptions(new HashMap<>(getCompactionOptions()));
    }

    cfm.bloomFilterFpChance(getDouble(KW_BF_FP_CHANCE, cfm.getBloomFilterFpChance()));

    if (!getCompressionOptions().isEmpty())
        cfm.compressionParameters(CompressionParameters.create(getCompressionOptions()));
    CachingOptions cachingOptions = getCachingOptions();
    if (cachingOptions != null)
        cfm.caching(cachingOptions);
}
 
Example #7
Source File: CqlRecordWriter.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private AbstractType<?> parseType(String type) throws ConfigurationException
{
    try
    {
        // always treat counters like longs, specifically CCT.serialize is not what we need
        if (type != null && type.equals("org.apache.cassandra.db.marshal.CounterColumnType"))
            return LongType.instance;
        return TypeParser.parse(type);
    }
    catch (SyntaxException e)
    {
        throw new ConfigurationException(e.getMessage(), e);
    }
}
 
Example #8
Source File: FrozenType.java    From stratio-cassandra with Apache License 2.0 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 #9
Source File: AbstractType.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static AbstractType<?> parseDefaultParameters(AbstractType<?> baseType, TypeParser parser) throws SyntaxException
{
    Map<String, String> parameters = parser.getKeyValueParameters();
    String reversed = parameters.get("reversed");
    if (reversed != null && (reversed.isEmpty() || reversed.equals("true")))
    {
        return ReversedType.getInstance(baseType);
    }
    else
    {
        return baseType;
    }
}
 
Example #10
Source File: SetType.java    From stratio-cassandra with Apache License 2.0 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 #11
Source File: ListType.java    From stratio-cassandra with Apache License 2.0 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);
}
 
Example #12
Source File: CFPropDefs.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private void validateMinimumInt(String field, int minimumValue, int defaultValue) throws SyntaxException, ConfigurationException
{
    Integer val = getInt(field, null);
    if (val != null && val < minimumValue)
        throw new ConfigurationException(String.format("%s cannot be smaller than %s, (default %s)",
                                                        field, minimumValue, defaultValue));

}
 
Example #13
Source File: TupleType.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static TupleType getInstance(TypeParser parser) throws ConfigurationException, SyntaxException
{
    List<AbstractType<?>> types = parser.getTypeParameters();
    for (int i = 0; i < types.size(); i++)
        types.set(i, types.get(i).freeze());
    return new TupleType(types);
}
 
Example #14
Source File: UserType.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static UserType getInstance(TypeParser parser) throws ConfigurationException, SyntaxException
{
    Pair<Pair<String, ByteBuffer>, List<Pair<ByteBuffer, AbstractType>>> params = parser.getUserTypeParameters();
    String keyspace = params.left.left;
    ByteBuffer name = params.left.right;
    List<ByteBuffer> columnNames = new ArrayList<>(params.right.size());
    List<AbstractType<?>> columnTypes = new ArrayList<>(params.right.size());
    for (Pair<ByteBuffer, AbstractType> p : params.right)
    {
        columnNames.add(p.left);
        columnTypes.add(p.right.freeze());
    }
    return new UserType(keyspace, name, columnNames, columnTypes);
}
 
Example #15
Source File: ReversedType.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static <T> ReversedType<T> getInstance(TypeParser parser) throws ConfigurationException, SyntaxException
{
    List<AbstractType<?>> types = parser.getTypeParameters();
    if (types.size() != 1)
        throw new ConfigurationException("ReversedType takes exactly one argument, " + types.size() + " given");
    return getInstance((AbstractType<T>) types.get(0));
}
 
Example #16
Source File: FrozenCollectionsTest.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private void assertInvalidCreateWithMessage(String createTableStatement, String errorMessage) throws Throwable
{
     try
    {
        createTableMayThrow(createTableStatement);
        Assert.fail("Expected CREATE TABLE statement to error: " + createTableStatement);
    }
    catch (InvalidRequestException | ConfigurationException | SyntaxException ex)
    {
        Assert.assertTrue("Expected error message to contain '" + errorMessage + "', but got '" + ex.getMessage() + "'",
                ex.getMessage().contains(errorMessage));
    }
}
 
Example #17
Source File: TypeParserTest.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse() throws ConfigurationException, SyntaxException
{
    AbstractType type;

    type = TypeParser.parse(null);
    assert type == BytesType.instance;

    type = TypeParser.parse("");
    assert type == BytesType.instance;

    type = TypeParser.parse("    ");
    assert type == BytesType.instance;

    type = TypeParser.parse("LongType");
    assert type == LongType.instance;

    type = TypeParser.parse("  LongType   ");
    assert type == LongType.instance;

    type = TypeParser.parse("LongType()");
    assert type == LongType.instance;

    type = TypeParser.parse("LongType(reversed=false)");
    assert type == LongType.instance;

    type = TypeParser.parse("LongType(reversed=true)");
    assert type == ReversedType.getInstance(LongType.instance);
    assert ((ReversedType)type).baseType == LongType.instance;

    type = TypeParser.parse("LongType(reversed)");
    assert type == ReversedType.getInstance(LongType.instance);
    assert ((ReversedType)type).baseType == LongType.instance;
}
 
Example #18
Source File: JsonOutputFormat.java    From aegisthus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private AbstractType<ByteBuffer> getConverter(Configuration conf, String key) {
    String converterType = conf.get(key);
    if (Strings.isNullOrEmpty(key)) {
        return BytesType.instance;
    }

    try {
        return (AbstractType<ByteBuffer>) TypeParser.parse(converterType);
    } catch (SyntaxException | ConfigurationException e) {
        throw Throwables.propagate(e);
    }
}
 
Example #19
Source File: AegisthusKeySortingComparator.java    From aegisthus with Apache License 2.0 5 votes vote down vote up
@Override
public void setConf(Configuration conf) {
    this.conf = conf;
    String columnType = conf.get(Aegisthus.Feature.CONF_COLUMNTYPE, "BytesType");
    legacyColumnNameFormatting = conf.getBoolean(Aegisthus.Feature.CONF_LEGACY_COLUMN_NAME_FORMATTING, false);
    sortColumnsByName = conf.getBoolean(Aegisthus.Feature.CONF_SORT_COLUMNS_BY_NAME, false);
    try {
        //noinspection unchecked
        columnNameConverter = (AbstractType<ByteBuffer>) TypeParser.parse(columnType);
    } catch (SyntaxException | ConfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: CFPropDefs.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public CachingOptions getCachingOptions() throws SyntaxException, ConfigurationException
{
    CachingOptions options = null;
    Object val = properties.get(KW_CACHING);
    if (val == null)
        return null;
    else if (val instanceof Map)
        options = CachingOptions.fromMap(getMap(KW_CACHING));
    else if (val instanceof String) // legacy syntax
    {
        options = CachingOptions.fromString(getSimple(KW_CACHING));
        logger.warn("Setting caching options with deprecated syntax.");
    }
    return options;
}
 
Example #21
Source File: Cqlsh.java    From sstable-tools with Apache License 2.0 5 votes vote down vote up
public void doSchema(String command) throws Exception {
    String path = command.substring(6).trim().replaceAll("\"", "");

    if (path.equalsIgnoreCase("off")) {
        System.out.println(DISABLING_SCHEMA);
        CassandraUtils.cqlOverride = null;
    } else if (Strings.isNullOrEmpty(path)) {
        if (!Strings.isNullOrEmpty(CassandraUtils.cqlOverride)) {
            System.out.printf(USER_DEFINED_SCHEMA, CassandraUtils.cqlOverride);
        } else {
            System.out.println(NO_USER_DEFINED_SCHEMA);
        }
    } else {
        File schemaFile = new File(path);
        if (!schemaFile.exists()) {
            System.err.printf(CANNOT_FIND_FILE, schemaFile.getAbsolutePath());
        } else {
            String cql = new String(Files.readAllBytes(schemaFile.toPath()));
            try {
                ParsedStatement statement = QueryProcessor.parseStatement(cql);
                if (statement instanceof CreateTableStatement.RawStatement) {
                    CassandraUtils.cqlOverride = cql;
                    System.out.printf(IMPORTED_SCHEMA, schemaFile.getAbsolutePath());
                } else {
                    System.err.printf(FAILED_TO_IMPORT_SCHEMA, schemaFile.getAbsoluteFile(), "Wrong type of statement, " + statement.getClass());
                }
            } catch (SyntaxException se) {
                System.err.printf(FAILED_TO_IMPORT_SCHEMA, schemaFile.getAbsoluteFile(), se.getMessage());
            }
        }
    }

}
 
Example #22
Source File: QueryProcessor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static ParsedStatement parseStatement(String queryStr) throws SyntaxException
{
    try
    {
        // Lexer and parser
        ErrorCollector errorCollector = new ErrorCollector(queryStr);
        CharStream stream = new ANTLRStringStream(queryStr);
        CqlLexer lexer = new CqlLexer(stream);
        lexer.addErrorListener(errorCollector);

        TokenStream tokenStream = new CommonTokenStream(lexer);
        CqlParser parser = new CqlParser(tokenStream);
        parser.addErrorListener(errorCollector);

        // Parse the query string to a statement instance
        ParsedStatement statement = parser.query();

        // The errorCollector has queue up any errors that the lexer and parser may have encountered
        // along the way, if necessary, we turn the last error into exceptions here.
        errorCollector.throwLastSyntaxError();

        return statement;
    }
    catch (RuntimeException re)
    {
        logger.error(String.format("The statement: [%s] could not be parsed.", queryStr), re);
        throw new SyntaxException(String.format("Failed parsing statement: [%s] reason: %s %s",
                                                queryStr,
                                                re.getClass().getSimpleName(),
                                                re.getMessage()));
    }
    catch (RecognitionException e)
    {
        throw new SyntaxException("Invalid or malformed CQL query string: " + e.getMessage());
    }
}
 
Example #23
Source File: PropertyDefinitions.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public void validate(Set<String> keywords, Set<String> obsolete) throws SyntaxException
{
    for (String name : properties.keySet())
    {
        if (keywords.contains(name))
            continue;

        if (obsolete.contains(name))
            logger.warn("Ignoring obsolete property {}", name);
        else
            throw new SyntaxException(String.format("Unknown property '%s'", name));
    }
}
 
Example #24
Source File: PropertyDefinitions.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
protected String getSimple(String name) throws SyntaxException
{
    Object val = properties.get(name);
    if (val == null)
        return null;
    if (!(val instanceof String))
        throw new SyntaxException(String.format("Invalid value for property '%s'. It should be a string", name));
    return (String)val;
}
 
Example #25
Source File: PropertyDefinitions.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
protected Map<String, String> getMap(String name) throws SyntaxException
{
    Object val = properties.get(name);
    if (val == null)
        return null;
    if (!(val instanceof Map))
        throw new SyntaxException(String.format("Invalid value for property '%s'. It should be a map.", name));
    return (Map<String, String>)val;
}
 
Example #26
Source File: CFPropDefs.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getCompressionOptions() throws SyntaxException
{
    Map<String, String> compressionOptions = getMap(KW_COMPRESSION);
    if (compressionOptions == null)
        return new HashMap<>();
    return compressionOptions;
}
 
Example #27
Source File: CFPropDefs.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getCompactionOptions() throws SyntaxException
{
    Map<String, String> compactionOptions = getMap(KW_COMPACTION);
    if (compactionOptions == null)
        return new HashMap<>();
    return compactionOptions;
}
 
Example #28
Source File: CFPropDefs.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public AbstractType<?> getComparator() throws ConfigurationException, SyntaxException
{
    return TypeParser.parse((comparators.get(getPropertyString(KW_COMPARATOR, "text")) != null)
                              ? comparators.get(getPropertyString(KW_COMPARATOR, "text"))
                              : getPropertyString(KW_COMPARATOR, "text"));
}
 
Example #29
Source File: CFPropDefs.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public Integer getDefaultTimeToLive() throws SyntaxException
{
    return getInt(KW_DEFAULT_TIME_TO_LIVE, 0);
}
 
Example #30
Source File: ErrorCollector.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
/**
 * Throws the last syntax error found by the lexer or the parser if it exists.
 *
 * @throws SyntaxException the syntax error.
 */
public void throwLastSyntaxError() throws SyntaxException
{
    if (!errorMsgs.isEmpty())
        throw new SyntaxException(errorMsgs.getLast());
}