Search in sources :

Example 6 with JsonNode

use of com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode 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)

Example 7 with JsonNode

use of com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode in project couchbase-jvm-clients by couchbase.

the class CoreViewIndexManager method parseAllDesignDocuments.

private static Map<String, ObjectNode> parseAllDesignDocuments(JsonNode node, boolean production) {
    Map<String, ObjectNode> result = new LinkedHashMap<>();
    node.get("rows").forEach(row -> {
        String metaId = row.path("doc").path("meta").path("id").asText();
        String ddocName = removeStart(metaId, "_design/");
        if (namespaceContainsName(ddocName, production)) {
            JsonNode ddocDef = row.path("doc").path("json");
            result.put(ddocName, (ObjectNode) ddocDef);
        }
    });
    return result;
}
Also used : ObjectNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with JsonNode

use of com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode in project couchbase-jvm-clients by couchbase.

the class ProjectionsApplier method insert.

private static void insert(ObjectNode document, String path, byte[] value) {
    List<PathElement> parsedPath = JsonPathParser.parse(path);
    JsonNode content = Mapper.decodeIntoTree(value);
    insertRecursive(document, parsedPath, content);
}
Also used : JsonNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode)

Example 9 with JsonNode

use of com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode in project couchbase-jvm-clients by couchbase.

the class AsyncSearchIndexManager method analyzeDocument.

/**
 * Allows to see how a document is analyzed against a specific index.
 *
 * @param name the name of the search index.
 * @param document the document to analyze.
 * @return a {@link CompletableFuture} with analyzed document parts once complete.
 */
