Java Code Examples for rx.subjects.AsyncSubject#create()

The following examples show how to use rx.subjects.AsyncSubject#create() . 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
Source File: AbstractOnDemandServiceTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailObservableIfCouldNotConnect() {
    InstrumentedService service = new InstrumentedService(host, bucket, password, port, ctx, factory);

    Endpoint endpoint = mock(Endpoint.class);
    final EndpointStates endpointStates = new EndpointStates(LifecycleState.DISCONNECTED);
    when(endpoint.states()).thenReturn(endpointStates.states());
    when(endpoint.connect()).thenReturn(Observable.just(LifecycleState.DISCONNECTED));
    when(factory.create(host, bucket, bucket, password, port, ctx)).thenReturn(endpoint);

    CouchbaseRequest req = mock(CouchbaseRequest.class);
    AsyncSubject<CouchbaseResponse> reqObservable = AsyncSubject.create();
    when(req.observable()).thenReturn(reqObservable);

    try {
        service.send(req);
        reqObservable.toBlocking().single();
        assertTrue("Should've failed but did not", false);
    } catch(CouchbaseException ex) {
        assertEquals("Could not connect endpoint.", ex.getMessage());
    } catch(Throwable tr) {
        assertTrue(tr.getMessage(), false);
    }
}
 
Example 2
Source File: YasjlAnalyticsResponseParser.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source File: ViewHandler.java    From couchbase-jvm-core with 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 4
Source File: AbstractPoolingServiceTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test(expected = RequestCancelledException.class)
public void shouldCancelRequestOnFailFastStrategy() {
    Endpoint endpoint1 = mock(Endpoint.class);
    EndpointStates e1s = new EndpointStates(LifecycleState.DISCONNECTED);
    when(endpoint1.states()).thenReturn(e1s.states());
    when(endpoint1.connect()).thenReturn(Observable.just(LifecycleState.DISCONNECTED));
    when(endpoint1.disconnect()).thenReturn(Observable.just(LifecycleState.DISCONNECTING));
    CoreEnvironment env = mock(CoreEnvironment.class);
    when(env.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);

    int endpoints = 1;
    SelectionStrategy strategy = mock(SelectionStrategy.class);
    when(strategy.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    CoreContext ctx = new CoreContext(env, null);
    InstrumentedService service = new InstrumentedService(host, bucket, password, port, ctx, endpoints,
            endpoints, strategy, factory);

    CouchbaseRequest request = mock(CouchbaseRequest.class);
    when(request.isActive()).thenReturn(true);
    AsyncSubject<CouchbaseResponse> response = AsyncSubject.create();
    when(request.observable()).thenReturn(response);
    service.send(request);

    response.toBlocking().single();
}
 
Example 5
Source File: RequestHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test(expected = RequestCancelledException.class)
public void shouldCancelOnRetryPolicyFailFast() throws Exception {
    CoreEnvironment env = mock(CoreEnvironment.class);
    when(env.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);
    ClusterConfig mockClusterConfig = mock(ClusterConfig.class);
    when(mockClusterConfig.hasBucket(anyString())).thenReturn(Boolean.TRUE);
    Observable<ClusterConfig> mockConfigObservable = Observable.just(mockClusterConfig);

    CoreContext ctx = new CoreContext(env, null);
    RequestHandler handler = new DummyLocatorClusterNodeHandler(ctx, mockConfigObservable);
    Node mockNode = mock(Node.class);
    when(mockNode.connect()).thenReturn(Observable.just(LifecycleState.DISCONNECTED));
    when(mockNode.state()).thenReturn(LifecycleState.DISCONNECTED);
    handler.addNode(mockNode).toBlocking().single();

    RequestEvent mockEvent = mock(RequestEvent.class);
    CouchbaseRequest mockRequest = mock(CouchbaseRequest.class);
    AsyncSubject<CouchbaseResponse> response = AsyncSubject.create();
    when(mockRequest.isActive()).thenReturn(true);
    when(mockEvent.getRequest()).thenReturn(mockRequest);
    when(mockRequest.observable()).thenReturn(response);
    handler.onEvent(mockEvent, 0, true);

    verify(mockNode, times(1)).send(SignalFlush.INSTANCE);
    verify(mockNode, never()).send(mockRequest);
    verify(mockEvent).setRequest(null);

    response.toBlocking().single();
}
 
Example 6
Source File: ComputationTaskInvoker.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private void drain() {
    if (waitingObservers.isEmpty()) {
        return;
    }

    AsyncSubject<Void> subject = AsyncSubject.create();
    Observable<Void> pending = pendingComputation.get();
    while (pending == null) {
        if (pendingComputation.compareAndSet(null, subject)) {
            pending = subject;
        } else {
            pending = pendingComputation.get();
        }
    }

    if (pending == subject) {
        List<Observer<? super O>> available = new ArrayList<>();
        waitingObservers.drainTo(available);
        computation
                .doOnTerminate(() -> {
                    pendingComputation.set(null);
                    subject.onCompleted();
                })
                .subscribe(
                        next -> doSafely(available, o -> o.onNext(next)),
                        e -> doSafely(available, o -> o.onError(e)),
                        () -> doSafely(available, Observer::onCompleted)
                );
    } else {
        pending.doOnTerminate(() -> worker.schedule(this::drain)).subscribe();
    }
}
 
Example 7
Source File: ObservablesTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
/**
 * Heper method to test fail-safe functionality.
 *
 * @param scheduler the scheduler to test against. if null, it will be failed on the current thread.
 * @param threadName the part of a thread name to match against for additional verification.
 */
private static void testFailSafe(final Scheduler scheduler, final String threadName) {
    Subject<CouchbaseResponse, CouchbaseResponse> subject = AsyncSubject.create();
    TestSubscriber<CouchbaseResponse> subscriber = TestSubscriber.create();
    subject.subscribe(subscriber);
    Exception failure = new CouchbaseException("Some Error");

    Observables.failSafe(scheduler, scheduler != null, subject, failure);

    subscriber.awaitTerminalEvent();
    subscriber.assertError(failure);
    assertTrue(subscriber.getLastSeenThread().getName().contains(threadName));
}
 
Example 8
Source File: AbstractEndpoint.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<LifecycleState> disconnect() {
    disconnected = true;

    if (state() == LifecycleState.DISCONNECTED || state() == LifecycleState.DISCONNECTING) {
        return Observable.just(state());
    }

    if (state() == LifecycleState.CONNECTING) {
        transitionState(LifecycleState.DISCONNECTED);
        return Observable.just(state());
    }

    transitionState(LifecycleState.DISCONNECTING);
    final AsyncSubject<LifecycleState> observable = AsyncSubject.create();
    channel.disconnect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Disconnected Endpoint.");
            } else {
                LOGGER.warn(
                    "{}Received an error during disconnect.",
                    logIdent(channel, AbstractEndpoint.this),
                    future.cause()
                );
            }
            transitionState(LifecycleState.DISCONNECTED);
            observable.onNext(state());
            observable.onCompleted();
            channel = null;
        }
    });
    return observable;
}
 
