Search in sources :

Example 1 with CoreHttpResponse

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

the class AnalyticsProtocol method submitStatement.

@Override
public QueryServiceResponse submitStatement(final String sql, final List<?> args, final SubmitStatementOptions options) throws SQLException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
    try {
        JsonGenerator jsonGen = driverContext.getGenericObjectWriter().getFactory().createGenerator(baos, JsonEncoding.UTF8);
        jsonGen.writeStartObject();
        jsonGen.writeStringField(CLIENT_TYPE, CLIENT_TYPE_JDBC);
        jsonGen.writeStringField(MODE, MODE_DEFERRED);
        jsonGen.writeStringField(STATEMENT, sql);
        jsonGen.writeBooleanField(SIGNATURE, true);
        jsonGen.writeStringField(PLAN_FORMAT, PLAN_FORMAT_STRING);
        jsonGen.writeNumberField(MAX_WARNINGS, maxWarnings);
        if (options.compileOnly) {
            jsonGen.writeBooleanField(COMPILE_ONLY, true);
        }
        if (options.forceReadOnly) {
            jsonGen.writeBooleanField(READ_ONLY, true);
        }
        if (options.sqlCompatMode) {
            jsonGen.writeBooleanField(SQL_COMPAT, true);
        }
        if (options.timeoutSeconds > 0) {
            jsonGen.writeStringField(TIMEOUT, options.timeoutSeconds + "s");
        }
        if (options.dataverseName != null) {
            jsonGen.writeStringField(DATAVERSE, options.dataverseName);
        }
        if (options.executionId != null) {
            jsonGen.writeStringField(CLIENT_CONTEXT_ID, options.executionId.toString());
        }
        if (scanWait != null && !scanWait.isEmpty()) {
            jsonGen.writeStringField(SCAN_WAIT, scanWait);
        }
        if (scanConsistency != null && !scanConsistency.isEmpty()) {
            jsonGen.writeStringField(SCAN_CONSISTENCY, scanConsistency);
        }
        if (args != null && !args.isEmpty()) {
            jsonGen.writeFieldName(ARGS);
            driverContext.getAdmFormatObjectWriter().writeValue(jsonGen, args);
        }
        jsonGen.writeEndObject();
        jsonGen.flush();
    } catch (InvalidDefinitionException e) {
        throw getErrorReporter().errorUnexpectedType(e.getType().getRawClass());
    } catch (IOException e) {
        throw getErrorReporter().errorInRequestGeneration(e);
    }
    Map<String, Object> headers = new HashMap<>();
    headers.put("Accept", "application/json; charset=UTF-8; lossless-adm=true");
    if (getLogger().isLoggable(Level.FINE)) {
        getLogger().log(Level.FINE, String.format("%s { %s } with args { %s }", options.compileOnly ? "compile" : "execute", sql, args != null ? args : ""));
    }
    try {
        CoreHttpResponse coreHttpResponse = connectionHandle.rawAnalyticsQuery(ConnectionHandle.HttpMethod.POST, QUERY_SERVICE_ENDPOINT_PATH, headers, baos.toByteArray(), getTimeout(options));
        return driverContext.getGenericObjectReader().forType(QueryServiceResponse.class).readValue(coreHttpResponse.content());
    } catch (JsonProcessingException e) {
        throw getErrorReporter().errorInProtocol(e);
    } catch (IOException e) {
        throw getErrorReporter().errorInConnection(e);
    }
}
Also used : HashMap(java.util.HashMap) InvalidDefinitionException(com.fasterxml.jackson.databind.exc.InvalidDefinitionException) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) CoreHttpResponse(com.couchbase.client.core.endpoint.http.CoreHttpResponse)

Example 2 with CoreHttpResponse

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

the class ViewEndpointIntegrationTest method dispatchGenericRequest.

/**
 * Makes sure that we can execute a generic view management request.
 *
 * <p>The mock does not support hitting the / path for views, so this test is ignored there.</p>
 */
@Test
@IgnoreWhen(clusterTypes = ClusterType.MOCKED)
void dispatchGenericRequest() throws Exception {
    TestNodeConfig node = config().nodes().get(0);
    ViewEndpoint endpoint = new ViewEndpoint(serviceContext, node.hostname(), node.ports().get(Services.VIEW));
    endpoint.connect();
    waitUntilCondition(() -> endpoint.state() == EndpointState.CONNECTED);
    CoreHttpRequest request = CoreHttpRequest.builder(CoreCommonOptions.of(Duration.ofSeconds(5), null, null), serviceContext, HttpMethod.GET, CoreHttpPath.path("/"), RequestTarget.views(config().bucketname())).build();
    endpoint.send(request);
    CoreHttpResponse response = request.response().get();
    assertEquals(ResponseStatus.SUCCESS, response.status());
    assertNotNull(response.content());
    assertTrue(response.content().length > 0);
    endpoint.disconnect();
    waitUntilCondition(() -> endpoint.state() == EndpointState.DISCONNECTED);
}
Also used : CoreHttpRequest(com.couchbase.client.core.endpoint.http.CoreHttpRequest) TestNodeConfig(com.couchbase.client.test.TestNodeConfig) CoreHttpResponse(com.couchbase.client.core.endpoint.http.CoreHttpResponse) IgnoreWhen(com.couchbase.client.test.IgnoreWhen) CoreIntegrationTest(com.couchbase.client.core.util.CoreIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 3 with CoreHttpResponse

use of com.couchbase.client.core.endpoint.http.CoreHttpResponse 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 CoreHttpResponse

use of com.couchbase.client.core.endpoint.http.CoreHttpResponse 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 CoreHttpResponse

use of com.couchbase.client.core.endpoint.http.CoreHttpResponse 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

CoreHttpResponse (com.couchbase.client.core.endpoint.http.CoreHttpResponse)7 CoreHttpClient (com.couchbase.client.core.endpoint.http.CoreHttpClient)4 UrlQueryStringBuilder (com.couchbase.client.core.util.UrlQueryStringBuilder)3 HashMap (java.util.HashMap)3 JsonObject (com.couchbase.client.java.json.JsonObject)2 JsonNode (com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode)1 CoreHttpPath (com.couchbase.client.core.endpoint.http.CoreHttpPath)1 CoreHttpRequest (com.couchbase.client.core.endpoint.http.CoreHttpRequest)1 AuthenticationFailureException (com.couchbase.client.core.error.AuthenticationFailureException)1 CouchbaseException (com.couchbase.client.core.error.CouchbaseException)1 CoreIntegrationTest (com.couchbase.client.core.util.CoreIntegrationTest)1 IgnoreWhen (com.couchbase.client.test.IgnoreWhen)1 TestNodeConfig (com.couchbase.client.test.TestNodeConfig)1 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 InvalidDefinitionException (com.fasterxml.jackson.databind.exc.InvalidDefinitionException)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 SQLException (java.sql.SQLException)1 ExecutionException (java.util.concurrent.ExecutionException)1