Java Code Examples for com.couchbase.client.core.message.ResponseStatus

The following examples show how to use com.couchbase.client.core.message.ResponseStatus. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Initialize this parser for a response parsing cycle.
 *
 *
 * @param responseContent the raw content to parse from.
 * @param responseStatus the status of the response.
 * @param request the original request.
 */
public void initialize(final ByteBuf responseContent, final ResponseStatus responseStatus,
                       final CouchbaseRequest request) {
    this.requestID = "";
    this.clientContextID = ""; //initialize to empty string instead of null as it is optional on the wire
    this.handle = "";
    this.sentResponse = false;
    this.response = null;
    this.status = responseStatus;
    this.responseContent = responseContent;
    this.currentRequest = request;

    queryRowObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    queryErrorObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    queryStatusObservable = AsyncSubject.create();
    queryInfoObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    querySignatureObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    queryProfileInfoObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);

    parser.initialize(responseContent);
    initialized = true;
}
 
Example 2
Source Project: couchbase-jvm-core   Source File: ConfigHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Decodes a {@link BucketStreamingResponse}.
 *
 * @param ctx the handler context.
 * @param header the received header.
 * @return a initialized {@link CouchbaseResponse}.
 */
private CouchbaseResponse handleBucketStreamingResponse(final ChannelHandlerContext ctx,
    final HttpResponse header) {
    SocketAddress addr = ctx.channel().remoteAddress();
    String host = addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getAddress().getHostAddress()
        : addr.toString();
    ResponseStatus status = ResponseStatusConverter.fromHttp(header.getStatus().code());

    Observable<String> scheduledObservable = null;
    if (status.isSuccess()) {
        streamingConfigObservable = BehaviorSubject.create();
        scheduledObservable = streamingConfigObservable.onBackpressureBuffer().observeOn(env().scheduler());
    }
    return new BucketStreamingResponse(
        scheduledObservable,
        host,
        status,
        currentRequest()
    );
}
 
Example 3
/**
 * Initialize this parser for a response parsing cycle.
 *
 *
 * @param responseContent the raw content to parse from.
 * @param responseStatus the status of the response.
 * @param request the original request.
 */
public void initialize(final ByteBuf responseContent, final ResponseStatus responseStatus,
    final CouchbaseRequest request) {
    this.requestID = "";
    this.clientContextID = ""; //initialize to empty string instead of null as it is optional on the wire
    this.sentResponse = false;
    this.response = null;
    this.status = responseStatus;
    this.responseContent = responseContent;
    this.currentRequest = request;

    queryRowObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    queryErrorObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    queryStatusObservable = AsyncSubject.create();
    queryInfoObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    querySignatureObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    queryProfileInfoObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);

    parser.initialize(responseContent);
    initialized = true;
}
 
Example 4
@Test
public void shouldFailOnInsertDocumentIfSetOnDocExists() {
    String subPath = "hello";
    ByteBuf fragment = Unpooled.copiedBuffer("\"world\"", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);

    SubDictAddRequest insertRequest = new SubDictAddRequest("shouldFailOnInsertDocumentIfSetOnDocExists", subPath, fragment, bucket());
    insertRequest.insertDocument(true);
    SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single();
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertTrue(insertResponse.status().isSuccess());
    SubDictAddRequest insertRequest2 = new SubDictAddRequest("shouldFailOnInsertDocumentIfSetOnDocExists", subPath, Unpooled.EMPTY_BUFFER, bucket());
    insertRequest2.insertDocument(false);
    SimpleSubdocResponse insertResponse2 = cluster().<SimpleSubdocResponse>send(insertRequest2).toBlocking().single();
    ReferenceCountUtil.releaseLater(insertResponse2.content());
    assertFalse(insertResponse2.status().isSuccess());
    RemoveResponse removeResponse = cluster().<RemoveResponse>send(new RemoveRequest("shouldFailOnInsertDocumentIfSetOnDocExists", bucket())).toBlocking().single();
    assertEquals(removeResponse.status(), ResponseStatus.SUCCESS);
}
 