public CompletableFuture<List<JsonObject>> analyzeDocument(final String name, final JsonObject document, final AnalyzeDocumentOptions options) {
    notNullOrEmpty(name, "Search Index Name");
    notNull(document, "Document");
    return searchHttpClient.post(path(analyzeDocumentPath(name)), options.build()).trace(TracingIdentifiers.SPAN_REQUEST_MS_ANALYZE_DOCUMENT).json(Mapper.encodeAsBytes(document.toMap())).exec(core).exceptionally(throwable -> {
        if (throwable.getMessage().contains("Page not found")) {
            throw new FeatureNotAvailableException("Document analysis is not available on this server version!");
        } else if (throwable instanceof RuntimeException) {
            throw (RuntimeException) throwable;
        } else {
            throw new CouchbaseException("Failed to analyze search document", throwable);
        }
    }).thenApply(response -> {
        JsonNode rootNode = Mapper.decodeIntoTree(response.content());
        List<Map<String, Object>> analyzed = Mapper.convertValue(rootNode.get("analyzed"), new TypeReference<List<Map<String, Object>>>() {
        });
        return analyzed.stream().filter(Objects::nonNull).map(JsonObject::from).collect(Collectors.toList());
    });
}
Also used : AnalyzeDocumentOptions.analyzeDocumentOptions(com.couchbase.client.java.manager.search.AnalyzeDocumentOptions.analyzeDocumentOptions) HttpHeaderNames(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpHeaderNames) GetSearchIndexOptions.getSearchIndexOptions(com.couchbase.client.java.manager.search.GetSearchIndexOptions.getSearchIndexOptions) Validators.notNull(com.couchbase.client.core.util.Validators.notNull) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) RequestTarget(com.couchbase.client.core.msg.RequestTarget) TypeReference(com.couchbase.client.core.deps.com.fasterxml.jackson.core.type.TypeReference) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) JsonNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode) TracingIdentifiers(com.couchbase.client.core.cnc.TracingIdentifiers) Map(java.util.Map) CoreHttpPath.path(com.couchbase.client.core.endpoint.http.CoreHttpPath.path) DropSearchIndexOptions.dropSearchIndexOptions(com.couchbase.client.java.manager.search.DropSearchIndexOptions.dropSearchIndexOptions) RequestSpan(com.couchbase.client.core.cnc.RequestSpan) GetAllSearchIndexesOptions.getAllSearchIndexesOptions(com.couchbase.client.java.manager.search.GetAllSearchIndexesOptions.getAllSearchIndexesOptions) CbTracing(com.couchbase.client.core.cnc.CbTracing) AllowQueryingSearchIndexOptions.allowQueryingSearchIndexOptions(com.couchbase.client.java.manager.search.AllowQueryingSearchIndexOptions.allowQueryingSearchIndexOptions) UTF_8(java.nio.charset.StandardCharsets.UTF_8) IndexNotFoundException(com.couchbase.client.core.error.IndexNotFoundException) Mapper(com.couchbase.client.core.json.Mapper) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) UrlQueryStringBuilder.urlEncode(com.couchbase.client.core.util.UrlQueryStringBuilder.urlEncode) FeatureNotAvailableException(com.couchbase.client.core.error.FeatureNotAvailableException) UpsertSearchIndexOptions.upsertSearchIndexOptions(com.couchbase.client.java.manager.search.UpsertSearchIndexOptions.upsertSearchIndexOptions) Collectors(java.util.stream.Collectors) Validators.notNullOrEmpty(com.couchbase.client.core.util.Validators.notNullOrEmpty) PauseIngestSearchIndexOptions.pauseIngestSearchIndexOptions(com.couchbase.client.java.manager.search.PauseIngestSearchIndexOptions.pauseIngestSearchIndexOptions) Objects(java.util.Objects) List(java.util.List) GetIndexedSearchIndexOptions.getIndexedSearchIndexOptions(com.couchbase.client.java.manager.search.GetIndexedSearchIndexOptions.getIndexedSearchIndexOptions) UnfreezePlanSearchIndexOptions.unfreezePlanSearchIndexOptions(com.couchbase.client.java.manager.search.UnfreezePlanSearchIndexOptions.unfreezePlanSearchIndexOptions) ResumeIngestSearchIndexOptions.resumeIngestSearchIndexOptions(com.couchbase.client.java.manager.search.ResumeIngestSearchIndexOptions.resumeIngestSearchIndexOptions) JsonObject(com.couchbase.client.java.json.JsonObject) FreezePlanSearchIndexOptions.freezePlanSearchIndexOptions(com.couchbase.client.java.manager.search.FreezePlanSearchIndexOptions.freezePlanSearchIndexOptions) Core(com.couchbase.client.core.Core) DisallowQueryingSearchIndexOptions.disallowQueryingSearchIndexOptions(com.couchbase.client.java.manager.search.DisallowQueryingSearchIndexOptions.disallowQueryingSearchIndexOptions) FeatureNotAvailableException(com.couchbase.client.core.error.FeatureNotAvailableException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) Objects(java.util.Objects) JsonNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode) ArrayList(java.util.ArrayList) List(java.util.List) JsonObject(com.couchbase.client.java.json.JsonObject) Map(java.util.Map)

Example 10 with JsonNode

use of com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode in project couchbase-jvm-clients by couchbase.

the class AsyncEventingFunctionManager method decodeFunction.

/**
 * Decodes a single {@link EventingFunction} from its raw encoded JSON representation.
 *
 * @param encoded the encoded JSON format.
 * @return an instantiated {@link EventingFunction}.
 */
