rx.subjects.AsyncSubject Java Examples

The following examples show how to use rx.subjects.AsyncSubject. 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: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotReleaseStoreRequestContentOnRetry() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
        content);
    response.setStatus(KeyValueStatus.ERR_NOT_MY_VBUCKET.code());

    UpsertRequest requestMock = mock(UpsertRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
}
 
Example #2
Source File: CouchbaseNodeTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test(expected = RequestCancelledException.class)
public void shouldCancelIfServiceCouldNotBeLocated() {
    ServiceRegistry registryMock = mock(ServiceRegistry.class);
    Service serviceMock = mock(Service.class);
    when(registryMock.serviceBy(ServiceType.BINARY, "bucket")).thenReturn(serviceMock);
    when(serviceMock.states()).thenReturn(Observable.<LifecycleState>empty());
    CoreEnvironment env = mock(CoreEnvironment.class);
    when(env.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);

    CoreContext ctx = new CoreContext(env, null);
    CouchbaseNode node = new CouchbaseNode(host, registryMock, ctx, ServiceFactory.INSTANCE);

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

    response.toBlocking().single();
}
 
Example #3
Source File: ViewLocatorTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailWhenUsedAgainstMemcacheBucket() {
    Locator locator = new ViewLocator(0);

    ClusterConfig config = mock(ClusterConfig.class);
    when(config.bucketConfig("default")).thenReturn(mock(MemcachedBucketConfig.class));

    CouchbaseRequest request = mock(ViewQueryRequest.class);
    Subject<CouchbaseResponse, CouchbaseResponse> response = AsyncSubject.create();
    when(request.bucket()).thenReturn("default");
    when(request.observable()).thenReturn(response);

    TestSubscriber<CouchbaseResponse> subscriber = new TestSubscriber<CouchbaseResponse>();
    response.subscribe(subscriber);

    locator.locateAndDispatch(request, Collections.<Node>emptyList(), config, null, null);

    subscriber.awaitTerminalEvent(1, TimeUnit.SECONDS);
    List<Throwable> errors = subscriber.getOnErrorEvents();
    assertEquals(1, errors.size());
    assertTrue(errors.get(0) instanceof ServiceNotAvailableException);
}
 
Example #4
Source File: AbstractOnDemandServiceTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailObservableIfErrorOnConnect() {
    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.<LifecycleState>error(new AuthenticationException()));
    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(AuthenticationException ex) {
        assertTrue(true);
        assertEquals(LifecycleState.IDLE, service.state());
    } catch(Throwable tr) {
        assertTrue(tr.getMessage(), false);
    }
}
 
Example #5
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 #6
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 #7
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReleaseStoreRequestContentOnSuccess() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
        content);
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);

    UpsertRequest requestMock = mock(UpsertRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(0, requestContent.refCnt());
}
 
Example #8
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 #9
Source File: YasjlQueryResponseParser.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.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 #10
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 #11
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReleaseAppendRequestContentOnSuccess() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
        content);
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);

    AppendRequest requestMock = mock(AppendRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(0, requestContent.refCnt());
}
 
Example #12
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotReleaseAppendRequestContentOnRetry() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
        content);
    response.setStatus(KeyValueStatus.ERR_NOT_MY_VBUCKET.code());

    AppendRequest requestMock = mock(AppendRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
}
 
Example #13
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotReleasePrependRequestContentOnRetry() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
        content);
    response.setStatus(KeyValueStatus.ERR_NOT_MY_VBUCKET.code());

    PrependRequest requestMock = mock(PrependRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
}
 
Example #14
Source File: SessionEstablishedState.java    From jawampa with Apache License 2.0 6 votes vote down vote up
public void performCall(final String procedure,
        final EnumSet<CallFlags> flags,
        final ArrayNode arguments,
        final ObjectNode argumentsKw,
        final AsyncSubject<Reply> resultSubject)
{
    final long requestId = IdGenerator.newLinearId(lastRequestId, requestMap);
    lastRequestId = requestId;
    
    ObjectNode options = stateController.clientConfig().objectMapper().createObjectNode();
    
    boolean discloseMe = flags != null && flags.contains(CallFlags.DiscloseMe) ? true : false;
    if (discloseMe) {
        options.put("disclose_me", discloseMe);
    }
    
    final CallMessage callMsg = new CallMessage(requestId, options, procedure, 
                                          arguments, argumentsKw);
    
    requestMap.put(requestId, new RequestMapEntry(CallMessage.ID, resultSubject));
    connectionController.sendMessage(callMsg, IWampConnectionPromise.Empty);
}
 