Example 5
@Test
public void shouldAccessDeletedDocumentIfSet() {
    assumeTrue(!useMock());

    String subPath = "_hello";
    ByteBuf fragment = Unpooled.copiedBuffer("\"world\"", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);

    SubDictAddRequest insertRequest = new SubDictAddRequest("shouldAccessDeletedDocumentIfSet", subPath, fragment, bucket());
    insertRequest.upsertDocument(true);
    insertRequest.xattr(true);
    insertRequest.createIntermediaryPath(true);
    SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single();
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertTrue(insertResponse.status().isSuccess());
    RemoveResponse response = cluster().<RemoveResponse>send(new RemoveRequest("shouldAccessDeletedDocumentIfSet", bucket())).toBlocking().single();
    assertEquals(response.status(), ResponseStatus.SUCCESS);

    SubGetRequest getRequest = new SubGetRequest("shouldAccessDeletedDocumentIfSet", subPath, bucket());
    getRequest.xattr(true);
    getRequest.accessDeleted(true);
    SimpleSubdocResponse getResponse = cluster().<SimpleSubdocResponse>send(getRequest).toBlocking().single();
    assertEquals(getResponse.status(), ResponseStatus.SUCCESS);
}
 
Example 6
Source Project: couchbase-jvm-core   Source File: ConfigHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeInitialBucketStreamingResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));

    BucketStreamingRequest requestMock = mock(BucketStreamingRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader);

    assertEquals(1, eventSink.responseEvents().size());
    BucketStreamingResponse event = (BucketStreamingResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertNotNull(event.configs());
    assertNotNull(event.host());
    assertEquals(0, requestQueue.size());
    ReferenceCountUtil.releaseLater(event);
    ReferenceCountUtil.releaseLater(responseHeader);
}
 
Example 7
Source Project: couchbase-jvm-core   Source File: SubdocumentMessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteExistingObjectPath() {
    String path = "sub.value";

    SubDeleteRequest request = new SubDeleteRequest(testSubKey, path, bucket());
    SimpleSubdocResponse response = cluster().<SimpleSubdocResponse>send(request).toBlocking().single();
    ReferenceCountUtil.releaseLater(response.content());

    assertTrue(response.status().isSuccess());
    assertEquals(0, response.content().readableBytes());
    assertEquals(ResponseStatus.SUCCESS, response.status());

    //assert the mutation
    String expected = "{\"value\":\"stringValue\", \"sub\": {\"array\": [\"array1\", 2, true]}}";
    assertMutation(testSubKey, expected);
}
 
Example 8
Source Project: couchbase-jvm-core   Source File: SubdocumentMessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceValueInSubObject() {
    String path = "sub.value";
    ByteBuf fragment = Unpooled.copiedBuffer("\"mutated\"", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);

    SubReplaceRequest request = new SubReplaceRequest(testSubKey, path, fragment, bucket());
    SimpleSubdocResponse response = cluster().<SimpleSubdocResponse>send(request).toBlocking().single();
    ReferenceCountUtil.releaseLater(response.content());

    assertTrue(response.status().isSuccess());
    assertEquals(0, response.content().readableBytes());
    assertEquals(ResponseStatus.SUCCESS, response.status());

    //assert the mutation
    String expected = "{\"value\":\"stringValue\", \"sub\": {\"value\": \"mutated\",\"array\": [\"array1\", 2, true]}}";
    assertMutation(testSubKey, expected);
}
 
Example 9
Source Project: couchbase-jvm-core   Source File: CarrierLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUsePortsFromConfigIfPresentWithoutAlternateNetwork() {
    ClusterFacade cluster = mock(ClusterFacade.class);
    CarrierLoader loader = new CarrierLoader(cluster, environment);

    ClusterConfig clusterConfig = new DefaultClusterConfig();

    String raw = Resources.read("config_with_external.json", DefaultCouchbaseBucketConfigTest.class);
    CouchbaseBucketConfig config = (CouchbaseBucketConfig)
        BucketConfigParser.parse(raw, mock(CoreEnvironment.class), "127.0.0.1");

    clusterConfig.setBucketConfig("foo", config);

    when(cluster.send(any(GetClusterConfigRequest.class))).thenReturn(Observable.just(
        (CouchbaseResponse) new GetClusterConfigResponse(clusterConfig, ResponseStatus.SUCCESS)
    ));

    assertEquals(11210, loader.port("172.17.0.2"));
}
 
