rx.subjects.Subject Java Examples

The following examples show how to use rx.subjects.Subject. 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: RateLimitedBatcherTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void onCompletedIsNotSentAfterOnError() {
    final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs);
    final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized();

    final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test();
    testScheduler.triggerActions();
    subscriber.assertNoTerminalEvent().assertNoValues();

    updates.onError(new RuntimeException("some problem"));
    testScheduler.triggerActions(); // onError is forwarded right away (i.e.: don't wait for the next flush event)
    subscriber.assertNotCompleted().assertError(RuntimeException.class);

    updates.onCompleted();
    subscriber.assertNotCompleted();
}
 
Example #2
Source File: HystrixMetricsStreamHandler.java    From ReactiveLab with Apache License 2.0 6 votes vote down vote up
private Observable<Void> handleHystrixRequest(final HttpServerResponse<O> response) {
    writeHeaders(response);

    final Subject<Void, Void> subject = PublishSubject.create();
    final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription();
    Subscription actionSubscription = Observable.timer(0, interval, TimeUnit.MILLISECONDS, Schedulers.computation())
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long tick) {
                    if (!response.getChannel().isOpen()) {
                        subscription.unsubscribe();
                        return;
                    }
                    try {
                        writeMetric(JsonMapper.toJson(metrics), response);
                    } catch (Exception e) {
                        subject.onError(e);
                    }
                }
            });
    subscription.set(actionSubscription);
    return subject;
}
 
Example #3
Source File: AbstractGenericHandler.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Publishes a response with the attached observable.
 *
 * @param response the response to publish.
 * @param observable pushing into the event sink.
 */
protected void publishResponse(final CouchbaseResponse response,
    final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
    if (response.status() != ResponseStatus.RETRY && observable != null) {
        if (moveResponseOut) {
            Scheduler scheduler = env().scheduler();
            if (scheduler instanceof CoreScheduler) {
                scheduleDirect((CoreScheduler) scheduler, response, observable);
            } else {
                scheduleWorker(scheduler, response, observable);
            }
        } else {
            completeResponse(response, observable);
        }
    } else {
        responseBuffer.publishEvent(ResponseHandler.RESPONSE_TRANSLATOR, response, observable);
    }
}
 