static EventingFunction decodeFunction(final byte[] encoded) {
    JsonNode func = Mapper.decodeIntoTree(encoded);
    if (func.isArray()) {
        throw new InvalidArgumentException("The provided JSON is an array (potentially of functions), not an individual function.", null, null);
    }
    JsonNode depcfg = func.get("depcfg");
    JsonNode settings = func.get("settings");
    String version = func.has("version") ? func.get("version").asText() : null;
    String functionInstanceId = func.has("function_instance_id") ? func.get("function_instance_id").asText() : null;
    int handlerUuid = func.has("handleruuid") ? func.get("handleruuid").asInt() : 0;
    EventingFunction.Builder toReturn = EventingFunction.builder(func.get("appname").asText(), func.get("appcode").asText(), EventingFunctionKeyspace.create(depcfg.get("source_bucket").asText(), depcfg.get("source_scope").asText(), depcfg.get("source_collection").asText()), EventingFunctionKeyspace.create(depcfg.get("metadata_bucket").asText(), depcfg.get("metadata_scope").asText(), depcfg.get("metadata_collection").asText())).handlerUuid(handlerUuid).functionInstanceId(functionInstanceId).version(version);
    EventingFunctionSettings.Builder settingsBuilder = EventingFunctionSettings.builder();
    if (settings.has("deployment_status")) {
        settingsBuilder.deploymentStatus(settings.get("deployment_status").asBoolean() ? EventingFunctionDeploymentStatus.DEPLOYED : EventingFunctionDeploymentStatus.UNDEPLOYED);
    }
    if (settings.has("processing_status")) {
        settingsBuilder.processingStatus(settings.get("processing_status").asBoolean() ? EventingFunctionProcessingStatus.RUNNING : EventingFunctionProcessingStatus.PAUSED);
    }
    if (func.has("enforce_schema")) {
        toReturn.enforceSchema(func.get("enforce_schema").asBoolean());
    }
    if (settings.has("cpp_worker_thread_count")) {
        settingsBuilder.cppWorkerThreadCount(settings.get("cpp_worker_thread_count").asLong());
    }
    if (settings.has("dcp_stream_boundary")) {
        String boundary = settings.get("dcp_stream_boundary").asText();
        settingsBuilder.dcpStreamBoundary(boundary.equals(EventingFunctionDcpBoundary.EVERYTHING.toString()) ? EventingFunctionDcpBoundary.EVERYTHING : EventingFunctionDcpBoundary.FROM_NOW);
    }
    if (settings.has("description")) {
        settingsBuilder.description(settings.get("description").asText());
    }
    if (settings.has("log_level")) {
        String logLevel = settings.get("log_level").asText();
        if (logLevel.equals(EventingFunctionLogLevel.DEBUG.toString())) {
            settingsBuilder.logLevel(EventingFunctionLogLevel.DEBUG);
        } else if (logLevel.equals(EventingFunctionLogLevel.TRACE.toString())) {
            settingsBuilder.logLevel(EventingFunctionLogLevel.TRACE);
        } else if (logLevel.equals(EventingFunctionLogLevel.INFO.toString())) {
            settingsBuilder.logLevel(EventingFunctionLogLevel.INFO);
        } else if (logLevel.equals(EventingFunctionLogLevel.ERROR.toString())) {
            settingsBuilder.logLevel(EventingFunctionLogLevel.ERROR);
        } else if (logLevel.equals(EventingFunctionLogLevel.WARNING.toString())) {
            settingsBuilder.logLevel(EventingFunctionLogLevel.WARNING);
        }
    }
    if (settings.has("language_compatibility")) {
        String compat = settings.get("language_compatibility").asText();
        if (compat.equals(EventingFunctionLanguageCompatibility.VERSION_6_0_0.toString())) {
            settingsBuilder.languageCompatibility(EventingFunctionLanguageCompatibility.VERSION_6_0_0);
        } else if (compat.equals(EventingFunctionLanguageCompatibility.VERSION_6_5_0.toString())) {
            settingsBuilder.languageCompatibility(EventingFunctionLanguageCompatibility.VERSION_6_5_0);
        } else if (compat.equals(EventingFunctionLanguageCompatibility.VERSION_6_6_2.toString())) {
            settingsBuilder.languageCompatibility(EventingFunctionLanguageCompatibility.VERSION_6_6_2);
        }
    }
    if (settings.has("lcb_inst_capacity")) {
        settingsBuilder.lcbInstCapacity(settings.get("lcb_inst_capacity").asLong());
    }
    if (settings.has("lcb_retry_count")) {
        settingsBuilder.lcbRetryCount(settings.get("lcb_retry_count").asLong());
    }
    if (settings.has("num_timer_partitions")) {
        settingsBuilder.numTimerPartitions(settings.get("num_timer_partitions").asLong());
    }
    if (settings.has("sock_batch_size")) {
        settingsBuilder.sockBatchSize(settings.get("sock_batch_size").asLong());
    }
    if (settings.has("tick_duration")) {
        settingsBuilder.tickDuration(Duration.ofMillis(settings.get("tick_duration").asLong()));
    }
    if (settings.has("timer_context_size")) {
        settingsBuilder.timerContextSize(settings.get("timer_context_size").asLong());
    }
    if (settings.has("bucket_cache_size")) {
        settingsBuilder.bucketCacheSize(settings.get("bucket_cache_size").asLong());
    }
    if (settings.has("bucket_cache_age")) {
        settingsBuilder.bucketCacheAge(settings.get("bucket_cache_age").asLong());
    }
    if (settings.has("curl_max_allowed_resp_size")) {
        settingsBuilder.curlMaxAllowedRespSize(settings.get("curl_max_allowed_resp_size").asLong());
    }
    if (settings.has("worker_count")) {
        settingsBuilder.workerCount(settings.get("worker_count").asLong());
    }
    if (settings.has("app_log_max_size")) {
        settingsBuilder.appLogMaxSize(settings.get("app_log_max_size").asLong());
    }
    if (settings.has("app_log_max_files")) {
        settingsBuilder.appLogMaxFiles(settings.get("app_log_max_files").asLong());
    }
    if (settings.has("checkpoint_interval")) {
        settingsBuilder.checkpointInterval(Duration.ofSeconds(settings.get("checkpoint_interval").asLong()));
    }
    if (settings.has("execution_timeout")) {
        settingsBuilder.executionTimeout(Duration.ofSeconds(settings.get("execution_timeout").asLong()));
    }
    if (settings.has("lcb_timeout")) {
        settingsBuilder.lcbTimeout(Duration.ofSeconds(settings.get("lcb_timeout").asLong()));
    }
    if (settings.has("user_prefix")) {
        settingsBuilder.userPrefix(settings.get("user_prefix").asText());
    }
    if (settings.has("app_log_dir")) {
        settingsBuilder.appLogDir(settings.get("app_log_dir").asText());
    }
    if (settings.has("n1ql_prepare_all")) {
        settingsBuilder.queryPrepareAll(settings.get("n1ql_prepare_all").asBoolean());
    }
    if (settings.has("enable_applog_rotation")) {
        settingsBuilder.enableAppLogRotation(settings.get("enable_applog_rotation").asBoolean());
    }
    if (settings.has("n1ql_consistency")) {
        if ("request".equals(settings.get("n1ql_consistency").asText())) {
            settingsBuilder.queryConsistency(QueryScanConsistency.REQUEST_PLUS);
        } else {
            settingsBuilder.queryConsistency(QueryScanConsistency.NOT_BOUNDED);
        }
    }
    if (settings.has("handler_headers")) {
        List<String> headers = new ArrayList<>();
        for (JsonNode entry : settings.get("handler_headers")) {
            headers.add(entry.asText());
        }
        settingsBuilder.handlerHeaders(headers);
    }
    if (settings.has("handler_footers")) {
        List<String> footers = new ArrayList<>();
        for (JsonNode entry : settings.get("handler_footers")) {
            footers.add(entry.asText());
        }
        settingsBuilder.handlerFooters(footers);
    }
    if (depcfg.has("buckets")) {
        List<EventingFunctionBucketBinding> bucketBindings = new ArrayList<>();
        for (JsonNode buckets : depcfg.get("buckets")) {
            String alias = buckets.get("alias").asText();
            EventingFunctionKeyspace keyspace = EventingFunctionKeyspace.create(buckets.get("bucket_name").asText(), buckets.get("scope_name").asText(), buckets.get("collection_name").asText());
            if ("rw".equals(buckets.get("access").asText())) {
                bucketBindings.add(EventingFunctionBucketBinding.createReadWrite(alias, keyspace));
            } else {
                bucketBindings.add(EventingFunctionBucketBinding.createReadOnly(alias, keyspace));
            }
        }
        toReturn.bucketBindings(bucketBindings);
    }
    if (depcfg.has("constants")) {
        List<EventingFunctionConstantBinding> constantBindings = new ArrayList<>();
        for (JsonNode constants : depcfg.get("constants")) {
            constantBindings.add(EventingFunctionConstantBinding.create(constants.get("value").asText(), constants.get("literal").asText()));
        }
        toReturn.constantBindings(constantBindings);
    }
    if (depcfg.has("curl")) {
        List<EventingFunctionUrlBinding> urlBindings = new ArrayList<>();
        for (JsonNode url : depcfg.get("curl")) {
            EventingFunctionUrlBinding.Builder binding = EventingFunctionUrlBinding.builder(url.get("hostname").asText(), url.get("value").asText());
            if (url.has("allow_cookies")) {
                binding.allowCookies(url.get("allow_cookies").asBoolean());
            }
            if (url.has("validate_ssl_certificate")) {
                binding.validateSslCertificate(url.get("validate_ssl_certificate").asBoolean());
            }
            if (url.has("auth_type")) {
                switch(url.get("auth_type").asText()) {
                    case "no-auth":
                        binding.auth(new EventingFunctionUrlNoAuth());
                        break;
                    case "basic":
                        binding.auth(new EventingFunctionUrlAuthBasic(url.get("username").asText(), null));
                        break;
                    case "digest":
                        binding.auth(new EventingFunctionUrlAuthDigest(url.get("username").asText(), null));
                        break;
                    case "bearer":
                        binding.auth(new EventingFunctionUrlAuthBearer(url.get("bearer_key").asText()));
                        break;
                }
            }
            urlBindings.add(binding.build());
        }
        toReturn.urlBindings(urlBindings);
    }
    return toReturn.settings(settingsBuilder.build()).build();
}
Also used : ArrayList(java.util.ArrayList) JsonNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode) InvalidArgumentException(com.couchbase.client.core.error.InvalidArgumentException)