Example 10
Source Project: couchbase-jvm-core   Source File: AbstractLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLoadConfigForOneSeedNode() {
    ClusterFacade cluster = mock(ClusterFacade.class);
    when(cluster.send(isA(AddNodeRequest.class))).thenReturn(
            Observable.just((CouchbaseResponse) new AddNodeResponse(ResponseStatus.SUCCESS, host))
    );
    when(cluster.send(isA(AddServiceRequest.class))).thenReturn(
            Observable.just((CouchbaseResponse) new AddServiceResponse(ResponseStatus.SUCCESS, host))
    );
    when(cluster.send(any(GetClusterConfigRequest.class))).thenReturn(Observable.just(
        (CouchbaseResponse) new GetClusterConfigResponse(new DefaultClusterConfig(), ResponseStatus.SUCCESS)
    ));

    InstrumentedLoader loader = new InstrumentedLoader(99, localhostConfig, cluster, environment);
    Observable<Tuple2<LoaderType, BucketConfig>> configObservable =
        loader.loadConfig(host, "default", "password");

    BucketConfig loadedConfig = configObservable.toBlocking().single().value2();
    assertEquals("default", loadedConfig.name());
    assertEquals(1, loadedConfig.nodes().size());
}
 
Example 11
Source Project: couchbase-jvm-core   Source File: ConfigHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeListDesignDocumentsResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CharsetUtil.UTF_8));
    HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CharsetUtil.UTF_8));

    GetDesignDocumentsRequest requestMock = mock(GetDesignDocumentsRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);

    assertEquals(1, eventSink.responseEvents().size());
    GetDesignDocumentsResponse event = (GetDesignDocumentsResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("foobar", event.content());
    assertTrue(requestQueue.isEmpty());
}
 
Example 12
Source Project: couchbase-jvm-core   Source File: HttpLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUsePortsFromConfigIfPresentWithAlternateNetwork() {
    ClusterFacade cluster = mock(ClusterFacade.class);
    HttpLoader loader = new HttpLoader(cluster, environment);

    ClusterConfig clusterConfig = new DefaultClusterConfig();

    String raw = Resources.read("config_with_external.json", DefaultCouchbaseBucketConfigTest.class);
    CouchbaseBucketConfig config = (CouchbaseBucketConfig)
        BucketConfigParser.parse(raw, mock(CoreEnvironment.class), "127.0.0.1");

    config.useAlternateNetwork("external");

    clusterConfig.setBucketConfig("foo", config);

    when(cluster.send(any(GetClusterConfigRequest.class))).thenReturn(Observable.just(
        (CouchbaseResponse) new GetClusterConfigResponse(clusterConfig, ResponseStatus.SUCCESS)
    ));

    assertEquals(32790, loader.port("172.17.0.2"));
}
 
Example 13
Source Project: couchbase-jvm-core   Source File: SubdocumentMessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddUniqueIfValueNotAlreadyInArray() {
    SubArrayRequest.ArrayOperation arrayOp = SubArrayRequest.ArrayOperation.ADD_UNIQUE;
    String path = "sub.array";

    ByteBuf fragment = Unpooled.copiedBuffer("99", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);

    SubArrayRequest request = new SubArrayRequest(testSubKey, path, arrayOp, fragment, bucket());
    SimpleSubdocResponse response = cluster().<SimpleSubdocResponse>send(request).toBlocking().single();

    assertEquals(ResponseStatus.SUCCESS, response.status());
    String expected = useMock()
        ? jsonContent.replace("[", "[99, ")
        : jsonContent.replace("]", ", 99]");
    assertMutation(testSubKey, expected);
}
 