Example 9
Source File: AbstractOnDemandServiceTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDispatchOnDemand() throws Exception {
    InstrumentedService service = new InstrumentedService(host, bucket, password, port, ctx, factory);

    Endpoint endpoint = mock(Endpoint.class);
    final EndpointStates endpointStates = new EndpointStates(LifecycleState.DISCONNECTED);
    when(endpoint.states()).thenReturn(endpointStates.states());
    when(endpoint.connect()).thenReturn(Observable.just(LifecycleState.CONNECTED));
    when(factory.create(host, bucket, bucket, password, port, ctx)).thenReturn(endpoint);

    assertEquals(0, service.endpoints().size());
    assertEquals(LifecycleState.IDLE, service.connect().toBlocking().single());
    assertEquals(0, service.endpoints().size());

    CouchbaseRequest req = mock(CouchbaseRequest.class);
    AsyncSubject<CouchbaseResponse> reqObservable = AsyncSubject.create();
    when(req.observable()).thenReturn(reqObservable);
    service.send(req);

    endpointStates.transitionState(LifecycleState.CONNECTING);
    endpointStates.transitionState(LifecycleState.CONNECTED);

    verify(endpoint, times(1)).send(req);
    verify(endpoint, times(1)).send(SignalFlush.INSTANCE);

    endpointStates.transitionState(LifecycleState.DISCONNECTED);

    assertEquals(LifecycleState.DISCONNECTED, endpointStates.state());
}
 
