Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *      Copyright (C) 2012 DataStax Inc.
   *
   *   Licensed under the Apache License, Version 2.0 (the "License");
   *   you may not use this file except in compliance with the License.
   *   You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *   Unless required by applicable law or agreed to in writing, software
  *   distributed under the License is distributed on an "AS IS" BASIS,
  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *   See the License for the specific language governing permissions and
  *   limitations under the License.
  */
 package com.datastax.driver.core;
 
 import java.util.*;
 
 
Data types supported by cassandra.
 
 public class DataType {

    
The CQL type name.
 
     public enum Name {
 
         ASCII     (String.class),
         BIGINT    (Long.class),
         BLOB      (ByteBuffer.class),
         BOOLEAN   (Boolean.class),
         COUNTER   (Long.class),
         DECIMAL   (BigDecimal.class),
         DOUBLE    (Double.class),
         FLOAT     (Float.class),
         INET      (InetAddress.class),
         INT       (Integer.class),
         TEXT      (String.class),
         TIMESTAMP (Date.class),
         UUID      (UUID.class),
         VARCHAR   (String.class),
         VARINT    (BigInteger.class),
         TIMEUUID  (UUID.class),
         LIST      (List.class),
         SET       (Set.class),
         MAP       (Map.class),
         CUSTOM    (ByteBuffer.class);
 
         final Class<?> javaType;
 
         private Name(Class<?> javaType) {
             this. = javaType;
         }

        
Returns whether this data type name represent the name of a collection type that is a list, set or map.

Returns:
whether this data type name represent the name of a collection type.
 
         public boolean isCollection() {
             switch (this) {
                 case :
                 case :
                 case :
                     return true;
                 default:
                     return false;
             }
         }

        
Returns the Java Class corresponding to this CQL type name. The correspondence between CQL types and java ones is as follow:
DataType (CQL)Java Class
ASCII String
BIGINT Long
BLOB ByteBuffer
BOOLEAN Boolean
COUNTER Long
CUSTOM ByteBuffer
DECIMAL BigDecimal
DOUBLE Double
FLOAT Float
INET InetAddress
INT Integer
LIST List
MAP Map
SET Set
TEXT String
TIMESTAMP Date
UUID UUID
VARCHAR String
VARINT BigInteger
TIMEUUID UUID

Returns:
the java Class corresponding to this CQL type name.
        public Class<?> asJavaClass() {
            return ;
        }
        @Override
        public String toString() {
            return super.toString().toLowerCase();
        }
    }
    private final DataType.Name name;
    private final List<DataTypetypeArguments;
    private final String customClassName;
    private static final Map<NameDataTypeprimitiveTypeMap = new EnumMap<NameDataType>(Name.class);
    static {
        for (Name name : Name.values()) {
            if (!name.isCollection() && name != .)
                .put(namenew DataType(name, Collections.<DataType>emptyList()));
        }
    }
    private static final Set<DataTypeprimitiveTypeSet = ImmutableSet.copyOf(.values());
    private DataType(DataType.Name nameList<DataTypetypeArguments) {
        this(nametypeArgumentsnull);
    }
    private DataType(DataType.Name nameList<DataTypetypeArgumentsString customClassName) {
        this. = name;
        this. = typeArguments;
        this. = customClassName;
    }

    
Returns the ASCII type.

Returns:
The ASCII type.
    public static DataType ascii() {
        return .get(.);
    }

    
Returns the BIGINT type.

Returns:
The BIGINT type.
    public static DataType bigint() {
        return .get(.);
    }

    
Returns the BLOB type.

Returns:
The BLOB type.
    public static DataType blob() {
        return .get(.);
    }

    
Returns the BOOLEAN type.

Returns:
The BOOLEAN type.
    public static DataType cboolean() {
        return .get(.);
    }

    
Returns the COUNTER type.

Returns:
The COUNTER type.
    public static DataType counter() {
        return .get(.);
    }

    
Returns the DECIMAL type.

Returns:
The DECIMAL type.
    public static DataType decimal() {
        return .get(.);
    }

    
Returns the DOUBLE type.

Returns:
The DOUBLE type.
    public static DataType cdouble() {
        return .get(.);
    }

    
Returns the FLOAT type.

Returns:
The FLOAT type.
    public static DataType cfloat() {
        return .get(.);
    }

    
Returns the INET type.

Returns:
The INET type.
    public static DataType inet() {
        return .get(.);
    }

    
Returns the INT type.

Returns:
The INT type.
    public static DataType cint() {
        return .get(.);
    }

    
Returns the TEXT type.

Returns:
The TEXT type.
    public static DataType text() {
        return .get(.);
    }

    
Returns the TIMESTAMP type.

Returns:
The TIMESTAMP type.
    public static DataType timestamp() {
        return .get(.);
    }

    
Returns the UUID type.

Returns:
The UUID type.
    public static DataType uuid() {
        return .get(.);
    }

    
Returns the VARCHAR type.

Returns:
The VARCHAR type.
    public static DataType varchar() {
        return .get(.);
    }

    
Returns the VARINT type.

Returns:
The VARINT type.
    public static DataType varint() {
        return .get(.);
    }

    
Returns the TIMEUUID type.

Returns:
The TIMEUUID type.
    public static DataType timeuuid() {
        return .get(.);
    }

    
Returns the type of lists of elementType elements.

Parameters:
elementType the type of the list elements.
Returns:
the type of lists of elementType elements.
    public static DataType list(DataType elementType) {
        return new DataType(., ImmutableList.of(elementType));
    }

    
Returns the type of sets of elementType elements.

Parameters:
elementType the type of the set elements.
Returns:
the type of sets of elementType elements.
    public static DataType set(DataType elementType) {
        return new DataType(., ImmutableList.of(elementType));
    }

    
Returns the type of maps of keyType to valueType elements.

Parameters:
keyType the type of the map keys.
valueType the type of the map values.
Returns:
the type of map of keyType to valueType elements.
    public static DataType map(DataType keyTypeDataType valueType) {
        return new DataType(., ImmutableList.of(keyTypevalueType));
    }

    
Returns a Custom type.

A custom type is defined by the name of the class used on the Cassandra side to implement it. Note that the support for custom type by the driver is limited: values of a custom type won't be interpreted by the driver in any way. They will thus be expected (by BoundStatement.setBytesUnsafe(int,java.nio.ByteBuffer) and returned (by Row.getBytesUnsafe(int)) as ByteBuffer.

The use of custom types is rarely useful and is thus not encouraged.

Also note that currently, the class implementing the custom type server side must be present in the driver classpath (this restriction should hopefully lifted at some point).

Parameters:
typeClassName the server-side class name for the type.
Returns:
the custom type for typeClassName.
    public static DataType custom(String typeClassName) {
        if (typeClassName == null)
            throw new NullPointerException();
        return new DataType(., Collections.<DataType>emptyList(), typeClassName);
    }

    
Returns the name of that type.

Returns:
the name of that type.
    public Name getName() {
        return ;
    }

    
Returns the type arguments of this type.

Note that only the collection types (LIST, MAP, SET) have type arguments. For the other types, this will return an empty list.

For the collection types:

  • For lists and sets, this method returns one argument, the type of the elements.
  • For maps, this method returns two arguments, the first one is the type of the map keys, the second one is the type of the map values.
    • Returns:
      an immutable list containing the type arguments of this type.
    public List<DataTypegetTypeArguments() {
        return ;
    }

    
Returns the server-side class name for a custom type.

Returns:
the server-side class name for a custom type or null for any other type.
    public String getCustomTypeClassName() {
        return ;
    }

    
Parses a string value for the type this object represent, returning its Cassandra binary representation.

Parameters:
value the value to parse.
Returns:
the binary representation of value.
Throws:
com.datastax.driver.core.exceptions.InvalidTypeException if value is not a valid string representation for this type. Please note that values for custom types can never be parsed and will always return this exception.
    public ByteBuffer parse(String value) {
        if ( == .)
            throw new InvalidTypeException(String.format("Cannot parse '%s' as value of custom type of class '%s' "
                                                       + "(values for custom type cannot be parse and must be inputed as bytes directly)"value));
        try {
            return Codec.getCodec(this).fromString(value);
        } catch (MarshalException e) {
            throw new InvalidTypeException(String.format("Cannot parse '%s' as a %s value (%s)"valuethise.getMessage()));
        }
    }

    
Returns whether this type is a collection one, i.e. a list, set or map type.

Returns:
whether this type is a collection one.
    public boolean isCollection() {
        return .isCollection();
    }

    
Returns the Java Class corresponding to this type. This is a shortcut for getName().asJavaClass().

Returns:
the java Class corresponding to this type.
See also:
DataType.Name.asJavaClass()
    public Class<?> asJavaClass() {
        return getName().asJavaClass();
    }

    
Returns a set of all the primitive types, where primitive types are defined as the types that don't have type arguments (that is excluding lists, sets, and maps).

Returns:
returns a set of all the primitive types.
    public static Set<DataTypeallPrimitiveTypes() {
        return ;
    }

    
Serialize a value of this type to bytes.

The actual format of the resulting bytes will correspond to the Cassandra encoding for this type.

Parameters:
value the value to serialize.
Returns:
the value serialized, or null if value is null.
Throws:
com.datastax.driver.core.exceptions.InvalidTypeException if value is not a valid object for this DataType.
    public ByteBuffer serialize(Object value) {
        Class<?> providedClass = value.getClass();
        Class<?> expectedClass = asJavaClass();
        if (!expectedClass.isAssignableFrom(providedClass))
            throw new InvalidTypeException(String.format("Invalid value for CQL type %s, expecting %s but %s provided"toString(), expectedClassprovidedClass));
        try {
            return Codec.getCodec(this).decompose(value);
        } catch (ClassCastException e) {
            // With collections, the element type has not been checked, so it can throw
            throw new InvalidTypeException("Invalid type for collection element: " + e.getMessage());
        }
    }

    
Deserialize a value of this type from the provided bytes.

The format of bytes must correspond to the Cassandra encoding for this type.

Parameters:
bytes bytes holding the value to deserialize.
Returns:
the deserialized value (of class this.asJavaClass()). Will return null if either bytes is null or if bytes.remaining() == 0 and this type has no value corresponding to an empty byte buffer (the latter somewhat strange behavior is due to the fact that for historical/technical reason, Cassandra types always accept empty byte buffer as valid value of those type, and so we avoid throwing an exception in that case. It is however highly discouraged to store empty byte buffers for types for which it doesn't make sense, so this implementation can generally be ignored).
Throws:
com.datastax.driver.core.exceptions.InvalidTypeException if bytes is not a valid encoding of an object of this DataType.
    public Object deserialize(ByteBuffer bytes) {
        AbstractType<?> codec = Codec.getCodec(this);
        try {
            codec.validate(bytes);
        } catch (MarshalException e) {
            throw new InvalidTypeException(String.format("Invalid serialized value for type %s (%s)"toString(), e.getMessage()));
        }
        try {
            return codec.compose(bytes);
        } catch (IndexOutOfBoundsException e) {
            // As it happens, types like Int32Type will accept empty byte buffers
            // in their validate method, but their compose method will throw. We
            // should probably fix that Cassandra side, but in the meantime ...
            return null;
        }
    }
    @Override
    public final int hashCode() {
        return Arrays.hashCode(new Object[]{  });
    }
    @Override
    public final boolean equals(Object o) {
        if(!(o instanceof DataType))
            return false;
        DataType d = (DataType)o;
        return  == d.name && .equals(d.typeArguments) && Objects.equal(d.customClassName);
    }
    @Override
    public String toString() {
        switch () {
            case :
            case :
                return String.format("%s<%s>".get(0));
            case :
                return String.format("%s<%s, %s>".get(0), .get(1));
            case :
                return String.format("'%s'");
            default:
                return .toString();
        }
    }
New to GrepCode? Check out our FAQ X