Example 14
Source Project: couchbase-jvm-core   Source File: ResponseHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSendProposedConfigToProvider() throws Exception {
    ClusterFacade clusterMock = mock(ClusterFacade.class);
    ConfigurationProvider providerMock = mock(ConfigurationProvider.class);
    ResponseHandler handler = new ResponseHandler(ENVIRONMENT, clusterMock, providerMock);
    ByteBuf config = Unpooled.copiedBuffer("{\"json\": true}", CharsetUtil.UTF_8);

    ResponseEvent retryEvent = new ResponseEvent();
    retryEvent.setMessage(new InsertResponse(ResponseStatus.RETRY, KeyValueStatus.ERR_TEMP_FAIL.code(),
            0, "bucket", config, null, mock(InsertRequest.class)));
    retryEvent.setObservable(mock(Subject.class));
    handler.onEvent(retryEvent, 1, true);

    ProposedBucketConfigContext ctx = new ProposedBucketConfigContext("bucket", "{\"json\": true}", null);
    verify(providerMock, times(1)).proposeBucketConfig(ctx);
    assertEquals(0, config.refCnt());
    assertNull(retryEvent.getMessage());
    assertNull(retryEvent.getObservable());
}
 
Example 15
Source Project: couchbase-jvm-core   Source File: SubdocumentMessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHaveIndividualResultsOnFullySuccessfulMultiLookup() {
    String expected = "EXIST(sub): SUCCESS\n" +
            "GET(sub.array[1]): SUCCESS = 2\n";

    SubMultiLookupRequest request = new SubMultiLookupRequest(testSubKey, bucket(),
            new LookupCommandBuilder(Lookup.EXIST, "sub").build(),
            new LookupCommandBuilder(Lookup.GET, "sub.array[1]").build());

    MultiLookupResponse response = cluster().<MultiLookupResponse>send(request).toBlocking().single();
    assertEquals(Unpooled.EMPTY_BUFFER, response.content());
    StringBuilder body = new StringBuilder();
    for (MultiResult r : response.responses()) {
        body.append(r.toString()).append('\n');
        ReferenceCountUtil.release(r.value());
    }

    assertTrue(response.cas() != 0);
    assertEquals(ResponseStatus.SUCCESS, response.status());
    assertEquals(expected, body.toString());
}
 
Example 16
Source Project: couchbase-jvm-core   Source File: ConfigHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeFlushNotEnabledResponse() throws Exception {
    String content = "{\"_\":\"Flush is disabled for the bucket\"}";
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
        new HttpResponseStatus(400, "Bad Request"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));

    FlushRequest requestMock = mock(FlushRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk);

    assertEquals(1, eventSink.responseEvents().size());
    FlushResponse event = (FlushResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.INVALID_ARGUMENTS, event.status());
    assertEquals("{\"_\":\"Flush is disabled for the bucket\"}", event.content());
    assertTrue(requestQueue.isEmpty());
}
 
Example 17
Source Project: couchbase-jvm-core   Source File: KeyValueMessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleDoubleInsert() throws Exception {
    String key = "insert-key";
    String content = "Hello World!";
    InsertRequest insert = new InsertRequest(key, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8), bucket());
    InsertResponse insertResponse = cluster().<InsertResponse>send(insert).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, insertResponse.status());
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertValidMetadata(insertResponse.mutationToken());

    insert = new InsertRequest(key, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8), bucket());
    insertResponse = cluster().<InsertResponse>send(insert).toBlocking().single();
    assertEquals(ResponseStatus.EXISTS, insertResponse.status());
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertNull(insertResponse.mutationToken());
}
 
