Package org.apache.cassandra.thrift

Examples of org.apache.cassandra.thrift.InvalidRequestException


                   .caching(CFMetaData.Caching.fromString(getPropertyString(CFPropDefs.KW_CACHING, CFMetaData.DEFAULT_CACHING_STRATEGY.toString())))
                   .bloomFilterFpChance(getPropertyDouble(CFPropDefs.KW_BF_FP_CHANCE, CFMetaData.DEFAULT_BF_FP_CHANCE));
        }
        catch (ConfigurationException e)
        {
            throw new InvalidRequestException(e.toString());
        }
        return newCFMD;
    }
View Full Code Here


            properties.applyToCFMetadata(newCFMD);
        }
        catch (ConfigurationException e)
        {
            throw new InvalidRequestException(e.getMessage());
        }
        return newCFMD;
    }
View Full Code Here

        {
            compactionStrategyClass = CFMetaData.createCompactionStrategy(compStrategy);
        }
        catch (ConfigurationException e)
        {
            throw new InvalidRequestException(e.getMessage());
        }

        // we need to remove parent:key = value pairs from the main properties
        Set<String> propsToRemove = new HashSet<String>();

        // check if we have compaction/compression options
        for (String property : properties.keySet())
        {
            if (!property.contains(":"))
                continue;

            String key = property.split(":")[1];
            String val = properties.get(property);

            if (property.startsWith(COMPACTION_OPTIONS_PREFIX))
            {
                compactionStrategyOptions.put(key, val);
                propsToRemove.add(property);
            }

            if (property.startsWith(COMPRESSION_PARAMETERS_PREFIX))
            {
                compressionParameters.put(key, val);
                propsToRemove.add(property);
            }
        }

        for (String property : propsToRemove)
            properties.remove(property);
        // Catch the case where someone passed a kwarg that is not recognized.
        for (String bogus : Sets.difference(properties.keySet(), allowedKeywords))
            throw new InvalidRequestException(bogus + " is not a valid keyword argument for CREATE COLUMNFAMILY");
        for (String obsolete : Sets.intersection(properties.keySet(), obsoleteKeywords))
            logger.warn("Ignoring obsolete property {}", obsolete);

        // Validate min/max compaction thresholds
        Integer minCompaction = getPropertyInt(KW_MINCOMPACTIONTHRESHOLD, null);
        Integer maxCompaction = getPropertyInt(KW_MAXCOMPACTIONTHRESHOLD, null);

        if ((minCompaction != null) && (maxCompaction != null))     // Both min and max are set
        {
            if ((minCompaction > maxCompaction) && (maxCompaction != 0))
                throw new InvalidRequestException(String.format("%s cannot be larger than %s",
                        KW_MINCOMPACTIONTHRESHOLD,
                        KW_MAXCOMPACTIONTHRESHOLD));
        }
        else if (minCompaction != null)     // Only the min threshold is set
        {
            if (minCompaction > CFMetaData.DEFAULT_MAX_COMPACTION_THRESHOLD)
                throw new InvalidRequestException(String.format("%s cannot be larger than %s, (default %s)",
                        KW_MINCOMPACTIONTHRESHOLD,
                        KW_MAXCOMPACTIONTHRESHOLD,
                        CFMetaData.DEFAULT_MAX_COMPACTION_THRESHOLD));
        }
        else if (maxCompaction != null)     // Only the max threshold is set
        {
            if ((maxCompaction < CFMetaData.DEFAULT_MIN_COMPACTION_THRESHOLD) && (maxCompaction != 0))
                throw new InvalidRequestException(String.format("%s cannot be smaller than %s, (default %s)",
                        KW_MAXCOMPACTIONTHRESHOLD,
                        KW_MINCOMPACTIONTHRESHOLD,
                        CFMetaData.DEFAULT_MIN_COMPACTION_THRESHOLD));
        }
    }