Example #4
Source File: AbstractGenericHandler.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Fulfill and complete the response observable.
 *
 * When called directly, this method completes on the event loop, but it can also be used in a callback (see
 * {@link #scheduleDirect(CoreScheduler, CouchbaseResponse, Subject)} for example.
 */
private void completeResponse(final CouchbaseResponse response,
    final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
    // Noone is listening anymore, handle tracing and/or orphan reporting
    // depending on if enabled or not.
    CouchbaseRequest request = response.request();
    if (request != null && !request.isActive()) {
        if (env().operationTracingEnabled() && request.span() != null) {
            Scope scope = env().tracer().scopeManager()
                    .activate(request.span(), true);
            scope.span().setBaggageItem("couchbase.orphan", "true");
            scope.close();
        }
        if (env().orphanResponseReportingEnabled()) {
            env().orphanResponseReporter().report(response);
        }
    }

    try {
        observable.onNext(response);
        observable.onCompleted();
    } catch (Exception ex) {
        LOGGER.warn("Caught exception while onNext on observable", ex);
        observable.onError(ex);
    }
}
 
Example #5
Source File: AbstractSubdocRequest.java    From couchbase-jvm-core with Apache License 2.0 6 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 observable    the observable which receives responses.
 * @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,
                             Subject<CouchbaseResponse, CouchbaseResponse> observable,
                             ByteBuf... restOfContent) {
    super(key, bucket, null, null, observable);
    this.path = path;
    ByteBuf pathByteBuf;
    if (path == null || path.isEmpty()) {
        pathByteBuf = Unpooled.EMPTY_BUFFER;
    } else {
        pathByteBuf = Unpooled.wrappedBuffer(path.getBytes(CharsetUtil.UTF_8));
    }
    this.pathLength = pathByteBuf.readableBytes();
    this.content = createContent(pathByteBuf, restOfContent);

    //checking nullity here allows to release all of restOfContent through cleanUpAndThrow releasing content()
    if (this.path == null) {
        cleanUpAndThrow(EXCEPTION_NULL_PATH);
    }
}
 
Example #6
Source File: UploadManager.java    From RxUploader with Apache License 2.0 6 votes vote down vote up
@NonNull
public UploadManager build() {
    if (uploadService == null) {
        throw new IllegalArgumentException("Must provide a valid upload service");
    }

    if (uploadDataStore == null) {
        throw new IllegalArgumentException("Must provide a valid upload data store");
    }

    if (uploadErrorAdapter == null) {
        throw new IllegalArgumentException("Must provide a valid upload error adapter");
    }

    final Subject<Job, Job> jobSubject = PublishSubject.<Job>create().toSerialized();
    final Subject<Status, Status> statusSubject =
            PublishSubject.<Status>create().toSerialized();

    final Uploader uploader = Uploader.create(uploadService);
    final UploadInteractor uploadInteractor =
            UploadInteractorImpl.create(uploader, uploadDataStore, uploadErrorAdapter);


    return new UploadManager(uploadInteractor, uploadErrorAdapter, jobSubject,
            statusSubject, deleteRecordOnComplete);
}
 
Example #7
Source File: WhiteBoard.java    From Shield with MIT License 6 votes vote down vote up
/**
 * Find the value of the key in the data set, and
 * returns an Observable with the value as its initial state.
 * If the key is not contained in the data set,
 * returns an Observable with null as its initial state.
 *
 * @param key The key to find the value
 * @return an Observable with the value as its initial state if the value is not null,
 * an Observable without initial state if the value is null
 */
public Observable getObservable(final String key) {

    Subject res = null;
    if (subjectMap.containsKey(key)) {
        res = subjectMap.get(key);
    } else {
        res = PublishSubject.create();
        subjectMap.put(key, res);
    }
    if (getData(key) != null) {
        return res.startWith(getData(key));
    } else {
        return res;
    }
}
 
Example #8
Source File: RateLimitedBatcherTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void ignoreErrorsFromDownstream() {
    final Instant now = Instant.ofEpochMilli(testScheduler.now());
    final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs);
    final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized();

    final AssertableSubscriber<?> subscriber = updates.lift(batcher)
            .lift(new ExceptionThrowingOperator("some error happened"))
            .test();
    testScheduler.triggerActions();
    subscriber.assertNoTerminalEvent().assertNoValues();

    for (int i = 0; i < 10; i++) {
        updates.onNext(new BatchableOperationMock(LOW, now, "resource2", "sub2", "create"));
        testScheduler.advanceTimeBy(minimumTimeInQueueMs, TimeUnit.MILLISECONDS);
        subscriber.assertNoTerminalEvent().assertNoValues();
    }

    updates.onCompleted();
    testScheduler.advanceTimeBy(minimumTimeInQueueMs, TimeUnit.MILLISECONDS);
    subscriber.assertNoValues().assertCompleted();
}
 
Example #9
Source File: RateLimitedBatcherTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void onErrorIsNotSentAfterOnCompleted() {
    final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs);
    final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized();

    final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test();
    testScheduler.triggerActions();
    subscriber.assertNoTerminalEvent().assertNoValues();

    updates.onCompleted();
    // onCompleted is sent after pending items are drained
    testScheduler.advanceTimeBy(minimumTimeInQueueMs, TimeUnit.MILLISECONDS);
    subscriber.assertNoErrors().assertCompleted();

    updates.onError(new RuntimeException("some problem"));
    subscriber.assertNoErrors();
}
 
Example #10
Source File: RateLimitedBatcherTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private void assertEmitSingleAfterReceiving(BatchableOperationMock expected, BatchableOperationMock... receiving) {
    final RateLimitedBatcher<BatchableOperationMock, String> batcher = buildBatcher(minimumTimeInQueueMs);
    final Subject<BatchableOperationMock, BatchableOperationMock> updates = PublishSubject.<BatchableOperationMock>create().toSerialized();

    final AssertableSubscriber<Batch<BatchableOperationMock, String>> subscriber = updates.lift(batcher).test();
    testScheduler.triggerActions();
    subscriber.assertNoTerminalEvent().assertNoValues();

    for (BatchableOperationMock received : receiving) {
        updates.onNext(received);
    }

    testScheduler.advanceTimeBy(2 * minimumTimeInQueueMs, TimeUnit.MILLISECONDS);
    subscriber.assertNoErrors()
            .assertValueCount(1)
            .assertValue(Batch.of(expected.getResourceId(), Collections.singletonList(expected)));
}
 
