Search in sources :

Example 6 with DriverInternalError

use of com.datastax.driver.core.exceptions.DriverInternalError in project java-driver by datastax.

the class DataTypeCqlNameParser method parse.

/**
 * @param currentUserTypes if this method gets called as part of a refresh that spans multiple user types, this contains the ones
 *                         that have already been refreshed. If the type we are parsing references a user type, we want to pick its
 *                         definition from this map in priority.
 * @param oldUserTypes     this contains all the keyspace's user types as they were before the refresh started. If we can't find a
 *                         definition in {@code currentUserTypes}, we'll check this map as a fallback.
 */
static DataType parse(String toParse, Cluster cluster, String currentKeyspaceName, Map<String, UserType> currentUserTypes, Map<String, UserType> oldUserTypes, boolean frozen, boolean shallowUserTypes) {
    if (toParse.startsWith("'"))
        return custom(toParse.substring(1, toParse.length() - 1));
    Parser parser = new Parser(toParse, 0);
    String type = parser.parseTypeName();
    DataType nativeType = NATIVE_TYPES_MAP.get(type.toLowerCase());
    if (nativeType != null)
        return nativeType;
    if (type.equalsIgnoreCase(LIST)) {
        List<String> parameters = parser.parseTypeParameters();
        if (parameters.size() != 1)
            throw new DriverInternalError(String.format("Excepting single parameter for list, got %s", parameters));
        DataType elementType = parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
        return list(elementType, frozen);
    }
    if (type.equalsIgnoreCase(SET)) {
        List<String> parameters = parser.parseTypeParameters();
        if (parameters.size() != 1)
            throw new DriverInternalError(String.format("Excepting single parameter for set, got %s", parameters));
        DataType elementType = parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
        return set(elementType, frozen);
    }
    if (type.equalsIgnoreCase(MAP)) {
        List<String> parameters = parser.parseTypeParameters();
        if (parameters.size() != 2)
            throw new DriverInternalError(String.format("Excepting two parameters for map, got %s", parameters));
        DataType keyType = parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
        DataType valueType = parse(parameters.get(1), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes);
        return map(keyType, valueType, frozen);
    }
    if (type.equalsIgnoreCase(FROZEN)) {
        List<String> parameters = parser.parseTypeParameters();
        if (parameters.size() != 1)
            throw new DriverInternalError(String.format("Excepting single parameter for frozen keyword, got %s", parameters));
        return parse(parameters.get(0), cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, true, shallowUserTypes);
    }
    if (type.equalsIgnoreCase(TUPLE)) {
        List<String> rawTypes = parser.parseTypeParameters();
        List<DataType> types = new ArrayList<DataType>(rawTypes.size());
        for (String rawType : rawTypes) {
            types.add(parse(rawType, cluster, currentKeyspaceName, currentUserTypes, oldUserTypes, false, shallowUserTypes));
        }
        return cluster.getMetadata().newTupleType(types);
    }
    // so that it gets detected later on, see TableMetadata
    if (type.equalsIgnoreCase(EMPTY))
        return custom(type);
    // Otherwise it's a UDT. If we only want a shallow definition build it, otherwise search known definitions.
    if (shallowUserTypes)
        return new UserType.Shallow(currentKeyspaceName, Metadata.handleId(type), frozen);
    UserType userType = null;
    if (currentUserTypes != null)
        userType = currentUserTypes.get(Metadata.handleId(type));
    if (userType == null && oldUserTypes != null)
        userType = oldUserTypes.get(Metadata.handleId(type));
    if (userType == null)
        throw new UnresolvedUserTypeException(currentKeyspaceName, type);
    else
        return userType.copy(frozen);
}
Also used : DriverInternalError(com.datastax.driver.core.exceptions.DriverInternalError) ArrayList(java.util.ArrayList) DataType(com.datastax.driver.core.DataType) UnresolvedUserTypeException(com.datastax.driver.core.exceptions.UnresolvedUserTypeException)

