Search in sources :

Example 41 with Action1

use of rx.functions.Action1 in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnFailureWithFallback.

private RequestContextTestResults testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker()).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    s.onError(new RuntimeException("onError"));
                }
            }).subscribeOn(userScheduler);
        }

        @Override
        protected Observable<Boolean> resumeWithFallback() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onNext(false);
                    s.onCompleted();
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Run => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(0, results.ts.getOnErrorEvents().size());
    assertEquals(1, results.ts.getOnNextEvents().size());
    assertEquals(false, results.ts.getOnNextEvents().get(0));
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isFailedExecution());
    assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 42 with Action1

use of rx.functions.Action1 in project Hystrix by Netflix.

the class HystrixCommandTest method testUnsubscribeBeforeSubscribe.

@Test
public void testUnsubscribeBeforeSubscribe() throws Exception {
    // this may happen in Observable chain, so Hystrix should make sure that command never executes/allocates in this situation
    Observable<String> error = Observable.error(new RuntimeException("foo"));
    HystrixCommand<Integer> cmd = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 100);
    Observable<Integer> cmdResult = cmd.toObservable().doOnNext(new Action1<Integer>() {

        @Override
        public void call(Integer integer) {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnNext : " + integer);
        }
    }).doOnError(new Action1<Throwable>() {

        @Override
        public void call(Throwable ex) {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnError : " + ex);
        }
    }).doOnCompleted(new Action0() {

        @Override
        public void call() {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnCompleted");
        }
    }).doOnSubscribe(new Action0() {

        @Override
        public void call() {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnSubscribe");
        }
    }).doOnUnsubscribe(new Action0() {

        @Override
        public void call() {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnUnsubscribe");
        }
    });
    // the zip operator will subscribe to each observable.  there is a race between the error of the first
    // zipped observable terminating the zip and the subscription to the command's observable
    Observable<String> zipped = Observable.zip(error, cmdResult, new Func2<String, Integer, String>() {

        @Override
        public String call(String s, Integer integer) {
            return s + integer;
        }
    });
    final CountDownLatch latch = new CountDownLatch(1);
    zipped.subscribe(new Subscriber<String>() {

        @Override
        public void onCompleted() {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnCompleted");
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnError : " + e);
            latch.countDown();
        }

        @Override
        public void onNext(String s) {
            System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnNext : " + s);
        }
    });
    latch.await(1000, TimeUnit.MILLISECONDS);
    System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
}
Also used : Action0(rx.functions.Action0) Action1(rx.functions.Action1) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Test(org.junit.Test)

Example 43 with Action1

use of rx.functions.Action1 in project Hystrix by Netflix.

the class HystrixCommandTest method testObservableTimeoutNoFallbackThreadContext.

/**
 * See https://github.com/Netflix/Hystrix/issues/212
 */
@Test
public void testObservableTimeoutNoFallbackThreadContext() {
    TestSubscriber<Object> ts = new TestSubscriber<Object>();
    final AtomicReference<Thread> onErrorThread = new AtomicReference<Thread>();
    final AtomicBoolean isRequestContextInitialized = new AtomicBoolean();
    TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 50);
    command.toObservable().doOnError(new Action1<Throwable>() {

        @Override
        public void call(Throwable t1) {
            System.out.println("onError: " + t1);
            System.out.println("onError Thread: " + Thread.currentThread());
            System.out.println("ThreadContext in onError: " + HystrixRequestContext.isCurrentThreadInitialized());
            onErrorThread.set(Thread.currentThread());
            isRequestContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
        }
    }).subscribe(ts);
    ts.awaitTerminalEvent();
    assertTrue(isRequestContextInitialized.get());
    assertTrue(onErrorThread.get().getName().startsWith("HystrixTimer"));
    List<Throwable> errors = ts.getOnErrorEvents();
    assertEquals(1, errors.size());
    Throwable e = errors.get(0);
    if (errors.get(0) instanceof HystrixRuntimeException) {
        HystrixRuntimeException de = (HystrixRuntimeException) e;
        assertNotNull(de.getFallbackException());
        assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
        assertNotNull(de.getImplementingClass());
        assertNotNull(de.getCause());
        assertTrue(de.getCause() instanceof TimeoutException);
    } else {
        fail("the exception should be ExecutionException with cause as HystrixRuntimeException");
    }
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertTrue(command.isResponseTimedOut());
    assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
    assertNotNull(command.getExecutionException());
    assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
}
Also used : Action1(rx.functions.Action1) AtomicReference(java.util.concurrent.atomic.AtomicReference) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TestSubscriber(rx.observers.TestSubscriber) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 44 with Action1

use of rx.functions.Action1 in project xDrip by NightscoutFoundation.

the class DexShareCollectionService method attemptRead.