Example #11
Source File: ResponseHandlerTest.java    From couchbase-jvm-core with 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 #12
Source File: ResponseHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIgnoreInvalidConfig() throws Exception {
    ClusterFacade clusterMock = mock(ClusterFacade.class);
    ConfigurationProvider providerMock = mock(ConfigurationProvider.class);
    ResponseHandler handler = new ResponseHandler(ENVIRONMENT, clusterMock, providerMock);
    ByteBuf config = Unpooled.copiedBuffer("Not my Vbucket", 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", "Not my Vbucket", null);
    verify(providerMock, never()).proposeBucketConfig(ctx);
    assertEquals(0, config.refCnt());
    assertNull(retryEvent.getMessage());
    assertNull(retryEvent.getObservable());
}
 
Example #13
Source File: RxBus.java    From Elephant with Apache License 2.0 6 votes vote down vote up
/**
 * 取消监听
 *
 * @param tag
 * @param observable
 * @return
 */
@SuppressWarnings("rawtypes")
public RxBus unregister(@NonNull Object tag,
                        @NonNull Observable<?> observable) {
    if (null == observable)
        return $();
    List<Subject> subjects = subjectMapper.get(tag);
    if (null != subjects) {
        subjects.remove((Subject<?, ?>) observable);
        if (isEmpty(subjects)) {
            subjectMapper.remove(tag);
            JLog.d("unregister", tag + "  size:" + subjects.size());
        }
    }
    return $();
}
 
Example #14
Source File: RxBus.java    From youqu_master with Apache License 2.0 6 votes vote down vote up
/**
 * 取消监听
 *
 * @param tag
 * @param observable
 * @return
 */
@SuppressWarnings("rawtypes")
public RxBus unregister(@NonNull Object tag,
                        @NonNull Observable<?> observable) {
    if (null == observable)
        return getInstance();
    List<Subject> subjects = subjectMapper.get(tag);
    if (null != subjects) {
        subjects.remove((Subject<?, ?>) observable);
        if (isEmpty(subjects)) {
            subjectMapper.remove(tag);
            LogUtils.logd("unregister"+ tag + "  size:" + subjects.size());
        }
    }
    return getInstance();
}
 
Example #15
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 #16
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 #17
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 #18
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 #19
Source File: AbstractGenericHandler.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
/**
 * Dispatches the response on a generic scheduler through creating a worker.
 */
private void scheduleWorker(Scheduler scheduler, final CouchbaseResponse response,
    final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
    final Scheduler.Worker worker = scheduler.createWorker();
    worker.schedule(new Action0() {
        @Override
        public void call() {
            completeResponse(response, observable);
            worker.unsubscribe();
        }
    });
}
 
Example #20
Source File: AbstractGenericHandler.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
/**
 * Optimized version of dispatching onto the core scheduler through direct scheduling.
 *
 * This method has less GC overhead compared to {@link #scheduleWorker(Scheduler, CouchbaseResponse, Subject)}
 * since no worker needs to be generated explicitly (but is not part of the public Scheduler interface).
 */
private void scheduleDirect(CoreScheduler scheduler, final CouchbaseResponse response,
    final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
    scheduler.scheduleDirect(new Action0() {
        @Override
        public void call() {
            completeResponse(response, observable);
        }
    });
}
 
Example #21
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 #22
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 #23
Source File: HystrixMetricsStreamHandler.java    From ReactiveLab with Apache License 2.0 5 votes vote down vote up
private Observable<Void> handleHystrixRequest(final HttpServerResponse<O> response) {
    writeHeaders(response);

    final Subject<Void, Void> subject = PublishSubject.create();
    final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription();
    Subscription actionSubscription = Observable.timer(0, interval, TimeUnit.MILLISECONDS, Schedulers.computation())
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long tick) {
                    if (!response.getChannel().isOpen()) {
                        subscription.unsubscribe();
                        return;
                    }
                    try {
                        for (HystrixCommandMetrics commandMetrics : HystrixCommandMetrics.getInstances()) {
                            writeMetric(JsonMapper.toJson(commandMetrics), response);
                        }
                        for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) {
                            writeMetric(JsonMapper.toJson(threadPoolMetrics), response);
                        }
                    } catch (Exception e) {
                        subject.onError(e);
                    }
                }
            });
    subscription.set(actionSubscription);
    return subject;
}
 