Example 7 with DriverInternalError

use of com.datastax.driver.core.exceptions.DriverInternalError in project java-driver by datastax.

the class SnappyCompressor method decompressDirect.

private ByteBuf decompressDirect(ByteBuf input) throws IOException {
    ByteBuffer in = inputNioBuffer(input);
    // Increase reader index.
    input.readerIndex(input.writerIndex());
    if (!Snappy.isValidCompressedBuffer(in))
        throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
    // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
    // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
    ByteBuf output = input.alloc().directBuffer(Snappy.uncompressedLength(in));
    try {
        ByteBuffer out = outputNioBuffer(output);
        int size = Snappy.uncompress(in, out);
        // Set the writer index so the amount of written bytes is reflected
        output.writerIndex(output.writerIndex() + size);
    } catch (IOException e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw e;
    }
    return output;
}
Also used : DriverInternalError(com.datastax.driver.core.exceptions.DriverInternalError) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer)

Example 8 with DriverInternalError

use of com.datastax.driver.core.exceptions.DriverInternalError in project java-driver by datastax.

the class SnappyCompressor method decompressHeap.

private ByteBuf decompressHeap(ByteBuf input) throws IOException {
    // Not a direct buffer so use byte arrays...
    int inOffset = input.arrayOffset() + input.readerIndex();
    byte[] in = input.array();
    int len = input.readableBytes();
    // Increase reader index.
    input.readerIndex(input.writerIndex());
    if (!Snappy.isValidCompressedBuffer(in, inOffset, len))
        throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");
    // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so
    // can eliminate the overhead of allocate a new byte[].
    ByteBuf output = input.alloc().heapBuffer(Snappy.uncompressedLength(in, inOffset, len));
    try {
        // Calculate the correct offset.
        int offset = output.arrayOffset() + output.writerIndex();
        byte[] out = output.array();
        int written = Snappy.uncompress(in, inOffset, len, out, offset);
        // Increase the writerIndex with the written bytes.
        output.writerIndex(output.writerIndex() + written);
    } catch (IOException e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw e;
    }
    return output;
}
Also used : DriverInternalError(com.datastax.driver.core.exceptions.DriverInternalError) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf)

Example 9 with DriverInternalError

use of com.datastax.driver.core.exceptions.DriverInternalError in project cassandra by apache.

the class ReprepareTestBase method testReprepareTwoKeyspaces.

