Search in sources :

Example 1 with CoreHttpClient

use of com.couchbase.client.core.endpoint.http.CoreHttpClient in project couchbase-jdbc-driver by couchbaselabs.

the class ConnectionHandle method rawAnalyticsQuery.

/**
 * Sends a raw analytics query, allows to be used where the regular API does not suffice.
 * <p>
 * It should really only be used if the primary query API cannot be used for some reason.
 *
 * @param method the http method to use.
 * @param path the http path to execute.
 * @param headers the optional http headers to send.
 * @param content the optional payload to send.
 * @param timeout the timeout to use.
 * @return the core response to use.
 * @throws SQLException in case the query failed.
 */
public CoreHttpResponse rawAnalyticsQuery(HttpMethod method, String path, Map<String, Object> headers, byte[] content, Duration timeout) throws SQLException {
    CoreHttpClient client = cluster.core().httpClient(RequestTarget.analytics());
    CoreCommonOptions options = CoreCommonOptions.of(timeout == null || timeout.isZero() ? null : timeout, null, null);
    CoreHttpRequest.Builder builder;
    switch(method) {
        case GET:
            builder = client.get(path(path), options);
            break;
        case DELETE:
            builder = client.delete(path(path), options);
            break;
        case POST:
            builder = client.post(path(path), options);
            if (content != null) {
                builder = builder.json(content);
            }
            break;
        default:
            throw new IllegalStateException("Unsupported http verb: " + method);
    }
    if (headers != null) {
        for (Map.Entry<String, Object> header : headers.entrySet()) {
            builder = builder.header(header.getKey(), header.getValue());
        }
    }
    try {
        return builder.build().exec(cluster.core()).get();
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof CouchbaseException) {
            String ctx = ((CouchbaseException) ex.getCause()).context().exportAsString(Context.ExportFormat.JSON);
            throw new SQLException("Failed to perform analytics query: " + ctx, ex);
        } else {
            throw new SQLException("Failed to perform analytics query - cause: " + ex.getMessage(), ex);
        }
    } catch (Exception ex) {
        throw new SQLException("Failed to perform analytics query - cause: " + ex.getMessage(), ex);
    }
}
Also used : CoreHttpRequest(com.couchbase.client.core.endpoint.http.CoreHttpRequest) SQLException(java.sql.SQLException) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ExecutionException(java.util.concurrent.ExecutionException) SQLException(java.sql.SQLException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) CoreCommonOptions(com.couchbase.client.core.endpoint.http.CoreCommonOptions) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map)

Example 2 with CoreHttpClient

use of com.couchbase.client.core.endpoint.http.CoreHttpClient in project couchbase-jvm-clients by couchbase.

the class AsyncCouchbaseHttpClient method exec.

private CompletableFuture<HttpResponse> exec(HttpMethod method, HttpTarget target, HttpPath path, CommonHttpOptions<?>.BuiltCommonHttpOptions options, Consumer<CoreHttpRequest.Builder> customizer) {
    CoreHttpRequest.Builder builder = new CoreHttpClient(core, target.coreTarget).newRequest(method, CoreHttpPath.path(path.formatted), options).bypassExceptionTranslation(true);
    options.headers().forEach(it -> builder.header(it.name, it.value));
    customizer.accept(builder);
    CoreHttpRequest req = builder.build();
    // request doesn't mysteriously time out while the service locator twiddles its thumbs.
    if (req.bucket() != null) {
        cluster.bucket(req.bucket());
    }
    return req.exec(core).thenApply(HttpResponse::new).exceptionally(t -> {
        HttpStatusCodeException statusCodeException = findCause(t, HttpStatusCodeException.class).orElseThrow(() -> propagate(t));
        return new HttpResponse(statusCodeException);
    });
}
Also used : CoreHttpRequest(com.couchbase.client.core.endpoint.http.CoreHttpRequest) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) HttpStatusCodeException(com.couchbase.client.core.error.HttpStatusCodeException)

Example 3 with CoreHttpClient

use of com.couchbase.client.core.endpoint.http.CoreHttpClient in project couchbase-jvm-clients by couchbase.

the class RateLimitingIntegrationTest method createLimitedScope.

static void createLimitedScope(String name, String bucket, ScopeRateLimits limits) throws Exception {
    Map<String, Object> jsonLimits = new HashMap<>();
    if (limits.kv != null) {
        jsonLimits.put("kv", mapOf("data_size", limits.kv.dataSize));
    }
    if (limits.fts != null) {
        jsonLimits.put("fts", mapOf("num_fts_indexes", limits.fts.numFtsIndexes));
    }
    if (limits.index != null) {
        jsonLimits.put("index", mapOf("num_indexes", limits.index.numIndexes));
    }
    if (limits.clusterManager != null) {
        jsonLimits.put("clusterManager", mapOf("num_collections", limits.clusterManager.numCollections));
    }
    UrlQueryStringBuilder formParams = UrlQueryStringBuilder.create();
    formParams.add("name", name);
    if (!jsonLimits.isEmpty()) {
        formParams.add("limits", Mapper.encodeAsString(jsonLimits));
    }
    CoreHttpClient client = adminCluster.core().httpClient(RequestTarget.manager());
    CoreHttpResponse result = client.post(path("/pools/default/buckets/" + bucket + "/scopes"), CoreCommonOptions.DEFAULT).form(formParams).exec(adminCluster.core()).get();
    assertEquals(ResponseStatus.SUCCESS, result.status());
}
Also used : HashMap(java.util.HashMap) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) JsonObject(com.couchbase.client.java.json.JsonObject) UrlQueryStringBuilder(com.couchbase.client.core.util.UrlQueryStringBuilder) CoreHttpResponse(com.couchbase.client.core.endpoint.http.CoreHttpResponse)

