Search in sources :

Example 11 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class Sdk2CompatibleLegacyTranscoder method deserialize.

protected Object deserialize(byte[] in) {
    Object rv = null;
    ByteArrayInputStream bis = null;
    ObjectInputStream is = null;
    try {
        if (in != null) {
            bis = new ByteArrayInputStream(in);
            is = new ObjectInputStream(bis);
            rv = is.readObject();
            is.close();
            bis.close();
        }
    } catch (IOException e) {
        throw new CouchbaseException("Caught IOException decoding bytes of data", e);
    } catch (ClassNotFoundException e) {
        throw new CouchbaseException("Caught ClassNotFoundException decoding bytes of data", e);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (Exception ex) {
        // ignored
        }
        try {
            if (bis != null) {
                bis.close();
            }
        } catch (Exception ex) {
        // ignored
        }
    }
    return rv;
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) IOException(java.io.IOException) ObjectInputStream(java.io.ObjectInputStream)

Example 12 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class CouchbaseArrayList method set.

@Override
public E set(int index, E element) {
    // fail fast on negative values, as they are interpreted as "starting from the back of the array" otherwise
    if (index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index);
    }
    String idx = "[" + index + "]";
    for (int i = 0; i < arrayListOptions.casMismatchRetries(); i++) {
        try {
            LookupInResult current = collection.lookupIn(id, Collections.singletonList(LookupInSpec.get(idx)), lookupInOptions);
            long returnCas = current.cas();
            // this loop ensures we return exactly what we replaced
            final E result = current.contentAs(0, entityTypeClass);
            collection.mutateIn(id, Collections.singletonList(MutateInSpec.replace(idx, element)), arrayListOptions.mutateInOptions().cas(returnCas));
            return result;
        } catch (DocumentNotFoundException e) {
            createEmptyList();
        } catch (CasMismatchException ex) {
        // will need to retry get-and-set
        } catch (PathNotFoundException ex) {
            throw new IndexOutOfBoundsException("Index: " + index);
        }
    }
    throw new CouchbaseException("CouchbaseArrayList set failed", new RetryExhaustedException("Couldn't perform set in less than " + arrayListOptions.casMismatchRetries() + " iterations. It is likely concurrent modifications of this document are the reason"));
}
Also used : LookupInResult(com.couchbase.client.java.kv.LookupInResult) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) DocumentNotFoundException(com.couchbase.client.core.error.DocumentNotFoundException) RetryExhaustedException(com.couchbase.client.core.retry.reactor.RetryExhaustedException) CasMismatchException(com.couchbase.client.core.error.CasMismatchException) PathNotFoundException(com.couchbase.client.core.error.subdoc.PathNotFoundException)

Example 13 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class ConnectionString method parseParams.

static Map<String, String> parseParams(final String input) {
    try {
        String[] parts = input.split("\\?");
        Map<String, String> params = new HashMap<>();
        if (parts.length > 1) {
            String found = parts[1];
            String[] exploded = found.split("&");
            for (int i = 0; i < exploded.length; i++) {
                String[] pair = exploded[i].split("=");
                params.put(pair[0], pair[1]);
            }
        }
        return params;
    } catch (Exception ex) {
        throw new CouchbaseException("Could not parse Params of connection string: " + input, ex);
    }
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) HashMap(java.util.HashMap) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) InvalidArgumentException(com.couchbase.client.core.error.InvalidArgumentException)

Example 14 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class ReplicaHelper method getAnyReplicaAsync.

/**
 * @param clientContext (nullable)
 * @param parentSpan (nullable)
 * @param responseMapper converts the GetReplicaResponse to the client's native result type
 */