View Full Code Here

            {
                result = Double.parseDouble(value);
            }
            catch (NumberFormatException e)
            {
                throw new InvalidRequestException(String.format("%s not valid for \"%s\"", value, key));
            }
        }
        return result;
    }
View Full Code Here

            {
                result = Integer.parseInt(value);
            }
            catch (NumberFormatException e)
            {
                throw new InvalidRequestException(String.format("%s not valid for \"%s\"", value, key));
            }
        }
        return result;
    }
View Full Code Here

        {
            try
            {
                // Column family name
                if (!columnFamily().matches("\\w+"))
                    throw new InvalidRequestException(String.format("\"%s\" is not a valid column family name (must be alphanumeric character only: [0-9A-Za-z]+)", columnFamily()));
                if (columnFamily().length() > Schema.NAME_LENGTH)
                    throw new InvalidRequestException(String.format("Column family names shouldn't be more than %s characters long (got \"%s\")", Schema.NAME_LENGTH, columnFamily()));

                for (Multiset.Entry<ColumnIdentifier> entry : definedNames.entrySet())
                    if (entry.getCount() > 1)
                        throw new InvalidRequestException(String.format("Multiple definition of identifier %s", entry.getElement()));

                properties.validate();

                CreateColumnFamilyStatement stmt = new CreateColumnFamilyStatement(cfName, properties);
                stmt.setBoundTerms(getBoundsTerms());
                for (Map.Entry<ColumnIdentifier, String> entry : definitions.entrySet())
                {
                    AbstractType<?> type = CFPropDefs.parseType(entry.getValue());
                    stmt.columns.put(entry.getKey(), type); // we'll remove what is not a column below
                }

                // Ensure that exactly one key has been specified.
                if (keyAliases.size() == 0)
                    throw new InvalidRequestException("You must specify a PRIMARY KEY");
                else if (keyAliases.size() > 1)
                    throw new InvalidRequestException("You may only specify one PRIMARY KEY");

                stmt.keyAlias = keyAliases.get(0).key;
                stmt.keyValidator = getTypeAndRemove(stmt.columns, keyAliases.get(0));
                if (stmt.keyValidator instanceof CounterColumnType)
                    throw new InvalidRequestException(String.format("counter type is not supported for PRIMARY KEY part %s", stmt.keyAlias));

                // Handle column aliases
                if (columnAliases != null && !columnAliases.isEmpty())
                {
                    // If we use compact storage and have only one alias, it is a
                    // standard "dynamic" CF, otherwise it's a composite
                    if (useCompactStorage && columnAliases.size() == 1)
                    {
                        stmt.columnAliases.add(columnAliases.get(0).key);
                        stmt.comparator = getTypeAndRemove(stmt.columns, columnAliases.get(0));
                        if (stmt.comparator instanceof CounterColumnType)
                            throw new InvalidRequestException(String.format("counter type is not supported for PRIMARY KEY part %s", stmt.columnAliases.get(0)));
                    }
                    else
                    {
                        List<AbstractType<?>> types = new ArrayList<AbstractType<?>>(columnAliases.size() + 1);
                        for (ColumnIdentifier t : columnAliases)
                        {
                            stmt.columnAliases.add(t.key);

                            AbstractType<?> type = getTypeAndRemove(stmt.columns, t);
                            if (type instanceof CounterColumnType)
                                throw new InvalidRequestException(String.format("counter type is not supported for PRIMARY KEY part %s", t.key));
                            types.add(type);
                        }
                        // For sparse, we must add the last UTF8 component
                        if (!useCompactStorage)
                            types.add(CFDefinition.definitionType);

                        if (types.isEmpty())
                            throw new IllegalStateException("Nonsensical empty parameter list for CompositeType");
                        stmt.comparator = CompositeType.getInstance(types);
                    }
                }
                else
                {
                    stmt.comparator = CFDefinition.definitionType;
                }

                if (useCompactStorage)
                {
                    // There should at least have been one column alias
                    if (stmt.columnAliases.isEmpty())
                        throw new InvalidRequestException("COMPACT STORAGE requires at least one column part of the clustering key, none found");
                    // There should be only one column definition remaining, which gives us the default validator.
                    if (stmt.columns.isEmpty())
                        throw new InvalidRequestException("COMPACT STORAGE requires one definition not part of the PRIMARY KEY, none found");
                    if (stmt.columns.size() > 1)
                        throw new InvalidRequestException(String.format("COMPACT STORAGE allows only one column not part of the PRIMARY KEY (got: %s)", StringUtils.join(stmt.columns.keySet(), ", ")));

                    Map.Entry<ColumnIdentifier, AbstractType> lastEntry = stmt.columns.entrySet().iterator().next();
                    stmt.defaultValidator = lastEntry.getValue();
                    stmt.valueAlias = lastEntry.getKey().key;
                    stmt.columns.remove(lastEntry.getKey());
                }
                else
                {
                    if (stmt.columns.isEmpty())
                        throw new InvalidRequestException("No definition found that is not part of the PRIMARY KEY");

                    // There is no way to insert/access a column that is not defined for non-compact
                    // storage, so the actual validator don't matter much (except that we want to recognize counter CF as limitation apply to them).
                    stmt.defaultValidator = (stmt.columns.values().iterator().next() instanceof CounterColumnType) ? CounterColumnType.instance : CFDefinition.definitionType;
                }

                return new ParsedStatement.Prepared(stmt);
            }
            catch (ConfigurationException e)
            {
                throw new InvalidRequestException(e.getMessage());
            }
        }