Example 10
Source File: WampClient.java    From jawampa with Apache License 2.0 5 votes vote down vote up
/**
 * Publishes an event under the given topic.
 * @param topic The topic that should be used for publishing the event
 * @param flags Additional publish flags if any. This can be null.
 * @param arguments The positional arguments for the published event
 * @param argumentsKw The keyword arguments for the published event.
 * These will only be taken into consideration if arguments is not null.
 * @return An observable that provides a notification whether the event
 * publication was successful. This contains either a single value (the
 * publication ID) and will then be completed or will be completed with
 * an error if the event could not be published.
 */
public Observable<Long> publish(final String topic, final EnumSet<PublishFlags> flags, final ArrayNode arguments,
    final ObjectNode argumentsKw)
{
    final AsyncSubject<Long> resultSubject = AsyncSubject.create();
    
    try {
        UriValidator.validate(topic, clientConfig.useStrictUriValidation());
    }
    catch (WampError e) {
        resultSubject.onError(e);
        return resultSubject;
    }
     
    boolean wasScheduled = stateController.tryScheduleAction(new Runnable() {
        @Override
        public void run() {
            if (!(stateController.currentState() instanceof SessionEstablishedState)) {
                resultSubject.onError(new ApplicationError(ApplicationError.NOT_CONNECTED));
                return;
            }
            // Forward publish into the session
            SessionEstablishedState curState = (SessionEstablishedState)stateController.currentState();
            curState.performPublish(topic, flags, arguments, argumentsKw, resultSubject);
            
        }
    });

    if (!wasScheduled) {
        resultSubject.onError(
            new ApplicationError(ApplicationError.CLIENT_CLOSED));
    }
    return resultSubject;
}
 
Example 11
Source File: DefaultConfigurationProviderTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldDelegateLoadingToSecondProviderIfFirstFails() throws Exception {
    ClusterFacade cluster = mock(ClusterFacade.class);
    Loader successLoader = mock(Loader.class);
    Loader errorLoader = mock(Loader.class);
    BucketConfig bucketConfig = mock(BucketConfig.class);
    when(bucketConfig.name()).thenReturn("bucket");
    when(successLoader.loadConfig(any(String.class), anyString(), anyString(), anyString()))
        .thenReturn(Observable.just(Tuple.create(LoaderType.Carrier, bucketConfig)));
    AsyncSubject<BucketConfig> errorSubject = AsyncSubject.create();
    when(errorLoader.loadConfig(any(String.class), anyString(), anyString(), anyString())).thenReturn((Observable) errorSubject);
    errorSubject.onError(new IllegalStateException());

    final Refresher refresher = mock(Refresher.class);
    when(refresher.configs()).thenReturn(Observable.<ProposedBucketConfigContext>empty());
    when(refresher.registerBucket(anyString(), nullable(String.class), nullable(String.class))).thenReturn(Observable.just(true));

    ConfigurationProvider provider = new DefaultConfigurationProvider(
        cluster,
        environment,
        Arrays.asList(errorLoader, successLoader),
        new HashMap<LoaderType, Refresher>() {{
            put(LoaderType.Carrier, refresher);
            put(LoaderType.HTTP, refresher);
        }}
    );

    provider.seedHosts(Sets.newSet("127.0.0.1"), true);
    Observable<ClusterConfig> configObservable = provider.openBucket("bucket", "password");
    ClusterConfig config = configObservable.toBlocking().first();
    assertTrue(config.hasBucket("bucket"));
    assertFalse(config.hasBucket("other"));
}
 
Example 12
Source File: AbstractLazyServiceTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLazilyCreateAndReuseEndpoint() {
    InstrumentedService service = new InstrumentedService(host, bucket, password, port, ctx, factory);

    Endpoint endpoint = mock(Endpoint.class);
    final EndpointStates endpointStates = new EndpointStates(LifecycleState.DISCONNECTED);
    when(endpoint.states()).thenReturn(endpointStates.states());
    when(endpoint.state()).thenReturn(endpointStates.state());
    when(endpoint.connect()).thenReturn(Observable.just(LifecycleState.CONNECTED));
    when(factory.create(host, bucket, bucket, password, port, ctx)).thenReturn(endpoint);

    assertEquals(0, service.endpoints().size());
    assertEquals(LifecycleState.IDLE, service.connect().toBlocking().single());
    assertEquals(0, service.endpoints().size());

    endpointStates.transitionState(LifecycleState.CONNECTING);
    endpointStates.transitionState(LifecycleState.CONNECTED);

    CouchbaseRequest req = mock(CouchbaseRequest.class);
    AsyncSubject<CouchbaseResponse> reqObservable = AsyncSubject.create();
    when(req.observable()).thenReturn(reqObservable);
    service.send(req);

    verify(endpoint, times(1)).send(req);
    verify(endpoint, times(1)).send(SignalFlush.INSTANCE);

    assertEquals(endpoint, service.endpoint());

    CouchbaseRequest req2 = mock(CouchbaseRequest.class);
    AsyncSubject<CouchbaseResponse> reqObservable2 = AsyncSubject.create();
    when(req2.observable()).thenReturn(reqObservable2);
    service.send(req2);

    assertEquals(endpoint, service.endpoint());
    endpointStates.transitionState(LifecycleState.DISCONNECTED);
    assertNull(service.endpoint());
}
 
