Search in sources :

Example 31 with Subscriber

use of rx.Subscriber in project azure-tools-for-java by Microsoft.

the class AzureDockerCertVaultOps method getVault.

public static AzureDockerCertVault getVault(AzureDockerCertVault certVault, KeyVaultClient keyVaultClient) throws AzureDockerException {
    if (certVault == null || keyVaultClient == null || certVault.uri == null) {
        throw new AzureDockerException("Unexpected argument values; azureClient, vault name and resourceGroupName cannot be null");
    }
    String vaultUri = certVault.uri;
    try {
        SecretBundle secret = keyVaultClient.getSecret(vaultUri, SECRETENTRY_DOCKERHOSTNAMES);
        if (secret != null) {
            certVault.hostName = secret.value();
        } else {
            certVault.hostName = null;
            return null;
        }
    } catch (Exception e) {
        return null;
    }
    //Execute Key Vault Secret read in parallel
    Map<String, String> secretNamesAndValueMap = new HashMap<>();
    Observable.from(DOCKERHOST_SECRETS).flatMap(secretName -> {
        return Observable.create(new Observable.OnSubscribe<Pair<String, String>>() {

            @Override
            public void call(Subscriber<? super Pair<String, String>> subscriber) {
                keyVaultClient.getSecretAsync(vaultUri, secretName, new ServiceCallback<SecretBundle>() {

                    @Override
                    public void failure(Throwable throwable) {
                        subscriber.onCompleted();
                    }

                    @Override
                    public void success(SecretBundle secretBundle) {
                        if (secretBundle != null) {
                            subscriber.onNext(new Pair<>(secretName, secretBundle.value()));
                        }
                        subscriber.onCompleted();
                    }
                });
            }
        }).subscribeOn(Schedulers.io());
    }, 5).subscribeOn(Schedulers.io()).toBlocking().subscribe(new Action1<Pair<String, String>>() {

        @Override
        public void call(Pair<String, String> secretNameAndValue) {
            secretNamesAndValueMap.put(secretNameAndValue.first(), secretNameAndValue.second());
        }
    });
    String currentSecretValue;
    currentSecretValue = secretNamesAndValueMap.get("vmUsername");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.vmUsername = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("vmPwd");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.vmPwd = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("sshKey");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.sshKey = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("sshPubKey");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.sshPubKey = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("tlsCACert");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.tlsCACert = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("tlsCAKey");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.tlsCAKey = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("tlsClientCert");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.tlsClientCert = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("tlsClientKey");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.tlsClientKey = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("tlsServerCert");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.tlsServerCert = currentSecretValue;
    }
    currentSecretValue = secretNamesAndValueMap.get("tlsServerKey");
    if (currentSecretValue != null && !currentSecretValue.isEmpty()) {
        certVault.tlsServerKey = currentSecretValue;
    }
    return certVault;
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) JSch(com.jcraft.jsch.JSch) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Action1(rx.functions.Action1) DEBUG(com.microsoft.azure.docker.ops.utils.AzureDockerUtils.DEBUG) SecretBundle(com.microsoft.azure.keyvault.models.SecretBundle) Observable(rx.Observable) Azure(com.microsoft.azure.management.Azure) Map(java.util.Map) Schedulers(rx.schedulers.Schedulers) DefaultLoader(com.microsoft.tooling.msservices.components.DefaultLoader) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Vault(com.microsoft.azure.management.keyvault.Vault) Subscriber(rx.Subscriber) ServiceCallback(com.microsoft.rest.ServiceCallback) Files(java.nio.file.Files) AzureDockerUtils(com.microsoft.azure.docker.ops.utils.AzureDockerUtils) FileWriter(java.io.FileWriter) Pair(com.microsoft.azuretools.utils.Pair) SetSecretRequest(com.microsoft.azure.keyvault.requests.SetSecretRequest) SecretPermissions(com.microsoft.azure.management.keyvault.SecretPermissions) List(java.util.List) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) AzureDockerCertVault(com.microsoft.azure.docker.model.AzureDockerCertVault) Paths(java.nio.file.Paths) CloudException(com.microsoft.azure.CloudException) KeyVaultClient(com.microsoft.azure.keyvault.KeyVaultClient) HashMap(java.util.HashMap) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) CloudException(com.microsoft.azure.CloudException) Observable(rx.Observable) SecretBundle(com.microsoft.azure.keyvault.models.SecretBundle) ServiceCallback(com.microsoft.rest.ServiceCallback) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) KeyPair(com.jcraft.jsch.KeyPair) Pair(com.microsoft.azuretools.utils.Pair)

Example 32 with Subscriber

use of rx.Subscriber in project android-oss by kickstarter.

the class ApiErrorOperator method call.

@Override
public Subscriber<? super Response<T>> call(@NonNull final Subscriber<? super T> subscriber) {
    return new Subscriber<retrofit2.Response<T>>() {

        @Override
        public void onCompleted() {
            if (!subscriber.isUnsubscribed()) {
                subscriber.onCompleted();
            }
        }

        @Override
        public void onError(@NonNull final Throwable e) {
            if (!subscriber.isUnsubscribed()) {
                subscriber.onError(e);
            }
        }

        @Override
        public void onNext(@NonNull final retrofit2.Response<T> response) {
            if (subscriber.isUnsubscribed()) {
                return;
            }
            if (!response.isSuccess()) {
                try {
                    final ErrorEnvelope envelope = gson.fromJson(response.errorBody().string(), ErrorEnvelope.class);
                    subscriber.onError(new ApiException(envelope, response));
                } catch (@NonNull final IOException e) {
                    subscriber.onError(new ResponseException(response));
                }
            }
            subscriber.onNext(response.body());
        }
    };
}
Also used : Response(retrofit2.Response) Subscriber(rx.Subscriber) ResponseException(com.kickstarter.services.ResponseException) NonNull(android.support.annotation.NonNull) ErrorEnvelope(com.kickstarter.services.apiresponses.ErrorEnvelope) IOException(java.io.IOException) ApiException(com.kickstarter.services.ApiException)

