Search in sources :

Example 46 with Core

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

the class RequestContextTest method customPayloadCanBeAttached.

@Test
void customPayloadCanBeAttached() {
    Request<?> request = mock(Request.class);
    Core core = mock(Core.class);
    RequestContext ctx = new RequestContext(new CoreContext(core, 1, null, mock(Authenticator.class)), request);
    assertNull(ctx.clientContext());
    Map<String, Object> payload = new HashMap<>();
    payload.put("foo", true);
    ctx.clientContext(payload);
    assertEquals(payload, ctx.clientContext());
}
Also used : CoreContext(com.couchbase.client.core.CoreContext) HashMap(java.util.HashMap) Core(com.couchbase.client.core.Core) Test(org.junit.jupiter.api.Test)

Example 47 with Core

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

the class AsyncScopeTest method shouldReuseAsyncCollection.

@Test
void shouldReuseAsyncCollection() {
    Core core = mock(Core.class);
    ConfigurationProvider configProvider = mock(ConfigurationProvider.class);
    Flux<ClusterConfig> configs = (Flux<ClusterConfig>) mock(Flux.class);
    when(configProvider.configs()).thenReturn(configs);
    when(core.configurationProvider()).thenReturn(configProvider);
    AsyncScope scope = new AsyncScope("scope", "bucket", core, mock(ClusterEnvironment.class));
    AsyncCollection collection1 = scope.defaultCollection();
    AsyncCollection collection2 = scope.defaultCollection();
    AsyncCollection collection3 = scope.collection("foo");
    AsyncCollection collection4 = scope.collection("foo");
    assertEquals(collection1, collection2);
    assertEquals(collection3, collection4);
    assertNotEquals(collection1, collection3);
    assertNotEquals(collection2, collection4);
}
Also used : ClusterEnvironment(com.couchbase.client.java.env.ClusterEnvironment) ConfigurationProvider(com.couchbase.client.core.config.ConfigurationProvider) Flux(reactor.core.publisher.Flux) Core(com.couchbase.client.core.Core) ClusterConfig(com.couchbase.client.core.config.ClusterConfig) Test(org.junit.jupiter.api.Test)

Example 48 with Core

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

the class SearchMock method loadSearchTestCase.

/**
 * Given JSON in the form expected, e.g. those from https://github.com/chvck/sdk-testcases which contains the
 * returned JSON from the search service in a field "data", returns the completed SearchResult that the API
 * would return.
 */
public static SearchResult loadSearchTestCase(InputStream json) throws ExecutionException, InterruptedException, IOException {
    // The idea is to fake packets that have come from the search service.
    // Start by preparing the packets.
    JsonObject jo = JsonObject.fromJson(toByteArray(json));
    JsonObject data = jo.getObject("data");
    byte[] b = data.toString().getBytes(StandardCharsets.UTF_8);
    ByteBuf bytes = Unpooled.wrappedBuffer(b);
    HttpContent content = new DefaultLastHttpContent(bytes);
    HttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    // Fake some core stuff
    Core mockedCore = mock(Core.class);
    CoreEnvironment env = CoreEnvironment.create();
    CoreContext ctx = new CoreContext(mockedCore, 0, env, PasswordAuthenticator.create("Administrator", "password"));
    // Our ChunkedSearchMessageHandler needs to be initialised by pretending we've sent an outbound SearchRequest
    // through it
    SearchRequest req = new SearchRequest(Duration.ofSeconds(10), ctx, BestEffortRetryStrategy.INSTANCE, null, null, null, null);
    // ChunkedSearchMessageHandler will try to encode() the SearchRequest.  Rather than mocking everything required
    // to get that working, just mock the encode method.
    SearchRequest spiedReq = spy(req);
    doReturn(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "localhost")).when(spiedReq).encode();
    doAnswer(v -> {
        EndpointContext endpointContext = new EndpointContext(ctx, new HostAndPort(null, 0), null, null, null, Optional.of("bucket"), null);
        BaseEndpoint endpoint = mock(BaseEndpoint.class);
        when(endpoint.context()).thenReturn(endpointContext);
        when(endpoint.pipelined()).thenReturn(false);
        // ChunkedSearchMessageHandler does most of the work in handling responses from the service
        ChunkedSearchMessageHandler handler = new ChunkedSearchMessageHandler(endpoint, endpointContext);
        // Netty's EmbeddedChannel lets us test ChannelHandlers like ChunkedSearchMessageHandler.  It's a Netty Channel
        // that doesn't touch the network at all.
        final EmbeddedChannel channel = new EmbeddedChannel(handler);
        // Writing the request is necessary to estabish some initial state inChunkedSearchMessageHandler
        channel.writeAndFlush(spiedReq);
        // Finally we can do the interesting bit of passing our fake FTS service response into
        // ChunkedSearchMessageHandler
        channel.writeInbound(resp);
        channel.writeInbound(content);
        return null;
    }).when(mockedCore).send(any());
    CompletableFuture<SearchResult> future = SearchAccessor.searchQueryAsync(mockedCore, req, DefaultJsonSerializer.create());
    SearchResult result = future.get();
    return result;
}
Also used : SearchRequest(com.couchbase.client.core.msg.search.SearchRequest) CoreContext(com.couchbase.client.core.CoreContext) DefaultFullHttpRequest(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultFullHttpRequest) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) EndpointContext(com.couchbase.client.core.endpoint.EndpointContext) JsonObject(com.couchbase.client.java.json.JsonObject) HttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) SearchResult(com.couchbase.client.java.search.result.SearchResult) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) HostAndPort(com.couchbase.client.core.util.HostAndPort) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) BaseEndpoint(com.couchbase.client.core.endpoint.BaseEndpoint) DefaultHttpResponse(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultHttpResponse) DefaultLastHttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.DefaultLastHttpContent) HttpContent(com.couchbase.client.core.deps.io.netty.handler.codec.http.HttpContent) Core(com.couchbase.client.core.Core)

Example 49 with Core

use of com.couchbase.client.core.Core 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)

Aggregations

Core (com.couchbase.client.core.Core)49 CoreContext (com.couchbase.client.core.CoreContext)31 Test (org.junit.jupiter.api.Test)25 CoreEnvironment (com.couchbase.client.core.env.CoreEnvironment)17 Duration (java.time.Duration)13 ArrayList (java.util.ArrayList)12 Map (java.util.Map)12 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)12 Stability (com.couchbase.client.core.annotation.Stability)11 Optional (java.util.Optional)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 BucketConfig (com.couchbase.client.core.config.BucketConfig)10 Authenticator (com.couchbase.client.core.env.Authenticator)10 List (java.util.List)10 Flux (reactor.core.publisher.Flux)10 Mono (reactor.core.publisher.Mono)10 Reactor (com.couchbase.client.core.Reactor)9 SeedNode (com.couchbase.client.core.env.SeedNode)9 CollectionIdentifier (com.couchbase.client.core.io.CollectionIdentifier)9 HashSet (java.util.HashSet)9