View Full Code Here

        private AbstractType<?> getTypeAndRemove(Map<ColumnIdentifier, AbstractType> columns, ColumnIdentifier t) throws InvalidRequestException, ConfigurationException
        {
            AbstractType type = columns.get(t);
            if (type == null)
                throw new InvalidRequestException(String.format("Unkown definition %s referenced in PRIMARY KEY", t));
            columns.remove(t);
            Boolean isReversed = definedOrdering.get(t);
            return isReversed != null && isReversed ? ReversedType.getInstance(type) : type;
        }
View Full Code Here

        {
            CFMetaData cfm = ThriftValidation.validateColumnFamily(keyspace(), columnFamily());
            ThriftValidation.validateConsistencyLevel(keyspace(), parameters.consistencyLevel, RequestType.READ);

            if (parameters.limit <= 0)
                throw new InvalidRequestException("LIMIT must be strictly positive");

            CFDefinition cfDef = cfm.getCfDef();
            SelectStatement stmt = new SelectStatement(cfDef, getBoundsTerms(), parameters);
            CFDefinition.Name[] names = new CFDefinition.Name[getBoundsTerms()];

            // Select clause
            if (parameters.isCount)
            {
                if (!selectClause.isEmpty())
                    throw new InvalidRequestException("Only COUNT(*) and COUNT(1) operations are currently supported.");
            }
            else
            {
                for (Selector t : selectClause)
                {
                    CFDefinition.Name name = cfDef.get(t.id());
                    if (name == null)
                        throw new InvalidRequestException(String.format("Undefined name %s in selection clause", t.id()));
                    if (t.hasFunction() && name.kind != CFDefinition.Name.Kind.COLUMN_METADATA && name.kind != CFDefinition.Name.Kind.VALUE_ALIAS)
                        throw new InvalidRequestException(String.format("Cannot use function %s on PRIMARY KEY part %s", t.function(), name));

                    stmt.selectedNames.add(Pair.create(name, t));
                }
            }

            /*
             * WHERE clause. For a given entity, rules are:
             *   - EQ relation conflicts with anything else (including a 2nd EQ)
             *   - Can't have more than one LT(E) relation (resp. GT(E) relation)
             *   - IN relation are restricted to row keys (for now) and conflics with anything else
             *     (we could allow two IN for the same entity but that doesn't seem very useful)
             *   - The value_alias cannot be restricted in any way (we don't support wide rows with indexed value in CQL so far)
             */
            for (Relation rel : whereClause)
            {
                CFDefinition.Name name = cfDef.get(rel.getEntity());
                if (name == null)
                    throw new InvalidRequestException(String.format("Undefined name %s in where clause ('%s')", rel.getEntity(), rel));

                if (rel.operator() == Relation.Type.IN)
                {
                    for (Term value : rel.getInValues())
                        if (value.isBindMarker())
                            names[value.bindIndex] = name;
                }
                else
                {
                    Term value = rel.getValue();
                    if (value.isBindMarker())
                        names[value.bindIndex] = name;
                }

                switch (name.kind)
                {
                    case KEY_ALIAS:
                        if (rel.operator() != Relation.Type.EQ && rel.operator() != Relation.Type.IN && !rel.onToken && !StorageService.getPartitioner().preservesOrder())
                            throw new InvalidRequestException("Only EQ and IN relation are supported on first component of the PRIMARY KEY for RandomPartitioner (unless you use the token() function)");
                        stmt.keyRestriction = updateRestriction(name, stmt.keyRestriction, rel);
                        break;
                    case COLUMN_ALIAS:
                        stmt.columnRestrictions[name.position] = updateRestriction(name, stmt.columnRestrictions[name.position], rel);
                        break;
                    case VALUE_ALIAS:
                        throw new InvalidRequestException(String.format("Restricting the value of a compact CF (%s) is not supported", name.name));
                    case COLUMN_METADATA:
                        stmt.metadataRestrictions.put(name, updateRestriction(name, stmt.metadataRestrictions.get(name), rel));
                        break;
                }
            }

            /*
             * At this point, the select statement if fully constructed, but we still have a few things to validate
             */

            // If a component of the PRIMARY KEY is restricted by a non-EQ relation, all preceding
            // components must have a EQ, and all following must have no restriction
            boolean shouldBeDone = false;
            CFDefinition.Name previous = null;
            Iterator<CFDefinition.Name> iter = cfDef.columns.values().iterator();
            for (int i = 0; i < stmt.columnRestrictions.length; i++)
            {
                CFDefinition.Name cname = iter.next();
                Restriction restriction = stmt.columnRestrictions[i];
                if (restriction == null)
                {
                    shouldBeDone = true;
                }
                else if (shouldBeDone)
                {
                    throw new InvalidRequestException(String.format("PRIMARY KEY part %s cannot be restricted (preceding part %s is either not restricted or by a non-EQ relation)", cname, previous));
                }
                else if (!restriction.isEquality())
                {
                    shouldBeDone = true;
                    // For non-composite slices, we don't support internally the difference between exclusive and
                    // inclusive bounds, so we deal with it manually.
                    if (!cfDef.isComposite && (!restriction.isInclusive(Bound.START) || !restriction.isInclusive(Bound.END)))
                        stmt.sliceRestriction = restriction;
                }
                // We only support IN for the last name so far
                else if (restriction.eqValues.size() > 1 && i != stmt.columnRestrictions.length - 1)
                {
                    throw new InvalidRequestException(String.format("PRIMARY KEY part %s cannot be restricted by IN relation (only the first and last parts can)", cname));
                }

                previous = cname;
            }

            // Deal with indexed columns
            if (!stmt.metadataRestrictions.isEmpty())
            {
                boolean hasEq = false;
                Set<ByteBuffer> indexed = Table.open(keyspace()).getColumnFamilyStore(columnFamily()).indexManager.getIndexedColumns();

                for (Map.Entry<CFDefinition.Name, Restriction> entry : stmt.metadataRestrictions.entrySet())
                {
                    if (entry.getValue().isEquality() && indexed.contains(entry.getKey().name.key))
                    {
                        hasEq = true;
                        break;
                    }
                }
                if (!hasEq)
                    throw new InvalidRequestException("No indexed columns present in by-columns clause with Equal operator");

                // If we have indexed columns and the key = X clause, we will do a range query, but if it's a IN relation, we don't know how to handle it.
                if (stmt.keyRestriction != null && stmt.keyRestriction.isEquality() && stmt.keyRestriction.eqValues.size() > 1)
                    throw new InvalidRequestException("Select on indexed columns and with IN clause for the PRIMARY KEY are not supported");
            }

            if (!stmt.parameters.orderings.isEmpty())
            {
                Boolean[] reversedMap = new Boolean[cfDef.columns.size()];
                int i = 0;
                for (Map.Entry<ColumnIdentifier, Boolean> entry : stmt.parameters.orderings.entrySet())
                {
                    ColumnIdentifier column = entry.getKey();
                    boolean reversed = entry.getValue();

                    CFDefinition.Name name = cfDef.get(column);
                    if (name == null)
                        throw new InvalidRequestException(String.format("Order by on unknown column %s", column));

                    if (name.kind != CFDefinition.Name.Kind.COLUMN_ALIAS)
                        throw new InvalidRequestException(String.format("Order by is currently only supported on the clustered columns of the PRIMARY KEY, got %s", column));

                    if (i++ != name.position)
                        throw new InvalidRequestException(String.format("Order by currently only support the ordering of columns following their declared order in the PRIMARY KEY"));

                    reversedMap[name.position] = (reversed != isReversedType(name));
                }

                // Check that all boolean in reversedMap, if set, agrees
                Boolean isReversed = null;
                for (Boolean b : reversedMap)
                {
                    // Column on which order is specified can be in any order
                    if (b == null)
                        continue;

                    if (isReversed == null)
                    {
                        isReversed = b;
                        continue;
                    }
                    if (isReversed != b)
                        throw new InvalidRequestException(String.format("Unsupported order by relation"));
                }
                assert isReversed != null;
                stmt.isReversed = isReversed;

                // Only allow ordering if the row key restriction is an equality,
                // since otherwise the order will be primarily on the row key.
                // TODO: we could allow ordering for IN queries, as we can do the
                // sorting post-query easily, but we will have to add it
                if (stmt.keyRestriction == null || !stmt.keyRestriction.isEquality() || stmt.keyRestriction.eqValues.size() != 1)
                    throw new InvalidRequestException("Ordering is only supported if the first part of the PRIMARY KEY is restricted by an Equal");
            }

            // If this is a query on tokens, it's necessary a range query (there can be more than one key per token), so reject IN queries (as we don't know how to do them)
            if (stmt.keyRestriction != null && stmt.keyRestriction.onToken && stmt.keyRestriction.isEquality() && stmt.keyRestriction.eqValues.size() > 1)
                throw new InvalidRequestException("Select using the token() function don't support IN clause");

            return new ParsedStatement.Prepared(stmt, Arrays.<CFDefinition.Name>asList(names));
        }