Example 18
Source Project: couchbase-jvm-core   Source File: KeyValueMessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRemoveDocumentWithoutCAS() throws Exception {
    String key = "remove-key";
    String content = "Hello World!";
    UpsertRequest upsert = new UpsertRequest(key, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8), bucket());
    UpsertResponse upsertResponse = cluster().<UpsertResponse>send(upsert).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, upsertResponse.status());
    ReferenceCountUtil.releaseLater(upsertResponse.content());
    assertValidMetadata(upsertResponse.mutationToken());

    RemoveRequest remove = new RemoveRequest(key, bucket());
    RemoveResponse response = cluster().<RemoveResponse>send(remove).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, response.status());
    assertTrue(response.cas() != upsertResponse.cas());
    ReferenceCountUtil.releaseLater(response.content());
    assertValidMetadata(response.mutationToken());
    assertMetadataSequence(upsertResponse.mutationToken(), response.mutationToken());

    GetRequest get = new GetRequest(key, bucket());
    GetResponse getResponse = cluster().<GetResponse>send(get).toBlocking().single();
    assertEquals(ResponseStatus.NOT_EXISTS, getResponse.status());
    ReferenceCountUtil.releaseLater(getResponse.content());
}
 
Example 19
Source Project: couchbase-jvm-core   Source File: KeyValueHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeObserveResponseDuringRebalance() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("{someconfig...}", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(new byte[] {}, Unpooled.EMPTY_BUFFER,
        content.copy());
    response.setStatus(KeyValueStatus.ERR_NOT_MY_VBUCKET.code());

    ObserveRequest requestMock = mock(ObserveRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(response);

    assertEquals(1, eventSink.responseEvents().size());
    ObserveResponse event = (ObserveResponse) eventSink.responseEvents().get(0).getMessage();
    assertEquals(ResponseStatus.RETRY, event.status());
    assertEquals(ObserveResponse.ObserveStatus.UNKNOWN, event.observeStatus());
}
 
Example 20
Source Project: couchbase-jvm-core   Source File: KeyValueMessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTouch() throws Exception {
    String key = "touch";

    UpsertRequest request = new UpsertRequest(key, Unpooled.copiedBuffer("content", CharsetUtil.UTF_8), 3, 0, bucket());
    UpsertResponse response = cluster().<UpsertResponse>send(request).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, response.status());
    ReferenceCountUtil.releaseLater(response.content());

    Thread.sleep(2000);

    TouchResponse touchResponse = cluster().<TouchResponse>send(new TouchRequest(key, 3, bucket())).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, touchResponse.status());
    ReferenceCountUtil.releaseLater(touchResponse.content());

    Thread.sleep(2000);

    GetResponse getResponse = cluster().<GetResponse>send(new GetRequest(key, bucket())).toBlocking().single();
    assertEquals(ResponseStatus.SUCCESS, getResponse.status());
    assertEquals("content", getResponse.content().toString(CharsetUtil.UTF_8));
    ReferenceCountUtil.releaseLater(getResponse.content());
}
 
Example 21
Source Project: couchbase-jvm-core   Source File: HttpLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUsePortsFromConfigIfPresentWithoutAlternateNetwork() {
    ClusterFacade cluster = mock(ClusterFacade.class);
    HttpLoader loader = new HttpLoader(cluster, environment);

    ClusterConfig clusterConfig = new DefaultClusterConfig();

    String raw = Resources.read("config_with_external.json", DefaultCouchbaseBucketConfigTest.class);
    CouchbaseBucketConfig config = (CouchbaseBucketConfig)
        BucketConfigParser.parse(raw, mock(CoreEnvironment.class), "127.0.0.1");

    clusterConfig.setBucketConfig("foo", config);

    when(cluster.send(any(GetClusterConfigRequest.class))).thenReturn(Observable.just(
        (CouchbaseResponse) new GetClusterConfigResponse(clusterConfig, ResponseStatus.SUCCESS)
    ));

    assertEquals(8091, loader.port("172.17.0.2"));
}
 
Example 22
Source Project: couchbase-jvm-core   Source File: ConfigHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeNotFoundBucketConfigResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
        new HttpResponseStatus(404, "Object Not Found"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer("Not found.", CharsetUtil.UTF_8));

    BucketConfigRequest requestMock = mock(BucketConfigRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk);

    assertEquals(1, eventSink.responseEvents().size());
    BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.NOT_EXISTS, event.status());
    assertEquals("Not found.", event.config());
    assertTrue(requestQueue.isEmpty());
}
 