Example #15
Source File: WampClient.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns an observable that will be completed with a single value once the client terminates.<br>
 * This can be used to asynchronously wait for completion after {@link #close() close} was called.
 */
public Observable<Void> getTerminationObservable() {
    final AsyncSubject<Void> termSubject = AsyncSubject.create();
    stateController.statusObservable().subscribe(new Observer<State>() {
        @Override
        public void onCompleted() {
            termSubject.onNext(null);
            termSubject.onCompleted();
        }

        @Override
        public void onError(Throwable e) {
            termSubject.onNext(null);
            termSubject.onCompleted();
        }

        @Override
        public void onNext(State t) { }
    });
    return termSubject;
}
 
Example #16
Source File: WampClient.java    From jawampa with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an observable that will be completed with a single value once the client terminates.<br>
 * This can be used to asynchronously wait for completion after {@link #close() close} was called.
 */
public Observable<Void> getTerminationObservable() {
    final AsyncSubject<Void> termSubject = AsyncSubject.create();
    stateController.statusObservable().subscribe(new Observer<State>() {
        @Override
        public void onCompleted() {
            termSubject.onNext(null);
            termSubject.onCompleted();
        }

        @Override
        public void onError(Throwable e) {
            termSubject.onNext(null);
            termSubject.onCompleted();
        }

        @Override
        public void onNext(State t) { }
    });
    return termSubject;
}
 
Example #17
Source File: SessionEstablishedState.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public void performCall(final String procedure,
        final EnumSet<CallFlags> flags,
        final ArrayNode arguments,
        final ObjectNode argumentsKw,
        final AsyncSubject<Reply> resultSubject)
{
    final long requestId = IdGenerator.newLinearId(lastRequestId, requestMap);
    lastRequestId = requestId;
    
    ObjectNode options = stateController.clientConfig().objectMapper().createObjectNode();
    
    boolean discloseMe = flags != null && flags.contains(CallFlags.DiscloseMe) ? true : false;
    if (discloseMe) {
        options.put("disclose_me", discloseMe);
    }
    
    final CallMessage callMsg = new CallMessage(requestId, options, procedure, 
                                          arguments, argumentsKw);
    
    requestMap.put(requestId, new RequestMapEntry(CallMessage.ID, resultSubject));
    connectionController.sendMessage(callMsg, IWampConnectionPromise.Empty);
}
 
Example #18
Source File: AsyncUtils.java    From Java_MVVM_with_Swing_and_RxJava_Examples with Apache License 2.0 6 votes vote down vote up
/**
 * Starts immediately the execution of the given Callable with a thread from
 * {@link Schedulers#io()}.
 *
 * The caller can await the execution termination through subscribing to the {@link Single} return value.
 * It's safe to "share" the {@link Single} return value reference and subscribe to it as many times as you want.
 * All subscribers get the result value (or the error) individually.
 *
 * Cancellation? The execution is automatically cancelled when all subscribers do unsubscribe while
 * the execution is still running. The given {@link Callable} will be interrupted.
 *
 * If there is no subscriber ever to the {@link Single} return value, the callable will be executed unobserved.
 * Make sure to have some kind of "exception handling" also for that case (like try-catch-logging blocks or
 * {@link Thread.UncaughtExceptionHandler}) to not "miss" issues.
 *
 * @param callable the code to execute
 * @param <T>      type of result
 * @return Single instance delivering asynchronously the result of the callable
 */
// experimental
public static <T> Single<T> executeAsync(Callable<T> callable) {
    AsyncSubject<T> resultSubject = AsyncSubject.create();

 final Subscription asyncOp = Observable.fromCallable(callable)
   .subscribeOn(Schedulers.io())
   .lift(preserveFullStackTrace())
            .subscribe(
                    t -> {
                        resultSubject.onNext(t);
                        resultSubject.onCompleted();
                    },
                    throwable -> {
                        resultSubject.onError(throwable);
                        resultSubject.onCompleted();
                    }
            );

    return resultSubject.doOnUnsubscribe(asyncOp::unsubscribe)
            .share()
            .toSingle();
}
 
Example #19
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test(expected = CouchbaseException.class)
public void shouldFailWhenOpaqueDoesNotMatch() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
            content);
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);
    response.setOpaque(1);

    PrependRequest requestMock = mock(PrependRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    AsyncSubject<CouchbaseResponse> responseSubject = AsyncSubject.<CouchbaseResponse>create();
    when(requestMock.observable()).thenReturn(responseSubject);
    when(requestMock.content()).thenReturn(requestContent);
    when(requestMock.opaque()).thenReturn(3);
    requestQueue.add(requestMock);

    channel.writeInbound(response);
    assertEquals(0, content.refCnt());
    responseSubject.toBlocking().single();
}
 
Example #20
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReleasePrependRequestContentOnSuccess() throws Exception {
    ByteBuf content = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    FullBinaryMemcacheResponse response = new DefaultFullBinaryMemcacheResponse(KEY, Unpooled.EMPTY_BUFFER,
        content);
    response.setStatus(BinaryMemcacheResponseStatus.SUCCESS);

    PrependRequest requestMock = mock(PrependRequest.class);
    ByteBuf requestContent = Unpooled.copiedBuffer("content", CharsetUtil.UTF_8);
    when(requestMock.bucket()).thenReturn("bucket");
    when(requestMock.observable()).thenReturn(AsyncSubject.<CouchbaseResponse>create());
    when(requestMock.content()).thenReturn(requestContent);
    requestQueue.add(requestMock);

    assertEquals(1, content.refCnt());
    assertEquals(1, requestContent.refCnt());
    channel.writeInbound(response);
    assertEquals(1, content.refCnt());
    assertEquals(0, requestContent.refCnt());
}
 