Example 13
Source File: ViewHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningDisabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    ViewQueryRequest requestMock1 = mock(ViewQueryRequest.class);
    when(requestMock1.query()).thenReturn("{...}");
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.username()).thenReturn("foo");
    when(requestMock1.password()).thenReturn("");
    when(requestMock1.observable()).thenReturn(obs1);
    when(requestMock1.isActive()).thenReturn(true);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    ViewQueryRequest requestMock2 = mock(ViewQueryRequest.class);
    when(requestMock2.query()).thenReturn("{...}");
    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.username()).thenReturn("foo");
    when(requestMock2.password()).thenReturn("");
    when(requestMock2.observable()).thenReturn(obs2);
    when(requestMock2.isActive()).thenReturn(true);


    TestSubscriber<CouchbaseResponse> t1 = TestSubscriber.create();
    TestSubscriber<CouchbaseResponse> t2 = TestSubscriber.create();

    obs1.subscribe(t1);
    obs2.subscribe(t2);

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertError(RequestCancelledException.class);
}
 
Example 14
Source File: ConfigHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningDisabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    GetDesignDocumentsRequest requestMock1 = mock(GetDesignDocumentsRequest.class);
    when(requestMock1.path()).thenReturn("");
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.username()).thenReturn("foo");
    when(requestMock1.password()).thenReturn("");
    when(requestMock1.observable()).thenReturn(obs1);
    when(requestMock1.isActive()).thenReturn(true);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    GetDesignDocumentsRequest requestMock2 = mock(GetDesignDocumentsRequest.class);
    when(requestMock1.path()).thenReturn("");
    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.username()).thenReturn("foo");
    when(requestMock2.password()).thenReturn("");
    when(requestMock2.observable()).thenReturn(obs2);
    when(requestMock2.isActive()).thenReturn(true);


    TestSubscriber<CouchbaseResponse> t1 = TestSubscriber.create();
    TestSubscriber<CouchbaseResponse> t2 = TestSubscriber.create();

    obs1.subscribe(t1);
    obs2.subscribe(t2);

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertError(RequestCancelledException.class);
}
 
Example 15
Source File: QueryHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldDecodeRawQueryResponseAsSingleJson() throws Exception {
    String response = Resources.read("chunked.json", this.getClass());
    String[] chunks = new String[] {
            response.substring(0, 48),
            response.substring(48, 84),
            response.substring(84, 144),
            response.substring(144, 258),
            response.substring(258, 438),
            response.substring(438, 564),
            response.substring(564, 702),
            response.substring(702, 740),
            response.substring(740)
    };

    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    Object[] httpChunks = new Object[chunks.length + 1];
    httpChunks[0] = responseHeader;
    for (int i = 1; i <= chunks.length; i++) {
        String chunk = chunks[i - 1];
        if (i == chunks.length) {
            httpChunks[i] = new DefaultLastHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8));
        } else {
            httpChunks[i] = new DefaultHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8));
        }
    }

    Subject<CouchbaseResponse,CouchbaseResponse> obs = AsyncSubject.create();
    RawQueryRequest requestMock = mock(RawQueryRequest.class);
    when(requestMock.observable()).thenReturn(obs);
    queue.add(requestMock);
    channel.writeInbound(httpChunks);
    RawQueryResponse inbound = (RawQueryResponse) obs.timeout(1, TimeUnit.SECONDS).toBlocking().last();
    //convert the ByteBuf to String and release before asserting
    String jsonResponse = inbound.jsonResponse().toString(CharsetUtil.UTF_8);
    inbound.jsonResponse().release();

    assertNotNull(inbound);
    assertEquals(ResponseStatus.SUCCESS, inbound.status());
    assertEquals(200, inbound.httpStatusCode());
    assertEquals("OK", inbound.httpStatusMsg());

    assertEquals(response, jsonResponse);
}
 