public void testReprepareTwoKeyspaces(BiConsumer<ClassLoader, Integer> instanceInitializer) throws Throwable {
    try (ICluster<IInvokableInstance> c = init(builder().withNodes(2).withConfig(config -> config.with(GOSSIP, NETWORK, NATIVE_PROTOCOL)).withInstanceInitializer(instanceInitializer).start())) {
        c.schemaChange(withKeyspace("CREATE KEYSPACE %s2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2};"));
        c.schemaChange(withKeyspace("CREATE TABLE %s.tbl (pk int, ck int, v int, PRIMARY KEY (pk, ck));"));
        ForceHostLoadBalancingPolicy lbp = new ForceHostLoadBalancingPolicy();
        for (int firstContact : new int[] { 1, 2 }) try (com.datastax.driver.core.Cluster cluster = com.datastax.driver.core.Cluster.builder().addContactPoint("127.0.0.1").addContactPoint("127.0.0.2").withLoadBalancingPolicy(lbp).build();
            Session session = cluster.connect()) {
            {
                session.execute(withKeyspace("USE %s"));
                c.stream().forEach((i) -> i.runOnInstance(QueryProcessor::clearPreparedStatementsCache));
                lbp.setPrimary(firstContact);
                final PreparedStatement select = session.prepare(withKeyspace("SELECT * FROM %s.tbl"));
                session.execute(select.bind());
                c.stream().forEach((i) -> i.runOnInstance(QueryProcessor::clearPreparedStatementsCache));
                lbp.setPrimary(firstContact == 1 ? 2 : 1);
                session.execute(withKeyspace("USE %s2"));
                try {
                    session.execute(select.bind());
                } catch (DriverInternalError e) {
                    Assert.assertTrue(e.getCause().getMessage().contains("can't execute it on"));
                    continue;
                }
                fail("Should have thrown");
            }
        }
    }
}
Also used : LoadBalancingPolicy(com.datastax.driver.core.policies.LoadBalancingPolicy) MethodDelegation(net.bytebuddy.implementation.MethodDelegation) ByteBuddy(net.bytebuddy.ByteBuddy) ElementMatchers.takesArguments(net.bytebuddy.matcher.ElementMatchers.takesArguments) QueryProcessor(org.apache.cassandra.cql3.QueryProcessor) QueryHandler(org.apache.cassandra.cql3.QueryHandler) Iterators(com.google.common.collect.Iterators) NATIVE_PROTOCOL(org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL) PreparedStatement(com.datastax.driver.core.PreparedStatement) FixedValue(net.bytebuddy.implementation.FixedValue) Session(com.datastax.driver.core.Session) BiConsumer(java.util.function.BiConsumer) AssertUtils.fail(org.apache.cassandra.distributed.shared.AssertUtils.fail) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) NETWORK(org.apache.cassandra.distributed.api.Feature.NETWORK) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) FBUtilities(org.apache.cassandra.utils.FBUtilities) Iterator(java.util.Iterator) ElementMatchers.named(net.bytebuddy.matcher.ElementMatchers.named) Collection(java.util.Collection) ClientState(org.apache.cassandra.service.ClientState) ICluster(org.apache.cassandra.distributed.api.ICluster) ClassLoadingStrategy(net.bytebuddy.dynamic.loading.ClassLoadingStrategy) DriverInternalError(com.datastax.driver.core.exceptions.DriverInternalError) List(java.util.List) IInvokableInstance(org.apache.cassandra.distributed.api.IInvokableInstance) Cluster(com.datastax.driver.core.Cluster) Host(com.datastax.driver.core.Host) HostDistance(com.datastax.driver.core.HostDistance) Comparator(java.util.Comparator) Assert(org.junit.Assert) Collections(java.util.Collections) Statement(com.datastax.driver.core.Statement) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) GOSSIP(org.apache.cassandra.distributed.api.Feature.GOSSIP) IInvokableInstance(org.apache.cassandra.distributed.api.IInvokableInstance) DriverInternalError(com.datastax.driver.core.exceptions.DriverInternalError) ICluster(org.apache.cassandra.distributed.api.ICluster) Cluster(com.datastax.driver.core.Cluster) PreparedStatement(com.datastax.driver.core.PreparedStatement) Session(com.datastax.driver.core.Session)

Aggregations

DriverInternalError (com.datastax.driver.core.exceptions.DriverInternalError)9 ByteBuf (io.netty.buffer.ByteBuf)2 IOException (java.io.IOException)2 UnknownHostException (java.net.UnknownHostException)2 ByteBuffer (java.nio.ByteBuffer)2 Cluster (com.datastax.driver.core.Cluster)1 DataType (com.datastax.driver.core.DataType)1 Host (com.datastax.driver.core.Host)1 HostDistance (com.datastax.driver.core.HostDistance)1 PreparedStatement (com.datastax.driver.core.PreparedStatement)1 Session (com.datastax.driver.core.Session)1 Statement (com.datastax.driver.core.Statement)1 UnresolvedUserTypeException (com.datastax.driver.core.exceptions.UnresolvedUserTypeException)1 LoadBalancingPolicy (com.datastax.driver.core.policies.LoadBalancingPolicy)1 Iterators (com.google.common.collect.Iterators)1 InetSocketAddress (java.net.InetSocketAddress)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Comparator (java.util.Comparator)1