Search in sources :

Example 21 with Subscriber

use of rx.Subscriber in project PhotoNoter by yydcdut.

the class RxUser method getQQ.

public Observable<IUser> getQQ() {
    return Observable.create(new Observable.OnSubscribe<IUser>() {

        @Override
        public void call(Subscriber<? super IUser> subscriber) {
            if (mQQUser == null) {
                String name = mSharedPreferences.getString(Q_NAME, NAME_DEFAULT);
                String netImagePath = mSharedPreferences.getString(Q_NET_IMAGE_PATH, Q_NET_IMAGE_PATH_DEFAULT);
                if (TextUtils.isEmpty(name) || TextUtils.isEmpty(netImagePath)) {
                    subscriber.onError(new RxException("没有登录!!!"));
                    return;
                } else {
                    mQQUser = new QQUser(name, netImagePath);
                }
            }
            subscriber.onNext(mQQUser);
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.io());
}
Also used : Subscriber(rx.Subscriber) IUser(com.yydcdut.note.entity.user.IUser) RxException(com.yydcdut.note.model.rx.exception.RxException) QQUser(com.yydcdut.note.entity.user.QQUser)

Example 22 with Subscriber

use of rx.Subscriber in project PhotoNoter by yydcdut.

the class RxUser method getEvernote.

public Observable<IUser> getEvernote() {
    return Observable.create(new Observable.OnSubscribe<IUser>() {

        @Override
        public void call(Subscriber<? super IUser> subscriber) {
            if (mEvernoteUser == null) {
                String name = mSharedPreferences.getString(EVERNOTE_NAME, NAME_DEFAULT);
                if (TextUtils.isEmpty(name)) {
                    subscriber.onError(new RxException("没有登录!!!"));
                } else {
                    mEvernoteUser = new EvernoteUser(name);
                }
            }
            subscriber.onNext(mEvernoteUser);
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.io());
}
Also used : Subscriber(rx.Subscriber) EvernoteUser(com.yydcdut.note.entity.user.EvernoteUser) IUser(com.yydcdut.note.entity.user.IUser) RxException(com.yydcdut.note.model.rx.exception.RxException)

Example 23 with Subscriber

use of rx.Subscriber in project PhotoNoter by yydcdut.

the class RxUser method updateNote2Evernote.

public Observable<Boolean> updateNote2Evernote(String bigPhotoPathWithoutFile, String photoName, String noteTitle, String noteContent) {
    return Observable.create(new Observable.OnSubscribe<List<Notebook>>() {

        @Override
        public void call(Subscriber<? super List<Notebook>> subscriber) {
            if (mEvernoteSession == null) {
                mEvernoteSession = new EvernoteSession.Builder(mContext).setLocale(Locale.SIMPLIFIED_CHINESE).setEvernoteService(EVERNOTE_SERVICE).setSupportAppLinkedNotebooks(SUPPORT_APP_LINKED_NOTEBOOKS).setForceAuthenticationInThirdPartyApp(true).build(BuildConfig.EVERNOTE_CONSUMER_KEY, BuildConfig.EVERNOTE_CONSUMER_SECRET).asSingleton();
            }
            EvernoteNoteStoreClient noteStoreClient = mEvernoteSession.getEvernoteClientFactory().getNoteStoreClient();
            try {
                List<Notebook> notebookList = noteStoreClient.listNotebooks();
                subscriber.onNext(notebookList);
            } catch (EDAMUserException e) {
                YLog.e(e);
                subscriber.onError(e);
            } catch (EDAMSystemException e) {
                YLog.e(e);
                subscriber.onError(e);
            } catch (TException e) {
                YLog.e(e);
                subscriber.onError(e);
            }
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.io()).flatMap(notebooks -> Observable.from(notebooks)).filter(notebook -> notebook.getName().equals(mContext.getResources().getString(R.string.app_name))).lift(new Observable.Operator<String, Notebook>() {

        @Override
        public Subscriber<? super Notebook> call(Subscriber<? super String> subscriber) {
            return new Subscriber<Notebook>() {

                private int mInTimes = 0;

                @Override
                public void onCompleted() {
                    if (mInTimes == 0) {
                        Notebook notebook = new Notebook();
                        notebook.setName(mContext.getResources().getString(R.string.app_name));
                        EvernoteNoteStoreClient noteStoreClient = mEvernoteSession.getEvernoteClientFactory().getNoteStoreClient();
                        try {
                            Notebook appNoteBook = noteStoreClient.createNotebook(notebook);
                            subscriber.onNext(appNoteBook.getGuid());
                        } catch (EDAMUserException e) {
                            YLog.e(e);
                            subscriber.onError(e);
                        } catch (EDAMSystemException e) {
                            YLog.e(e);
                            subscriber.onError(e);
                        } catch (TException e) {
                            YLog.e(e);
                            subscriber.onError(e);
                        }
                    }
                    subscriber.onCompleted();
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onNext(Notebook notebook) {
                    mInTimes++;
                    subscriber.onNext(notebook.getGuid());
                }
            };
        }
    }).map(s -> {
        Note note = new Note();
        note.setNotebookGuid(s);
        return note;
    }).lift(new Observable.Operator<Boolean, Note>() {

        @Override
        public Subscriber<? super Note> call(Subscriber<? super Boolean> subscriber) {
            return new Subscriber<Note>() {

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

                @Override
                public void onError(Throwable e) {
                    subscriber.onError(e);
                }

                @Override
                public void onNext(Note note) {
                    note.setTitle(noteTitle);
                    InputStream in = null;
                    // Hash the data in the image file. The hash is used to reference the file in the ENML note content.
                    try {
                        in = new BufferedInputStream(new FileInputStream(bigPhotoPathWithoutFile));
                        FileData data = new FileData(EvernoteUtil.hash(in), new File(bigPhotoPathWithoutFile));
                        ResourceAttributes attributes = new ResourceAttributes();
                        attributes.setFileName(photoName);
                        // Create a new Resource
                        Resource resource = new Resource();
                        resource.setData(data);
                        resource.setMime("image/jpeg");
                        resource.setAttributes(attributes);
                        note.addToResources(resource);
                        // Set the note's ENML content
                        String content = EvernoteUtil.NOTE_PREFIX + noteContent + EvernoteUtil.createEnMediaTag(resource) + EvernoteUtil.NOTE_SUFFIX;
                        note.setContent(content);
                        EvernoteNoteStoreClient noteStoreClient = mEvernoteSession.getEvernoteClientFactory().getNoteStoreClient();
                        noteStoreClient.createNote(note);
                    } catch (FileNotFoundException e) {
                        YLog.e(e);
                        subscriber.onError(e);
                    } catch (IOException e) {
                        YLog.e(e);
                        subscriber.onError(e);
                    } catch (EDAMNotFoundException e) {
                        YLog.e(e);
                        subscriber.onError(e);
                    } catch (TException e) {
                        YLog.e(e);
                        subscriber.onError(e);
                    } catch (EDAMUserException e) {
                        YLog.e(e);
                        subscriber.onError(e);
                    } catch (EDAMSystemException e) {
                        YLog.e(e);
                        subscriber.onError(e);
                    } finally {
                        FilePathUtils.closeStream(in);
                    }
                    subscriber.onNext(true);
                }
            };
        }
    });
}
Also used : TException(com.evernote.thrift.TException) EDAMSystemException(com.evernote.edam.error.EDAMSystemException) Context(android.content.Context) BufferedInputStream(java.io.BufferedInputStream) Singleton(javax.inject.Singleton) Observable(rx.Observable) Inject(javax.inject.Inject) EvernoteUtil(com.evernote.client.android.EvernoteUtil) ResourceAttributes(com.evernote.edam.type.ResourceAttributes) JSONException(org.json.JSONException) Notebook(com.evernote.edam.type.Notebook) JSONObject(org.json.JSONObject) TException(com.evernote.thrift.TException) User(com.evernote.edam.type.User) Locale(java.util.Locale) ContextLife(com.yydcdut.note.injector.ContextLife) FilePathUtils(com.yydcdut.note.utils.FilePathUtils) Schedulers(rx.schedulers.Schedulers) QQToken(com.tencent.connect.auth.QQToken) R(com.yydcdut.note.R) EvernoteUser(com.yydcdut.note.entity.user.EvernoteUser) WeakReference(java.lang.ref.WeakReference) Tencent(com.tencent.tauth.Tencent) Subscriber(rx.Subscriber) Resource(com.evernote.edam.type.Resource) IUser(com.yydcdut.note.entity.user.IUser) EDAMUserException(com.evernote.edam.error.EDAMUserException) TextUtils(android.text.TextUtils) EDAMNotFoundException(com.evernote.edam.error.EDAMNotFoundException) QQUser(com.yydcdut.note.entity.user.QQUser) IOException(java.io.IOException) UserInfo(com.tencent.connect.UserInfo) FileInputStream(java.io.FileInputStream) Note(com.evernote.edam.type.Note) FileData(com.evernote.client.conn.mobile.FileData) UiError(com.tencent.tauth.UiError) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) EvernoteNoteStoreClient(com.evernote.client.android.asyncclient.EvernoteNoteStoreClient) RxException(com.yydcdut.note.model.rx.exception.RxException) List(java.util.List) IUiListener(com.tencent.tauth.IUiListener) SharedPreferences(android.content.SharedPreferences) EvernoteSession(com.evernote.client.android.EvernoteSession) BuildConfig(com.yydcdut.note.BuildConfig) Activity(android.app.Activity) YLog(com.yydcdut.note.utils.YLog) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) EDAMUserException(com.evernote.edam.error.EDAMUserException) EDAMSystemException(com.evernote.edam.error.EDAMSystemException) Subscriber(rx.Subscriber) BufferedInputStream(java.io.BufferedInputStream) List(java.util.List) FileData(com.evernote.client.conn.mobile.FileData) Notebook(com.evernote.edam.type.Notebook) EvernoteNoteStoreClient(com.evernote.client.android.asyncclient.EvernoteNoteStoreClient) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(com.evernote.edam.type.Resource) IOException(java.io.IOException) Observable(rx.Observable) FileInputStream(java.io.FileInputStream) ResourceAttributes(com.evernote.edam.type.ResourceAttributes) EDAMNotFoundException(com.evernote.edam.error.EDAMNotFoundException) Note(com.evernote.edam.type.Note) File(java.io.File)

Example 24 with Subscriber

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

the class AzureDockerUtils method refreshDockerSubscriptions.

public static Map<String, AzureDockerSubscription> refreshDockerSubscriptions(AzureManager azureAuthManager) {
    Map<String, AzureDockerSubscription> subsMap = new HashMap<>();
    try {
        if (DEBUG)
            System.out.format("Get AzureDockerHostsManage subscription details: %s\n", new Date().toString());
        SubscriptionManager subscriptionManager = azureAuthManager.getSubscriptionManager();
        List<SubscriptionDetail> subscriptions = subscriptionManager.getSubscriptionDetails();
        if (subscriptions != null) {
            if (DEBUG)
                System.out.format("Get AzureDockerHostsManage Docker subscription details: %s\n", new Date().toString());
            Observable.from(subscriptions).flatMap(subscriptionDetail -> {
                return Observable.create(new Observable.OnSubscribe<AzureDockerSubscription>() {

                    @Override
                    public void call(Subscriber<? super AzureDockerSubscription> dockerSubscriptionSubscriber) {
                        if (subscriptionDetail.isSelected()) {
                            AzureDockerSubscription dockerSubscription = new AzureDockerSubscription();
                            dockerSubscription.id = subscriptionDetail.getSubscriptionId();
                            try {
                                if (DEBUG)
                                    System.out.format("\tGet AzureDockerHostsManage Docker subscription: %s at %s\n", dockerSubscription.id, new Date().toString());
                                dockerSubscription.tid = subscriptionDetail.getTenantId();
                                dockerSubscription.name = subscriptionDetail.getSubscriptionName();
                                dockerSubscription.azureClient = azureAuthManager.getAzure(dockerSubscription.id);
                                dockerSubscription.keyVaultClient = azureAuthManager.getKeyVaultClient(subscriptionDetail.getTenantId());
                                dockerSubscription.isSelected = true;
                                if (AzureDockerUtils.hasServicePrincipalAzureManager(azureAuthManager)) {
                                    dockerSubscription.userId = null;
                                    dockerSubscription.servicePrincipalId = azureAuthManager.getCurrentUserId();
                                } else {
                                    dockerSubscription.userId = azureAuthManager.getCurrentUserId();
                                    dockerSubscription.servicePrincipalId = null;
                                }
                                dockerSubscriptionSubscriber.onNext(dockerSubscription);
                            } catch (Exception e) {
                                e.printStackTrace();
                                DefaultLoader.getUIHelper().showError(e.getMessage(), "Error Loading Subscription Details for " + dockerSubscription.id);
                            }
                        }
                        dockerSubscriptionSubscriber.onCompleted();
                    }
                }).subscribeOn(Schedulers.io());
            }).subscribeOn(Schedulers.io()).toBlocking().subscribe(new Action1<AzureDockerSubscription>() {

                @Override
                public void call(AzureDockerSubscription dockerSubscription) {
                    subsMap.put(dockerSubscription.id, dockerSubscription);
                }
            });
        }
        if (DEBUG)
            System.out.format("Get AzureDockerHostsManage locations: %s\n", new Date().toString());
        List<Subscription> azureSubscriptionList = azureAuthManager.getSubscriptions();
        for (Subscription subscription : azureSubscriptionList) {
            AzureDockerSubscription dockerSubscription = subsMap.get(subscription.subscriptionId());
            if (dockerSubscription != null) {
                List<String> locations = subscription.listLocations().stream().sorted(Comparator.comparing(Location::displayName)).map(o -> o.name().toLowerCase()).collect(Collectors.toList());
                dockerSubscription.locations = locations;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        DefaultLoader.getUIHelper().showError(e.getMessage(), "Error loading subscription details");
    }
    return subsMap;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) java.util(java.util) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) URL(java.net.URL) Subnet(com.microsoft.azure.management.network.Subnet) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) Callable(java.util.concurrent.Callable) Action1(rx.functions.Action1) Location(com.microsoft.azure.management.resources.Location) Observable(rx.Observable) Azure(com.microsoft.azure.management.Azure) Network(com.microsoft.azure.management.network.Network) Func1(rx.functions.Func1) ServicePrincipalAzureManager(com.microsoft.azuretools.sdkmanage.ServicePrincipalAzureManager) Schedulers(rx.schedulers.Schedulers) DefaultLoader(com.microsoft.tooling.msservices.components.DefaultLoader) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) Vault(com.microsoft.azure.management.keyvault.Vault) Subscription(com.microsoft.azure.management.resources.Subscription) SubscriptionManager(com.microsoft.azuretools.authmanage.SubscriptionManager) Subscriber(rx.Subscriber) AzureDockerCertVaultOps(com.microsoft.azure.docker.ops.AzureDockerCertVaultOps) AzureRegisterProviderNamespaces(com.microsoft.azuretools.utils.AzureRegisterProviderNamespaces) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) Pair(com.microsoft.azuretools.utils.Pair) CountDownLatch(java.util.concurrent.CountDownLatch) Action0(rx.functions.Action0) com.microsoft.azure.docker.model(com.microsoft.azure.docker.model) AzureDockerVMOps(com.microsoft.azure.docker.ops.AzureDockerVMOps) KeyVaultClient(com.microsoft.azure.keyvault.KeyVaultClient) SubscriptionManager(com.microsoft.azuretools.authmanage.SubscriptionManager) Observable(rx.Observable) UnknownHostException(java.net.UnknownHostException) SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) Subscription(com.microsoft.azure.management.resources.Subscription)

Example 25 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)

Aggregations

Subscriber (rx.Subscriber)48 List (java.util.List)16 Observable (rx.Observable)15 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 Cursor (android.database.Cursor)5 ContextLife (com.yydcdut.note.injector.ContextLife)5 Map (java.util.Map)5 Inject (javax.inject.Inject)5 Subscription (rx.Subscription)5 Action0 (rx.functions.Action0)5