Example 16
Source File: TestCouchbaseTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static CouchbaseConnector getConnector(Class responseClass) throws Exception {
  ENV = DefaultCouchbaseEnvironment.create();

  CouchbaseCore core = mock(CouchbaseCore.class);
  CouchbaseAsyncBucket asyncBucket = new CouchbaseAsyncBucket(core,
      ENV,
      BUCKET,
      USERNAME,
      PASSWORD,
      Collections.emptyList()
  );

  final CouchbaseRequest requestMock = mock(CouchbaseRequest.class);

  Subject<CouchbaseResponse, CouchbaseResponse> response = AsyncSubject.create();

  if(responseClass == SimpleSubdocResponse.class) {
    final BinarySubdocRequest subdocRequestMock = mock(BinarySubdocRequest.class);
    when(subdocRequestMock.span()).thenReturn(mock(Span.class));

    response.onNext(new SimpleSubdocResponse(ResponseStatus.SUCCESS,
        KeyValueStatus.SUCCESS.code(),
        BUCKET,
        Unpooled.EMPTY_BUFFER,
        subdocRequestMock,
        1234,
        null
    ));

    response.onCompleted();
  } else {

    Constructor con = responseClass.getConstructor(ResponseStatus.class,
        short.class,
        long.class,
        String.class,
        ByteBuf.class,
        MutationToken.class,
        CouchbaseRequest.class
    );

    response.onNext((CouchbaseResponse) con.newInstance(ResponseStatus.SUCCESS,
        KeyValueStatus.SUCCESS.code(),
        1234,
        BUCKET,
        Unpooled.EMPTY_BUFFER,
        null,
        requestMock
    ));
    response.onCompleted();
  }

  when(core.send(any(BinarySubdocRequest.class))).thenReturn(response);
  when(core.send(any())).thenReturn(response);
  when(requestMock.span()).thenReturn(mock(Span.class));

  CouchbaseConnector connector = mock(CouchbaseConnector.class);
  when(connector.getScheduler()).thenReturn(ENV.scheduler());
  when(connector.bucket()).thenReturn(asyncBucket);

  return connector;
}
 
Example 17
Source File: QueryHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testBigChunkedResponseWithEscapedBackslashInRowObject() throws Exception {
    String response = Resources.read("chunkedResponseWithDoubleBackslashes.txt", this.getClass());
    String[] chunks = response.split("(?m)^[0-9a-f]+");

    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    responseHeader.headers().add("Transfer-Encoding", "chunked");
    responseHeader.headers().add("Content-Type", "application/json; version=1.0.0");
    Object[] httpChunks = new Object[chunks.length];
    httpChunks[0] = responseHeader;
    for (int i = 1; i < chunks.length; i++) {
        String chunk = chunks[i];
        if (i == chunks.length - 1) {
            httpChunks[i] = new DefaultLastHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8));
        } else {
            httpChunks[i] = new DefaultHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8));
        }
    }

    Subject<CouchbaseResponse,CouchbaseResponse> obs = AsyncSubject.create();
    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    when(requestMock.observable()).thenReturn(obs);
    queue.add(requestMock);
    channel.writeInbound(httpChunks);
    GenericQueryResponse inbound = (GenericQueryResponse) obs.timeout(1, TimeUnit.SECONDS).toBlocking().last();

    final AtomicInteger found = new AtomicInteger(0);
    final AtomicInteger errors = new AtomicInteger(0);
    inbound.rows().timeout(5, TimeUnit.SECONDS).toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf byteBuf) {
            int rowNumber = found.incrementAndGet();
            String content = byteBuf.toString(CharsetUtil.UTF_8);
            byteBuf.release();
            assertNotNull(content);
            assertFalse(content.isEmpty());
        }
    });

    inbound.errors().timeout(5, TimeUnit.SECONDS).toBlocking().forEach(new Action1<ByteBuf>() {
        @Override
        public void call(ByteBuf buf) {
            buf.release();
            errors.incrementAndGet();
        }
    });

    //ignore signature
    ReferenceCountUtil.release(inbound.signature().timeout(5, TimeUnit.SECONDS).toBlocking().single());

    String status = inbound.queryStatus().timeout(5, TimeUnit.SECONDS).toBlocking().single();

    List<ByteBuf> metricList = inbound.info().timeout(1, TimeUnit.SECONDS).toList().toBlocking().single();
    assertEquals(1, metricList.size());
    ByteBuf metricsBuf = metricList.get(0);
    ReferenceCountUtil.releaseLater(metricsBuf);
    Map<String, Object> metrics = DefaultObjectMapper.readValueAsMap(metricsBuf.toString(CharsetUtil.UTF_8));

    assertEquals("success", status);

    assertEquals(5, found.get());
    assertEquals(0, errors.get());

    assertEquals(found.get(), metrics.get("resultCount"));
}
 