View Full Code Here

        }

        Restriction updateRestriction(CFDefinition.Name name, Restriction restriction, Relation newRel) throws InvalidRequestException
        {
            if (newRel.onToken && name.kind != CFDefinition.Name.Kind.KEY_ALIAS)
                throw new InvalidRequestException(String.format("The token() function is only supported on the partition key, found on %s", name));

            switch (newRel.operator())
            {
                case EQ:
                    if (restriction != null)
                        throw new InvalidRequestException(String.format("%s cannot be restricted by more than one relation if it includes an Equal", name));
                    restriction = new Restriction(newRel.getValue(), newRel.onToken);
                    break;
                case IN:
                    if (restriction != null)
                        throw new InvalidRequestException(String.format("%s cannot be restricted by more than one reation if it includes a IN", name));
                    restriction = new Restriction(newRel.getInValues());
                    break;
                case GT:
                case GTE:
                case LT:
View Full Code Here

                    inclusive = true;
                    break;
            }

            if (bounds[b.idx] != null)
                throw new InvalidRequestException(String.format("Invalid restrictions found on %s", name));
            bounds[b.idx] = t;
            boundInclusive[b.idx] = inclusive;
        }
View Full Code Here

TOP

Related Classes of org.apache.cassandra.thrift.InvalidRequestException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.