public void attemptRead() {
    PowerManager powerManager = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wakeLock1 = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ReadingShareData");
    wakeLock1.acquire(60000);
    requestHighPriority();
    Log.d(TAG, "Attempting to read data");
    final Action1<Long> systemTimeListener = new Action1<Long>() {

        @Override
        public void call(Long s) {
            if (s != null) {
                Log.d(TAG, "Made the full round trip, got " + s + " as the system time");
                final long additiveSystemTimeOffset = new Date().getTime() - s;
                final Action1<Long> dislpayTimeListener = new Action1<Long>() {

                    @Override
                    public void call(Long s) {
                        if (s != null) {
                            Log.d(TAG, "Made the full round trip, got " + s + " as the display time offset");
                            final long addativeDisplayTimeOffset = additiveSystemTimeOffset - (s * 1000);
                            Log.d(TAG, "Making " + addativeDisplayTimeOffset + " the the total time offset");
                            final Action1<EGVRecord[]> evgRecordListener = new Action1<EGVRecord[]>() {

                                @Override
                                public void call(EGVRecord[] egvRecords) {
                                    if (egvRecords != null) {
                                        Log.d(TAG, "Made the full round trip, got " + egvRecords.length + " EVG Records");
                                        BgReading.create(egvRecords, additiveSystemTimeOffset, getApplicationContext());
                                        statusErrors = 0;
                                        {
                                            Log.d(TAG, "Releasing wl in egv");
                                            requestLowPriority();
                                            if (wakeLock1 != null && wakeLock1.isHeld())
                                                wakeLock1.release();
                                            Log.d(TAG, "released");
                                        }
                                        if (shouldDisconnect) {
                                            stopSelf();
                                        } else {
                                            setRetryTimer();
                                        }
                                    }
                                }
                            };
                            final Action1<SensorRecord[]> sensorRecordListener = new Action1<SensorRecord[]>() {

                                @Override
                                public void call(SensorRecord[] sensorRecords) {
                                    if (sensorRecords != null) {
                                        Log.d(TAG, "Made the full round trip, got " + sensorRecords.length + " Sensor Records");
                                        BgReading.create(sensorRecords, additiveSystemTimeOffset, getApplicationContext());
                                        statusErrors = 0;
                                        readData.getRecentEGVs(evgRecordListener);
                                    }
                                }
                            };
                            final Action1<CalRecord[]> calRecordListener = new Action1<CalRecord[]>() {

                                @Override
                                public void call(CalRecord[] calRecords) {
                                    if (calRecords != null) {
                                        Log.d(TAG, "Made the full round trip, got " + calRecords.length + " Cal Records");
                                        Calibration.create(calRecords, addativeDisplayTimeOffset, getApplicationContext());
                                        statusErrors = 0;
                                        readData.getRecentSensorRecords(sensorRecordListener);
                                    }
                                }
                            };
                            readData.getRecentCalRecords(calRecordListener);
                        } else if (wakeLock1 != null && wakeLock1.isHeld())
                            wakeLock1.release();
                    }
                };
                readData.readDisplayTimeOffset(dislpayTimeListener);
            } else if (wakeLock1 != null && wakeLock1.isHeld())
                wakeLock1.release();
        }
    };
    readData.readSystemTime(systemTimeListener);
}
Also used : Action1(rx.functions.Action1) EGVRecord(com.eveningoutpost.dexdrip.ImportedLibraries.dexcom.records.EGVRecord) Date(java.util.Date) PowerManager(android.os.PowerManager) SensorRecord(com.eveningoutpost.dexdrip.ImportedLibraries.dexcom.records.SensorRecord) CalRecord(com.eveningoutpost.dexdrip.ImportedLibraries.dexcom.records.CalRecord)

Example 45 with Action1

use of rx.functions.Action1 in project xDrip by NightscoutFoundation.

the class ReadDataShare method readDataBasePage.

private <T> T readDataBasePage(final int recordType, int page, final Action1<byte[]> fullPageListener) {
    byte numOfPages = 1;
    if (page < 0) {
        throw new IllegalArgumentException("Invalid page requested:" + page);
    }
    ArrayList<Byte> payload = new ArrayList<Byte>();
    payload.add((byte) recordType);
    byte[] pageInt = ByteBuffer.allocate(4).putInt(page).array();
    payload.add(pageInt[3]);
    payload.add(pageInt[2]);
    payload.add(pageInt[1]);
    payload.add(pageInt[0]);
    payload.add(numOfPages);
    accumulatedResponse = null;
    final Action1<byte[]> databasePageReader = new Action1<byte[]>() {

        @Override
        public void call(byte[] s) {
            Log.d("ReadDataShare", "Database Page Reader received SIZE: " + s.length);
            byte[] temp = s;
            if (accumulatedResponse == null) {
                accumulatedResponse = s;
            } else {
                try {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    outputStream.write(accumulatedResponse);
                    outputStream.write(temp);
                    accumulatedResponse = outputStream.toByteArray();
                    Log.d("ReadDataShare", "Combined Response length: " + accumulatedResponse.length);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (temp.length < 20) {
                Observable.just(accumulatedResponse).subscribe(fullPageListener).unsubscribe();
            }
        }
    };
    writeCommand(Constants.READ_DATABASE_PAGES, payload, databasePageReader);
    return null;
}
Also used : Action1(rx.functions.Action1) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

Action1 (rx.functions.Action1)108 Test (org.junit.Test)33 Action0 (rx.functions.Action0)28 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)24 UiThreadTest (android.support.test.annotation.UiThreadTest)20 Observable (rx.Observable)20 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)12 HystrixRuntimeException (com.netflix.hystrix.exception.HystrixRuntimeException)11 ArrayList (java.util.ArrayList)11 CountDownLatch (java.util.concurrent.CountDownLatch)11 TestSubscriber (rx.observers.TestSubscriber)10 AllTypes (io.realm.entities.AllTypes)9 List (java.util.List)9 TestCircuitBreaker (com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker)7 RunTestInLooperThread (io.realm.rule.RunTestInLooperThread)6 IOException (java.io.IOException)6 Func1 (rx.functions.Func1)6 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)5 Method (java.lang.reflect.Method)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5