Example 18
Source File: QueryHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
private void shouldDecodeChunked(boolean metrics, String... chunks) throws Exception {
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    Object[] httpChunks = new Object[chunks.length + 1];
    httpChunks[0] = responseHeader;
    for (int i = 1; i <= chunks.length; i++) {
        String chunk = chunks[i - 1];
        if (i == chunks.length) {
            httpChunks[i] = new DefaultLastHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8));
        } else {
            httpChunks[i] = new DefaultHttpContent(Unpooled.copiedBuffer(chunk, CharsetUtil.UTF_8));
        }
    }

    Subject<CouchbaseResponse,CouchbaseResponse> obs = AsyncSubject.create();
    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    when(requestMock.observable()).thenReturn(obs);
    queue.add(requestMock);
    channel.writeInbound(httpChunks);
    GenericQueryResponse inbound = (GenericQueryResponse) obs.timeout(1, TimeUnit.SECONDS).toBlocking().last();
    Map<String, Object> expectedMetrics;
    if (metrics) {
        expectedMetrics = expectedMetricsCounts(5678, 1234); //these are the numbers parsed from metrics object, not real count
    } else {
        expectedMetrics = null;
    }

    final AtomicInteger found = new AtomicInteger(0);
    final AtomicInteger errors = new AtomicInteger(0);
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, "123456\\\"78901234567890", "success",
            "{\"horseName\":\"json\"}",
            new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf byteBuf) {
                    found.incrementAndGet();
                    String content = byteBuf.toString(CharsetUtil.UTF_8);
                    byteBuf.release();
                    assertNotNull(content);
                    assertTrue(!content.isEmpty());
                    try {
                        Map<String, Object> decoded = DefaultObjectMapper.readValueAsMap(content);
                        assertTrue(decoded.size() > 0);
                        assertTrue(decoded.containsKey("horseName"));
                    } catch (Exception e) {
                        fail(e.toString());
                    }
                }
            },
            new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    buf.release();
                    errors.incrementAndGet();
                }
            },
            expectedMetrics
    );
    assertEquals(5, found.get());
    assertEquals(4, errors.get());
}
 
Example 19
Source File: AbstractSubdocRequest.java    From couchbase-jvm-core with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link AbstractSubdocRequest}.
 *
 * @param key           the key of the document.
 * @param path          the subdocument path to consider inside the document.
 * @param bucket        the bucket of the document.
 * @param restOfContent the optional remainder of the {@link #content()} of the final protocol message, or null if not applicable
 * @throws NullPointerException if the path is null (see {@link #EXCEPTION_NULL_PATH})
 */
public AbstractSubdocRequest(String key, String path, String bucket, ByteBuf... restOfContent) {
    this(key, path, bucket, AsyncSubject.<CouchbaseResponse>create(), restOfContent);
}
 
Example 20
Source File: AbstractCouchbaseRequest.java    From couchbase-jvm-core with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new {@link AbstractCouchbaseRequest}.
 *
 * Depending on the type of operation, bucket and password may be null, this needs to
 * be enforced properly by the child implementations.
 *
 * This constructor will create a AsyncSubject, which implies that the response for this
 * request only emits one message. If you need to expose a streaming response, use the
 * other constructor and feed it a ReplaySubject or something similar.
 *
 * @param bucket the name of the bucket.
 * @param username user authorized to access the bucket.
 * @param password user password.
 */
protected AbstractCouchbaseRequest(String bucket, String username, String password) {
    this(bucket, username, password, AsyncSubject.<CouchbaseResponse>create());
}