Example 4 with CoreHttpClient

use of com.couchbase.client.core.endpoint.http.CoreHttpClient in project couchbase-jvm-clients by couchbase.

the class RateLimitingIntegrationTest method createRateLimitedUser.

/**
 * Creates a user which is rate limited to perform the tests.
 */
static void createRateLimitedUser(String username, Limits limits) throws Exception {
    Map<String, Object> jsonLimits = new HashMap<>();
    if (limits.keyValueLimits != null) {
        KeyValueLimits kv = limits.keyValueLimits;
        jsonLimits.put("kv", CbCollections.mapOf("num_connections", kv.numConnections, "num_ops_per_min", kv.numOpsPerMin, "ingress_mib_per_min", kv.ingressMibPerMin, "egress_mib_per_min", kv.egressMibPerMin));
    }
    if (limits.queryLimits != null) {
        QueryLimits query = limits.queryLimits;
        jsonLimits.put("query", mapOf("num_queries_per_min", query.numQueriesPerMin, "num_concurrent_requests", query.numConcurrentRequests, "ingress_mib_per_min", query.ingressMibPerMin, "egress_mib_per_min", query.egressMibPerMin));
    }
    if (limits.searchLimits != null) {
        SearchLimits fts = limits.searchLimits;
        jsonLimits.put("fts", mapOf("num_queries_per_min", fts.numQueriesPerMin, "num_concurrent_requests", fts.numConcurrentRequests, "ingress_mib_per_min", fts.ingressMibPerMin, "egress_mib_per_min", fts.egressMibPerMin));
    }
    if (limits.clusterManagerLimits != null) {
        ClusterManagerLimits cm = limits.clusterManagerLimits;
        jsonLimits.put("clusterManager", mapOf("num_concurrent_requests", cm.numConcurrentRequests, "ingress_mib_per_min", cm.ingressMibPerMin, "egress_mib_per_min", cm.egressMibPerMin));
    }
    UrlQueryStringBuilder formParams = UrlQueryStringBuilder.create();
    formParams.add("password", RL_PASSWORD);
    formParams.add("roles", "admin");
    if (!jsonLimits.isEmpty()) {
        formParams.add("limits", Mapper.encodeAsString(jsonLimits));
    }
    CoreHttpClient client = adminCluster.core().httpClient(RequestTarget.manager());
    CoreHttpResponse result = client.put(path("/settings/rbac/users/local/" + username), CoreCommonOptions.DEFAULT).form(formParams).exec(adminCluster.core()).get();
    assertEquals(ResponseStatus.SUCCESS, result.status());
}
Also used : HashMap(java.util.HashMap) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) JsonObject(com.couchbase.client.java.json.JsonObject) UrlQueryStringBuilder(com.couchbase.client.core.util.UrlQueryStringBuilder) CoreHttpResponse(com.couchbase.client.core.endpoint.http.CoreHttpResponse)

Example 5 with CoreHttpClient

use of com.couchbase.client.core.endpoint.http.CoreHttpClient in project couchbase-jdbc-driver by couchbaselabs.

the class ConnectionHandle method clusterVersion.

/**
 * Retrieves the raw cluster version as a string.
 *
 * @return the cluster version as a string if successful.
 * @throws SQLException if fetching the cluster version failed.
 */
public String clusterVersion() throws SQLException {
    CoreHttpClient client = cluster.core().httpClient(RequestTarget.manager());
    CompletableFuture<CoreHttpResponse> exec = client.get(path("/pools"), CoreCommonOptions.DEFAULT).build().exec(cluster.core());
    try {
        JsonNode root = Mapper.decodeIntoTree(exec.get().content());
        return root.get("implementationVersion").asText();
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof AuthenticationFailureException) {
            throw authError(ex);
        } else {
            throw new SQLException("Failed to fetch cluster version", ex);
        }
    } catch (Exception e) {
        throw new SQLException("Failed to fetch cluster version", e);
    }
}
Also used : SQLException(java.sql.SQLException) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) JsonNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) ExecutionException(java.util.concurrent.ExecutionException) CoreHttpResponse(com.couchbase.client.core.endpoint.http.CoreHttpResponse) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ExecutionException(java.util.concurrent.ExecutionException) SQLException(java.sql.SQLException)

Aggregations

CoreHttpClient (com.couchbase.client.core.endpoint.http.CoreHttpClient)6 CoreHttpResponse (com.couchbase.client.core.endpoint.http.CoreHttpResponse)4 CoreHttpRequest (com.couchbase.client.core.endpoint.http.CoreHttpRequest)2 AuthenticationFailureException (com.couchbase.client.core.error.AuthenticationFailureException)2 CouchbaseException (com.couchbase.client.core.error.CouchbaseException)2 UrlQueryStringBuilder (com.couchbase.client.core.util.UrlQueryStringBuilder)2 JsonObject (com.couchbase.client.java.json.JsonObject)2 SQLException (java.sql.SQLException)2 HashMap (java.util.HashMap)2 ExecutionException (java.util.concurrent.ExecutionException)2 JsonNode (com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode)1 CoreCommonOptions (com.couchbase.client.core.endpoint.http.CoreCommonOptions)1 HttpStatusCodeException (com.couchbase.client.core.error.HttpStatusCodeException)1 Map (java.util.Map)1