Example 33 with Subscriber

use of rx.Subscriber in project archi by ivacf.

the class MainPresenter method loadRepositories.

public void loadRepositories(String usernameEntered) {
    String username = usernameEntered.trim();
    if (username.isEmpty())
        return;
    mainMvpView.showProgressIndicator();
    if (subscription != null)
        subscription.unsubscribe();
    ArchiApplication application = ArchiApplication.get(mainMvpView.getContext());
    GithubService githubService = application.getGithubService();
    subscription = githubService.publicRepositories(username).observeOn(AndroidSchedulers.mainThread()).subscribeOn(application.defaultSubscribeScheduler()).subscribe(new Subscriber<List<Repository>>() {

        @Override
        public void onCompleted() {
            Log.i(TAG, "Repos loaded " + repositories);
            if (!repositories.isEmpty()) {
                mainMvpView.showRepositories(repositories);
            } else {
                mainMvpView.showMessage(R.string.text_empty_repos);
            }
        }

        @Override
        public void onError(Throwable error) {
            Log.e(TAG, "Error loading GitHub repos ", error);
            if (isHttp404(error)) {
                mainMvpView.showMessage(R.string.error_username_not_found);
            } else {
                mainMvpView.showMessage(R.string.error_loading_repos);
            }
        }

        @Override
        public void onNext(List<Repository> repositories) {
            MainPresenter.this.repositories = repositories;
        }
    });
}
Also used : GithubService(uk.ivanc.archimvp.model.GithubService) Repository(uk.ivanc.archimvp.model.Repository) ArchiApplication(uk.ivanc.archimvp.ArchiApplication) Subscriber(rx.Subscriber) List(java.util.List)

Example 34 with Subscriber

use of rx.Subscriber in project archi by ivacf.

the class MainActivity method loadGithubRepos.

public void loadGithubRepos(String username) {
    progressBar.setVisibility(View.VISIBLE);
    reposRecycleView.setVisibility(View.GONE);
    infoTextView.setVisibility(View.GONE);
    ArchiApplication application = ArchiApplication.get(this);
    GithubService githubService = application.getGithubService();
    subscription = githubService.publicRepositories(username).observeOn(AndroidSchedulers.mainThread()).subscribeOn(application.defaultSubscribeScheduler()).subscribe(new Subscriber<List<Repository>>() {

        @Override
        public void onCompleted() {
            progressBar.setVisibility(View.GONE);
            if (reposRecycleView.getAdapter().getItemCount() > 0) {
                reposRecycleView.requestFocus();
                hideSoftKeyboard();
                reposRecycleView.setVisibility(View.VISIBLE);
            } else {
                infoTextView.setText(R.string.text_empty_repos);
                infoTextView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onError(Throwable error) {
            Log.e(TAG, "Error loading GitHub repos ", error);
            progressBar.setVisibility(View.GONE);
            if (error instanceof HttpException && ((HttpException) error).code() == 404) {
                infoTextView.setText(R.string.error_username_not_found);
            } else {
                infoTextView.setText(R.string.error_loading_repos);
            }
            infoTextView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onNext(List<Repository> repositories) {
            Log.i(TAG, "Repos loaded " + repositories);
            RepositoryAdapter adapter = (RepositoryAdapter) reposRecycleView.getAdapter();
            adapter.setRepositories(repositories);
            adapter.notifyDataSetChanged();
        }
    });
}
Also used : GithubService(uk.ivanc.archi.model.GithubService) Repository(uk.ivanc.archi.model.Repository) Subscriber(rx.Subscriber) HttpException(retrofit2.adapter.rxjava.HttpException) List(java.util.List)

Example 35 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnTimeout.

private RequestContextTestResults testRequestContextOnTimeout(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).withExecutionTimeoutInMilliseconds(50))) {

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

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    // ignore the interrupted exception
                    }
                }
            }).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(1, results.ts.getOnErrorEvents().size());
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isResponseTimedOut());
    assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Notification(rx.Notification)

Aggregations

Subscriber (rx.Subscriber)50 List (java.util.List)16 Observable (rx.Observable)16 IOException (java.io.IOException)11 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)10 Action1 (rx.functions.Action1)10 Schedulers (rx.schedulers.Schedulers)10 Context (android.content.Context)8 ArrayList (java.util.ArrayList)8 OnSubscribe (rx.Observable.OnSubscribe)8 TestCircuitBreaker (com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker)7 RxException (com.yydcdut.note.model.rx.exception.RxException)7 Notification (rx.Notification)7 TestSubscriber (rx.observers.TestSubscriber)7 File (java.io.File)6 Cursor (android.database.Cursor)5 View (android.view.View)5 ContextLife (com.yydcdut.note.injector.ContextLife)5 Map (java.util.Map)5 Inject (javax.inject.Inject)5