Example 23
Source Project: couchbase-jvm-core   Source File: ViewHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link ViewQueryResponse} from its request based on the returned info.
 *
 * Note that observables are attached to this response which are completed later in the response cycle.
 *
 * @return the initial response.
 */
private CouchbaseResponse handleViewQueryResponse() {
    int code = responseHeader.getStatus().code();
    String phrase = responseHeader.getStatus().reasonPhrase();
    ResponseStatus status = ResponseStatusConverter.fromHttp(responseHeader.getStatus().code());
    Scheduler scheduler = env().scheduler();
    long ttl = env().autoreleaseAfter();
    viewRowObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    viewInfoObservable = UnicastAutoReleaseSubject.create(ttl, TimeUnit.MILLISECONDS, scheduler);
    viewErrorObservable = AsyncSubject.create();

    //set up trace ids on all these UnicastAutoReleaseSubjects, so that if they get in a bad state
    // (multiple subscribers or subscriber coming in too late) we can trace back to here
    viewRowObservable.withTraceIdentifier("viewRow");
    viewInfoObservable.withTraceIdentifier("viewInfo");

    return new ViewQueryResponse(
        viewRowObservable.onBackpressureBuffer().observeOn(scheduler),
        viewInfoObservable.onBackpressureBuffer().observeOn(scheduler),
        viewErrorObservable.observeOn(scheduler),
        code,
        phrase,
        status,
        currentRequest()
    );
}
 
Example 24
Source Project: couchbase-jvm-core   Source File: ConfigHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecodeSuccessBucketConfigResponse() throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultHttpContent(Unpooled.copiedBuffer("foo", CHARSET));
    HttpContent responseChunk2 = new DefaultLastHttpContent(Unpooled.copiedBuffer("bar", CHARSET));

    BucketConfigRequest requestMock = mock(BucketConfigRequest.class);
    requestQueue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk1, responseChunk2);
    channel.readInbound();

    assertEquals(1, eventSink.responseEvents().size());
    BucketConfigResponse event = (BucketConfigResponse) eventSink.responseEvents().get(0).getMessage();

    assertEquals(ResponseStatus.SUCCESS, event.status());
    assertEquals("foobar", event.config());
    assertTrue(requestQueue.isEmpty());
}
 
Example 25
Source Project: couchbase-jvm-core   Source File: BucketLifecycleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSucceedSubsequentlyAfterFailedAttempt() throws Exception {
    final CouchbaseCore core = new CouchbaseCore(ENV);

    core.send(new SeedNodesRequest(Arrays.asList(TestProperties.seedNode())));

    OpenBucketRequest badAttempt = new OpenBucketRequest(TestProperties.bucket() + "asd", TestProperties.username(), TestProperties.password());

    final OpenBucketRequest goodAttempt;
    if (ClusterDependentTest.minClusterVersion()[0] >= 5) {
        goodAttempt = new OpenBucketRequest(TestProperties.bucket(), TestProperties.adminUser(), TestProperties.adminPassword());
    } else {
        goodAttempt = new OpenBucketRequest(TestProperties.bucket(), TestProperties.username(), TestProperties.password());

    }

    OpenBucketResponse response = core
        .<OpenBucketResponse>send(badAttempt)
        .onErrorResumeNext(Observable.defer(new Func0<Observable<OpenBucketResponse>>() {
            @Override
            public Observable<OpenBucketResponse> call() {
                return core.send(goodAttempt);
            }
        }))
        .timeout(10, TimeUnit.SECONDS)
        .toBlocking()
        .single();

    assertEquals(ResponseStatus.SUCCESS, response.status());
    core.send(new CloseBucketRequest(TestProperties.bucket())).toBlocking().single();
}
 