public static <R> CompletableFuture<R> getAnyReplicaAsync(final Core core, final CollectionIdentifier collectionIdentifier, final String documentId, final Duration timeout, final RetryStrategy retryStrategy, final Map<String, Object> clientContext, final RequestSpan parentSpan, final Function<GetReplicaResponse, R> responseMapper) {
    RequestSpan getAnySpan = core.context().environment().requestTracer().requestSpan(TracingIdentifiers.SPAN_GET_ANY_REPLICA, parentSpan);
    CompletableFuture<List<CompletableFuture<R>>> listOfFutures = getAllReplicasAsync(core, collectionIdentifier, documentId, timeout, retryStrategy, clientContext, getAnySpan, responseMapper);
    // Aggregating the futures here will discard the individual errors, which we don't need
    CompletableFuture<R> anyReplicaFuture = new CompletableFuture<>();
    listOfFutures.whenComplete((futures, throwable) -> {
        if (throwable != null) {
            anyReplicaFuture.completeExceptionally(throwable);
        }
        final AtomicBoolean successCompleted = new AtomicBoolean(false);
        final AtomicInteger totalCompleted = new AtomicInteger(0);
        final List<ErrorContext> nestedContexts = Collections.synchronizedList(new ArrayList<>());
        futures.forEach(individual -> individual.whenComplete((result, error) -> {
            int completed = totalCompleted.incrementAndGet();
            if (error != null) {
                if (error instanceof CompletionException && error.getCause() instanceof CouchbaseException) {
                    nestedContexts.add(((CouchbaseException) error.getCause()).context());
                }
            }
            if (result != null && successCompleted.compareAndSet(false, true)) {
                anyReplicaFuture.complete(result);
            }
            if (!successCompleted.get() && completed == futures.size()) {
                anyReplicaFuture.completeExceptionally(new DocumentUnretrievableException(new AggregateErrorContext(nestedContexts)));
            }
        }));
    });
    return anyReplicaFuture.whenComplete((getReplicaResult, throwable) -> getAnySpan.end());
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) CouchbaseBucketConfig(com.couchbase.client.core.config.CouchbaseBucketConfig) ArrayList(java.util.ArrayList) DefaultErrorUtil.keyValueStatusToException(com.couchbase.client.core.error.DefaultErrorUtil.keyValueStatusToException) TracingIdentifiers(com.couchbase.client.core.cnc.TracingIdentifiers) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DocumentUnretrievableException(com.couchbase.client.core.error.DocumentUnretrievableException) CoreContext(com.couchbase.client.core.CoreContext) Duration(java.time.Duration) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) Stability(com.couchbase.client.core.annotation.Stability) RequestSpan(com.couchbase.client.core.cnc.RequestSpan) GetResponse(com.couchbase.client.core.msg.kv.GetResponse) IndividualReplicaGetFailedEvent(com.couchbase.client.core.cnc.events.request.IndividualReplicaGetFailedEvent) BucketConfig(com.couchbase.client.core.config.BucketConfig) Reactor(com.couchbase.client.core.Reactor) CommonExceptions(com.couchbase.client.core.error.CommonExceptions) Mono(reactor.core.publisher.Mono) CompletionException(java.util.concurrent.CompletionException) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) Collectors(java.util.stream.Collectors) Validators.notNullOrEmpty(com.couchbase.client.core.util.Validators.notNullOrEmpty) Flux(reactor.core.publisher.Flux) List(java.util.List) Stream(java.util.stream.Stream) GetRequest(com.couchbase.client.core.msg.kv.GetRequest) ReplicaGetRequest(com.couchbase.client.core.msg.kv.ReplicaGetRequest) ErrorContext(com.couchbase.client.core.error.context.ErrorContext) CollectionIdentifier(com.couchbase.client.core.io.CollectionIdentifier) RetryStrategy(com.couchbase.client.core.retry.RetryStrategy) Core(com.couchbase.client.core.Core) ReducedKeyValueErrorContext(com.couchbase.client.core.error.context.ReducedKeyValueErrorContext) Collections(java.util.Collections) AggregateErrorContext(com.couchbase.client.core.error.context.AggregateErrorContext) DocumentUnretrievableException(com.couchbase.client.core.error.DocumentUnretrievableException) ErrorContext(com.couchbase.client.core.error.context.ErrorContext) ReducedKeyValueErrorContext(com.couchbase.client.core.error.context.ReducedKeyValueErrorContext) AggregateErrorContext(com.couchbase.client.core.error.context.AggregateErrorContext) RequestSpan(com.couchbase.client.core.cnc.RequestSpan) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AggregateErrorContext(com.couchbase.client.core.error.context.AggregateErrorContext) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 15 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class Bytes method readAllBytes.

public static byte[] readAllBytes(InputStream is) {
    notNull(is, "input stream");
    try {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[4 * 1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            result.write(buffer, 0, len);
        }
        return result.toByteArray();
    } catch (IOException e) {
        throw new CouchbaseException("Failed to read bytes from stream.", e);
    }
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

CouchbaseException (com.couchbase.client.core.error.CouchbaseException)46 DocumentNotFoundException (com.couchbase.client.core.error.DocumentNotFoundException)8 Test (org.junit.jupiter.api.Test)8 ByteBuf (com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)7 CasMismatchException (com.couchbase.client.core.error.CasMismatchException)7 RetryExhaustedException (com.couchbase.client.core.retry.reactor.RetryExhaustedException)7 LookupInResult (com.couchbase.client.java.kv.LookupInResult)7 JavaIntegrationTest (com.couchbase.client.java.util.JavaIntegrationTest)7 Duration (java.time.Duration)7 IgnoreWhen (com.couchbase.client.test.IgnoreWhen)6 ArrayList (java.util.ArrayList)6 AuthenticationFailureException (com.couchbase.client.core.error.AuthenticationFailureException)5 RateLimitedException (com.couchbase.client.core.error.RateLimitedException)5 IndexNotFoundException (com.couchbase.client.core.error.IndexNotFoundException)4 UnambiguousTimeoutException (com.couchbase.client.core.error.UnambiguousTimeoutException)4 PathNotFoundException (com.couchbase.client.core.error.subdoc.PathNotFoundException)4 JsonObject (com.couchbase.client.java.json.JsonObject)4 SearchIndex (com.couchbase.client.java.manager.search.SearchIndex)4 List (java.util.List)4 RequestSpan (com.couchbase.client.core.cnc.RequestSpan)3