Aggregations

JsonNode (com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode)12 ArrayList (java.util.ArrayList)5 CoreHttpClient (com.couchbase.client.core.endpoint.http.CoreHttpClient)2 CouchbaseException (com.couchbase.client.core.error.CouchbaseException)2 InvalidArgumentException (com.couchbase.client.core.error.InvalidArgumentException)2 Map (java.util.Map)2 Core (com.couchbase.client.core.Core)1 CbTracing (com.couchbase.client.core.cnc.CbTracing)1 RequestSpan (com.couchbase.client.core.cnc.RequestSpan)1 TracingIdentifiers (com.couchbase.client.core.cnc.TracingIdentifiers)1 TypeReference (com.couchbase.client.core.deps.com.fasterxml.jackson.core.type.TypeReference)1 ObjectNode (com.couchbase.client.core.deps.com.fasterxml.jackson.databind.node.ObjectNode)1 HttpHeaderNames (com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpHeaderNames)1 CoreHttpPath.path (com.couchbase.client.core.endpoint.http.CoreHttpPath.path)1 CoreHttpResponse (com.couchbase.client.core.endpoint.http.CoreHttpResponse)1 AuthenticationFailureException (com.couchbase.client.core.error.AuthenticationFailureException)1 FeatureNotAvailableException (com.couchbase.client.core.error.FeatureNotAvailableException)1 IndexNotFoundException (com.couchbase.client.core.error.IndexNotFoundException)1 Mapper (com.couchbase.client.core.json.Mapper)1 RequestTarget (com.couchbase.client.core.msg.RequestTarget)1