Example #24
Source File: ResponseHandler.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
/**
 * Handles {@link ResponseEvent}s that come into the response RingBuffer.
 *
 * Hey I just mapped you,
 * And this is crazy,
 * But here's my data
 * so subscribe me maybe.
 *
 * It's hard to block right,
 * at you baby,
 * But here's my data ,
 * so subscribe me maybe.
 */
@Override
public void onEvent(final ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
    try {
        CouchbaseMessage message = event.getMessage();
        if (message instanceof SignalConfigReload) {
            configurationProvider.signalOutdated();
        } else if (message instanceof CouchbaseResponse) {
            final CouchbaseResponse response = (CouchbaseResponse) message;
            ResponseStatus status = response.status();
            if (status == ResponseStatus.RETRY) {
                retry(event, true);
            } else {
                final Scheduler.Worker worker = environment.scheduler().createWorker();
                final Subject<CouchbaseResponse, CouchbaseResponse> obs = event.getObservable();
                worker.schedule(new Action0() {
                    @Override
                    public void call() {
                        try {
                            obs.onNext(response);
                            obs.onCompleted();
                        } catch(Exception ex) {
                            obs.onError(ex);
                        } finally {
                            worker.unsubscribe();
                        }
                    }
                });
            }
        } else if (message instanceof CouchbaseRequest) {
            retry(event, false);
        } else {
            throw new IllegalStateException("Got message type I do not understand: " + message);
        }
    } finally {
       event.setMessage(null);
       event.setObservable(null);
    }
}
 
Example #25
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 #26
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 #27
Source File: RxBusOlder.java    From RxBus with Apache License 2.0 5 votes vote down vote up
public void post(@NonNull Object tag, @NonNull Object content) {
    List<Subject> subjects = mSubjectsMapper.get(tag);
    if (subjects != null && !subjects.isEmpty()) {
        for (Subject subject : subjects) {
            subject.onNext(content);
        }
    }
    if (DEBUG) {
        Timber.d("[send] mSubjectsMapper: " + mSubjectsMapper);
    }
}
 
Example #28
Source File: RxBusOlder.java    From RxBus with Apache License 2.0 5 votes vote down vote up
public void unregister(@NonNull Object tag, @NonNull Observable observable) {
    List<Subject> subjects = mSubjectsMapper.get(tag);
    if (subjects != null) {
        subjects.remove(observable);
        if (subjects.isEmpty()) {
            mSubjectsMapper.remove(tag);
        }
        if (DEBUG) {
            Timber.d("[unregister] mSubjectsMapper: " + mSubjectsMapper);
        }
    }
}
 
Example #29
Source File: RxBusOlder.java    From RxBus with Apache License 2.0 5 votes vote down vote up
public <T> Observable<T> register(@NonNull Object tag, @NonNull Class<T> clazz) {
    List<Subject> subjectList = mSubjectsMapper.get(tag);
    if (subjectList == null) {
        subjectList = new ArrayList<>();
        mSubjectsMapper.put(tag, subjectList);
    }

    Subject<T, T> subject = new SerializedSubject<>(PublishSubject.<T>create());
    subjectList.add(subject);
    if (DEBUG) {
        Timber.d("[register] mSubjectsMapper: " + mSubjectsMapper);
    }
    return subject;
}
 
Example #30
Source File: RxBus.java    From youqu_master with Apache License 2.0 5 votes vote down vote up
/**
 * 注册事件源
 *
 * @param tag
 * @return
 */
@SuppressWarnings({"rawtypes"})
public <T> Observable<T> register(@NonNull Object tag) {
    List<Subject> subjectList = subjectMapper.get(tag);
    if (null == subjectList) {
        subjectList = new ArrayList<Subject>();
        subjectMapper.put(tag, subjectList);
    }
    Subject<T, T> subject;
    subjectList.add(subject = PublishSubject.create());
    LogUtils.logd("register"+tag + "  size:" + subjectList.size());
    return subject;
}