Example 26
@Test
public void shouldUpsertDocumentIfSetWithExpiryAndPathFlags() {
    String subPath = "first.hello";
    ByteBuf fragment = Unpooled.copiedBuffer("\"world\"", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);
    SubDictAddRequest insertRequest = new SubDictAddRequest("shouldUpsertDocumentIfSetWithExpiryAndPathFlags", subPath, fragment, bucket(), 10, 0);
    insertRequest.upsertDocument(true);
    insertRequest.createIntermediaryPath(true);
    SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single();
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertTrue(insertResponse.status().isSuccess());
    RemoveResponse response = cluster().<RemoveResponse>send(new RemoveRequest("shouldUpsertDocumentIfSetWithExpiryAndPathFlags", bucket())).toBlocking().single();
    assertEquals(response.status(), ResponseStatus.SUCCESS);
}
 
Example 27
@Test
public void shouldFailIfUpsertDocumentIsNotSetWhenDocumentDoesNotExist() {
    String subPath = "hello";
    ByteBuf fragment = Unpooled.copiedBuffer("\"world\"", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);
    SubDictAddRequest insertRequest = new SubDictAddRequest("shouldFailIfUpsertDocumentIsNotSetWhenDocumentDoesNotExist", subPath, fragment, bucket());
    SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single();
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertEquals(insertResponse.status(), ResponseStatus.NOT_EXISTS);
}
 
Example 28
@Test
public void shouldInsertDocumentIfSet() {
    String subPath = "hello";
    ByteBuf fragment = Unpooled.copiedBuffer("\"world\"", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);

    SubDictAddRequest insertRequest = new SubDictAddRequest("shouldInsertDocumentIfSet", subPath, fragment, bucket());
    insertRequest.insertDocument(true);
    SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single();
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertTrue(insertResponse.status().isSuccess());
    RemoveResponse response = cluster().<RemoveResponse>send(new RemoveRequest("shouldInsertDocumentIfSet", bucket())).toBlocking().single();
    assertEquals(response.status(), ResponseStatus.SUCCESS);
}
 
Example 29
Source Project: couchbase-jvm-core   Source File: SubdocumentMessageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSucceedExistOnArrayPath() {
    String path = "sub.array[1]";

    SubExistRequest request = new SubExistRequest(testSubKey, path, bucket());
    SimpleSubdocResponse response = cluster().<SimpleSubdocResponse>send(request).toBlocking().single();

    assertEquals(ResponseStatus.SUCCESS, response.status());
}
 
Example 30
Source Project: couchbase-jvm-core   Source File: CarrierRefresherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotRefreshWithInvalidClusterConfig() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    CarrierRefresher refresher = new CarrierRefresher(ENVIRONMENT, cluster);
    refresher.registerBucket("bucket", "");
    ConfigurationProvider provider = mock(ConfigurationProvider.class);
    refresher.provider(provider);

    ClusterConfig clusterConfig = mock(ClusterConfig.class);
    BucketConfig bucketConfig = mock(BucketConfig.class);
    when(bucketConfig.name()).thenReturn("bucket");
    List<NodeInfo> nodeInfos = new ArrayList<NodeInfo>();

    Map<String, Integer> ports = new HashMap<String, Integer>();
    ports.put("direct", 11210);
    nodeInfos.add(new DefaultNodeInfo(null, "localhost:8091", ports, null));
    when(bucketConfig.nodes()).thenReturn(nodeInfos);
    Map<String, BucketConfig> bucketConfigs = new HashMap<String, BucketConfig>();
    bucketConfigs.put("bucket", bucketConfig);

    when(clusterConfig.bucketConfigs()).thenReturn(bucketConfigs);

    ByteBuf content = Unpooled.copiedBuffer("", CharsetUtil.UTF_8);
    when(cluster.send(any(GetBucketConfigRequest.class))).thenReturn(Observable.just(
        (CouchbaseResponse) new GetBucketConfigResponse(
            ResponseStatus.FAILURE, KeyValueStatus.ERR_NOT_FOUND.code(),
            "bucket",
            content,
            "127.0.0.1"
        )
    ));

    refresher.refresh(clusterConfig);

    Thread.sleep(200);

    ProposedBucketConfigContext ctx = new ProposedBucketConfigContext("bucket", "", null);
    verify(provider, never()).proposeBucketConfig(ctx);
    assertEquals(0, content.refCnt());
}