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);
}
}
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);
}
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());
}
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());
}
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);
}
}
Aggregations