Example #21
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 #22
Source File: KeyValueHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHavePipeliningEnabled() {
    Subject<CouchbaseResponse,CouchbaseResponse> obs1 = AsyncSubject.create();
    GetRequest requestMock1 = mock(GetRequest.class);
    when(requestMock1.keyBytes()).thenReturn("hello".getBytes());
    when(requestMock1.bucket()).thenReturn("foo");
    when(requestMock1.observable()).thenReturn(obs1);

    Subject<CouchbaseResponse,CouchbaseResponse> obs2 = AsyncSubject.create();
    GetRequest requestMock2 = mock(GetRequest.class);
    when(requestMock2.keyBytes()).thenReturn("hello".getBytes());

    when(requestMock2.bucket()).thenReturn("foo");
    when(requestMock2.observable()).thenReturn(obs2);


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

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

    channel.writeOutbound(requestMock1, requestMock2);

    t1.assertNotCompleted();
    t2.assertNotCompleted();
}
 
Example #23
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 #24
Source File: AbstractEndpointTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test(expected = NotConnectedException.class)
public void shouldRejectMessageIfNotConnected() {
    BootstrapAdapter bootstrap = mock(BootstrapAdapter.class);
    Endpoint endpoint = new DummyEndpoint(bootstrap, ctx);

    CouchbaseRequest mockRequest = mock(CouchbaseRequest.class);
    Subject<CouchbaseResponse, CouchbaseResponse> subject = AsyncSubject.create();
    when(mockRequest.observable()).thenReturn(subject);
    endpoint.send(mockRequest);
    mockRequest.observable().toBlocking().single();
}
 
Example #25
Source File: SearchHandlerTest.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();
    SearchQueryRequest requestMock1 = mock(SearchQueryRequest.class);
    when(requestMock1.path()).thenReturn("");
    when(requestMock1.payload()).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();
    SearchQueryRequest requestMock2 = mock(SearchQueryRequest.class);
    when(requestMock2.path()).thenReturn("");
    when(requestMock2.payload()).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 #26
Source File: WampClient.java    From jawampa with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a remote procedure call through the router.<br>
 * The function will return immediately, as the actual call will happen
 * asynchronously.
 * @param procedure The name of the procedure to call. Must be a valid WAMP
 * Uri.
 * @param flags Additional call flags if any. This can be null.
 * @param arguments A list of all positional arguments for the procedure call
 * @param argumentsKw All named arguments for the procedure call
 * @return An observable that provides a notification whether the call was
 * was successful and the return value. If the call is successful the
 * returned observable will be completed with a single value (the return value).
 * If the remote procedure call yields an error the observable will be completed
 * with an error.
 */
public Observable<Reply> call(final String procedure,
                              final EnumSet<CallFlags> flags,
                              final ArrayNode arguments,
                              final ObjectNode argumentsKw)
{
    final AsyncSubject<Reply> resultSubject = AsyncSubject.create();
    
    try {
        UriValidator.validate(procedure, 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 performing actual call into the session
            SessionEstablishedState curState = (SessionEstablishedState)stateController.currentState();
            curState.performCall(procedure, flags, arguments, argumentsKw, resultSubject);
        }
    });

    if (!wasScheduled) {
        resultSubject.onError(
            new ApplicationError(ApplicationError.CLIENT_CLOSED));
    }
    
    return resultSubject;
}
 
Example #27
Source File: QueryHandlerTest.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();
    RawQueryRequest requestMock1 = mock(RawQueryRequest.class);
    when(requestMock1.query()).thenReturn("SELECT * FROM `foo`");
    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();
    RawQueryRequest requestMock2 = mock(RawQueryRequest.class);
    when(requestMock2.query()).thenReturn("SELECT * FROM `foo`");
    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 #28
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 #29
Source File: QueryHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecodeRawQueryServerNotOk() throws Exception {
    int expectedCode = 400; //BAD REQUEST
    String expectedMsg = "Sorry Sir!";
    String body = "Something bad happened, and this is not JSON";

    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(expectedCode, expectedMsg));
    HttpContent responseBody = new DefaultLastHttpContent(Unpooled.copiedBuffer(body, CharsetUtil.UTF_8));

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

    //convert the ByteBuf to String and release before asserting
    String byteBufResponse = inbound.jsonResponse().toString(CharsetUtil.UTF_8);
    inbound.jsonResponse().release();

    assertNotNull(inbound);
    assertEquals(ResponseStatus.INVALID_ARGUMENTS, inbound.status());
    assertEquals(expectedCode, inbound.httpStatusCode());
    assertEquals(expectedMsg, inbound.httpStatusMsg());

    assertEquals(body, byteBufResponse); //the response still contains the body
}
 
Example #30
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);
}