Search in sources :

Example 31 with Observable

use of rx.Observable in project azure-sdk-for-java by Azure.

the class ManageWebAppSourceControlAsync method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(final Azure azure) {
    // New resources
    final String suffix = ".azurewebsites.net";
    final String app1Name = SdkContext.randomResourceName("webapp1-", 20);
    final String app2Name = SdkContext.randomResourceName("webapp2-", 20);
    final String app3Name = SdkContext.randomResourceName("webapp3-", 20);
    final String app4Name = SdkContext.randomResourceName("webapp4-", 20);
    final String app1Url = app1Name + suffix;
    final String app2Url = app2Name + suffix;
    final String app3Url = app3Name + suffix;
    final String app4Url = app4Name + suffix;
    final String planName = SdkContext.randomResourceName("jplan_", 15);
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);
    try {
        //============================================================
        // Create a web app with a new app service plan
        System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
        Observable<?> app1Observable = azure.webApps().define(app1Name).withRegion(Region.US_WEST).withNewResourceGroup(rgName).withNewWindowsPlan(PricingTier.STANDARD_S1).withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).createAsync().flatMap(new Func1<Indexable, Observable<?>>() {

            @Override
            public Observable<?> call(Indexable indexable) {
                if (indexable instanceof WebApp) {
                    WebApp app = (WebApp) indexable;
                    System.out.println("Created web app " + app.name());
                    return Observable.merge(Observable.just(indexable), app.getPublishingProfileAsync().map(new Func1<PublishingProfile, PublishingProfile>() {

                        @Override
                        public PublishingProfile call(PublishingProfile publishingProfile) {
                            System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
                            Utils.uploadFileToFtp(publishingProfile, "helloworld.war", ManageWebAppSourceControlAsync.class.getResourceAsStream("/helloworld.war"));
                            System.out.println("Deployment helloworld.war to web app " + app1Name + " completed");
                            return publishingProfile;
                        }
                    }));
                }
                return Observable.just(indexable);
            }
        });
        System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
        System.out.println("Creating another web app " + app3Name + "...");
        System.out.println("Creating another web app " + app4Name + "...");
        Observable<?> app234Observable = azure.appServices().appServicePlans().getByResourceGroupAsync(rgName, planName).flatMap(new Func1<AppServicePlan, Observable<Indexable>>() {

            @Override
            public Observable<Indexable> call(AppServicePlan plan) {
                return Observable.merge(azure.webApps().define(app2Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).withLocalGitSourceControl().withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).createAsync(), azure.webApps().define(app3Name).withExistingWindowsPlan(plan).withNewResourceGroup(rgName).defineSourceControl().withPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started").withBranch("master").attach().createAsync(), azure.webApps().define(app4Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).createAsync());
            }
        }).flatMap(new Func1<Indexable, Observable<?>>() {

            @Override
            public Observable<?> call(Indexable indexable) {
                if (indexable instanceof WebApp) {
                    WebApp app = (WebApp) indexable;
                    System.out.println("Created web app " + app.name());
                    if (!app.name().equals(app2Name)) {
                        return Observable.just(indexable);
                    }
                    // for the second web app Deploy a local Tomcat
                    return app.getPublishingProfileAsync().map(new Func1<PublishingProfile, PublishingProfile>() {

                        @Override
                        public PublishingProfile call(PublishingProfile profile) {
                            System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
                            Git git = null;
                            try {
                                git = Git.init().setDirectory(new File(ManageWebAppSourceControlAsync.class.getResource("/azure-samples-appservice-helloworld/").getPath())).call();
                                git.add().addFilepattern(".").call();
                                git.commit().setMessage("Initial commit").call();
                                PushCommand command = git.push();
                                command.setRemote(profile.gitUrl());
                                command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
                                command.setRefSpecs(new RefSpec("master:master"));
                                command.setForce(true);
                                command.call();
                            } catch (GitAPIException e) {
                                e.printStackTrace();
                            }
                            System.out.println("Deployment to web app " + app2Name + " completed");
                            return profile;
                        }
                    });
                }
                return Observable.just(indexable);
            }
        });
        Observable.merge(app1Observable, app234Observable).toBlocking().subscribe();
        // warm up
        System.out.println("Warming up " + app1Url + "/helloworld...");
        curl("http://" + app1Url + "/helloworld");
        System.out.println("Warming up " + app2Url + "/helloworld...");
        curl("http://" + app2Url + "/helloworld");
        System.out.println("Warming up " + app3Url + "...");
        curl("http://" + app3Url);
        System.out.println("Warming up " + app4Url + "...");
        curl("http://" + app4Url);
        Thread.sleep(5000);
        System.out.println("CURLing " + app1Url + "/helloworld...");
        System.out.println(curl("http://" + app1Url + "/helloworld"));
        System.out.println("CURLing " + app2Url + "/helloworld...");
        System.out.println(curl("http://" + app2Url + "/helloworld"));
        System.out.println("CURLing " + app3Url + "...");
        System.out.println(curl("http://" + app3Url));
        System.out.println("CURLing " + app4Url + "...");
        System.out.println(curl("http://" + app4Url));
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByNameAsync(rgName).toBlocking().subscribe();
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Observable(rx.Observable) PushCommand(org.eclipse.jgit.api.PushCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) AppServicePlan(com.microsoft.azure.management.appservice.AppServicePlan) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) PublishingProfile(com.microsoft.azure.management.appservice.PublishingProfile) Func1(rx.functions.Func1) File(java.io.File) WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 32 with Observable

use of rx.Observable in project azure-sdk-for-java by Azure.

the class VirtualNetworkGatewaysInner method generatevpnclientpackageWithServiceResponseAsync.

/**
     * Generates VPN client package for P2S client of the virtual network gateway in the specified resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param virtualNetworkGatewayName The name of the virtual network gateway.
     * @param processorArchitecture VPN client Processor Architecture. Possible values are: 'AMD64' and 'X86'. Possible values include: 'Amd64', 'X86'
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the String object
     */
public Observable<ServiceResponse<String>> generatevpnclientpackageWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayName, ProcessorArchitecture processorArchitecture) {
    if (resourceGroupName == null) {
        throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
    }
    if (virtualNetworkGatewayName == null) {
        throw new IllegalArgumentException("Parameter virtualNetworkGatewayName is required and cannot be null.");
    }
    if (this.client.subscriptionId() == null) {
        throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
    }
    if (processorArchitecture == null) {
        throw new IllegalArgumentException("Parameter processorArchitecture is required and cannot be null.");
    }
    final String apiVersion = "2016-12-01";
    VpnClientParameters parameters = new VpnClientParameters();
    parameters.withProcessorArchitecture(processorArchitecture);
    return service.generatevpnclientpackage(resourceGroupName, virtualNetworkGatewayName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() {

        @Override
        public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) {
            try {
                ServiceResponse<String> clientResponse = generatevpnclientpackageDelegate(response);
                return Observable.just(clientResponse);
            } catch (Throwable t) {
                return Observable.error(t);
            }
        }
    });
}
Also used : Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) ServiceResponse(com.microsoft.rest.ServiceResponse) VpnClientParameters(com.microsoft.azure.management.network.VpnClientParameters) Observable(rx.Observable) ResponseBody(okhttp3.ResponseBody)

Example 33 with Observable

use of rx.Observable in project azure-sdk-for-java by Azure.

the class ExternalChildResourceCollectionImpl method commitAsync.

/**
     * Commits the changes in the external child resource childCollection.
     * <p/>
     * This method returns an observable stream, its observer's onNext will be called for each successfully
     * committed resource followed by one call to 'onCompleted' or one call to 'onError' with a
     * {@link CompositeException } containing the list of exceptions where each exception describes the reason
     * for failure of a resource commit.
     *
     * @return the observable stream
     */
public Observable<FluentModelTImpl> commitAsync() {
    final ExternalChildResourceCollectionImpl<FluentModelTImpl, FluentModelT, InnerModelT, ParentImplT, ParentT> self = this;
    List<FluentModelTImpl> items = new ArrayList<>();
    for (FluentModelTImpl item : this.childCollection.values()) {
        items.add(item);
    }
    final List<Throwable> exceptionsList = Collections.synchronizedList(new ArrayList<Throwable>());
    Observable<FluentModelTImpl> deleteStream = Observable.from(items).filter(new Func1<FluentModelTImpl, Boolean>() {

        @Override
        public Boolean call(FluentModelTImpl childResource) {
            return childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeRemoved;
        }
    }).flatMap(new Func1<FluentModelTImpl, Observable<FluentModelTImpl>>() {

        @Override
        public Observable<FluentModelTImpl> call(final FluentModelTImpl childResource) {
            return childResource.deleteAsync().map(new Func1<Void, FluentModelTImpl>() {

                @Override
                public FluentModelTImpl call(Void response) {
                    return childResource;
                }
            }).doOnNext(new Action1<FluentModelTImpl>() {

                @Override
                public void call(FluentModelTImpl childResource) {
                    childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None);
                    self.childCollection.remove(childResource.name());
                }
            }).onErrorResumeNext(new Func1<Throwable, Observable<FluentModelTImpl>>() {

                @Override
                public Observable<FluentModelTImpl> call(Throwable throwable) {
                    exceptionsList.add(throwable);
                    return Observable.empty();
                }
            });
        }
    });
    Observable<FluentModelTImpl> createStream = Observable.from(items).filter(new Func1<FluentModelTImpl, Boolean>() {

        @Override
        public Boolean call(FluentModelTImpl childResource) {
            return childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeCreated;
        }
    }).flatMap(new Func1<FluentModelTImpl, Observable<FluentModelTImpl>>() {

        @Override
        public Observable<FluentModelTImpl> call(final FluentModelTImpl childResource) {
            return childResource.createAsync().map(new Func1<FluentModelT, FluentModelTImpl>() {

                @Override
                public FluentModelTImpl call(FluentModelT fluentModelT) {
                    return childResource;
                }
            }).doOnNext(new Action1<FluentModelTImpl>() {

                @Override
                public void call(FluentModelTImpl fluentModelT) {
                    childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None);
                }
            }).onErrorResumeNext(new Func1<Throwable, Observable<? extends FluentModelTImpl>>() {

                @Override
                public Observable<FluentModelTImpl> call(Throwable throwable) {
                    self.childCollection.remove(childResource.name());
                    exceptionsList.add(throwable);
                    return Observable.empty();
                }
            });
        }
    });
    Observable<FluentModelTImpl> updateStream = Observable.from(items).filter(new Func1<FluentModelTImpl, Boolean>() {

        @Override
        public Boolean call(FluentModelTImpl childResource) {
            return childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeUpdated;
        }
    }).flatMap(new Func1<FluentModelTImpl, Observable<FluentModelTImpl>>() {

        @Override
        public Observable<FluentModelTImpl> call(final FluentModelTImpl childResource) {
            return childResource.updateAsync().map(new Func1<FluentModelT, FluentModelTImpl>() {

                @Override
                public FluentModelTImpl call(FluentModelT e) {
                    return childResource;
                }
            }).doOnNext(new Action1<FluentModelTImpl>() {

                @Override
                public void call(FluentModelTImpl childResource) {
                    childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None);
                }
            }).onErrorResumeNext(new Func1<Throwable, Observable<? extends FluentModelTImpl>>() {

                @Override
                public Observable<FluentModelTImpl> call(Throwable throwable) {
                    exceptionsList.add(throwable);
                    return Observable.empty();
                }
            });
        }
    });
    final PublishSubject<FluentModelTImpl> aggregatedErrorStream = PublishSubject.create();
    Observable<FluentModelTImpl> operationsStream = Observable.merge(deleteStream, createStream, updateStream).doOnTerminate(new Action0() {

        @Override
        public void call() {
            if (clearAfterCommit()) {
                self.childCollection.clear();
            }
            if (exceptionsList.isEmpty()) {
                aggregatedErrorStream.onCompleted();
            } else {
                aggregatedErrorStream.onError(new CompositeException(exceptionsList));
            }
        }
    });
    Observable<FluentModelTImpl> stream = Observable.concat(operationsStream, aggregatedErrorStream);
    return stream;
}
Also used : Action0(rx.functions.Action0) CompositeException(rx.exceptions.CompositeException) ArrayList(java.util.ArrayList) Observable(rx.Observable) Func1(rx.functions.Func1)

Example 34 with Observable

use of rx.Observable in project azure-sdk-for-java by Azure.

the class NetworkWatchersInner method getTopologyWithServiceResponseAsync.

/**
     * Gets the current network topology by resource group.
     *
     * @param resourceGroupName The name of the resource group.
     * @param networkWatcherName The name of the network watcher.
     * @param targetResourceGroupName The name of the target resource group to perform topology on.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the TopologyInner object
     */
public Observable<ServiceResponse<TopologyInner>> getTopologyWithServiceResponseAsync(String resourceGroupName, String networkWatcherName, String targetResourceGroupName) {
    if (resourceGroupName == null) {
        throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
    }
    if (networkWatcherName == null) {
        throw new IllegalArgumentException("Parameter networkWatcherName is required and cannot be null.");
    }
    if (this.client.subscriptionId() == null) {
        throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
    }
    if (targetResourceGroupName == null) {
        throw new IllegalArgumentException("Parameter targetResourceGroupName is required and cannot be null.");
    }
    final String apiVersion = "2016-12-01";
    TopologyParameters parameters = new TopologyParameters();
    parameters.withTargetResourceGroupName(targetResourceGroupName);
    return service.getTopology(resourceGroupName, networkWatcherName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<TopologyInner>>>() {

        @Override
        public Observable<ServiceResponse<TopologyInner>> call(Response<ResponseBody> response) {
            try {
                ServiceResponse<TopologyInner> clientResponse = getTopologyDelegate(response);
                return Observable.just(clientResponse);
            } catch (Throwable t) {
                return Observable.error(t);
            }
        }
    });
}
Also used : Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) ServiceResponse(com.microsoft.rest.ServiceResponse) Observable(rx.Observable) TopologyParameters(com.microsoft.azure.management.network.TopologyParameters) ResponseBody(okhttp3.ResponseBody)

Example 35 with Observable

use of rx.Observable in project azure-sdk-for-java by Azure.

the class KeyVaultClientImpl method setCertificateIssuerWithServiceResponseAsync.

/**
     * Sets the specified certificate issuer.
     *
     * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
     * @param issuerName The name of the issuer.
     * @param provider The issuer provider.
     * @return the observable to the IssuerBundle object
     */
public Observable<ServiceResponse<IssuerBundle>> setCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName, String provider) {
    if (vaultBaseUrl == null) {
        throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null.");
    }
    if (issuerName == null) {
        throw new IllegalArgumentException("Parameter issuerName is required and cannot be null.");
    }
    if (this.apiVersion() == null) {
        throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null.");
    }
    if (provider == null) {
        throw new IllegalArgumentException("Parameter provider is required and cannot be null.");
    }
    final IssuerCredentials credentials = null;
    final OrganizationDetails organizationDetails = null;
    final IssuerAttributes attributes = null;
    CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters();
    parameter.withProvider(provider);
    parameter.withCredentials(null);
    parameter.withOrganizationDetails(null);
    parameter.withAttributes(null);
    String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl);
    return service.setCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameter, parameterizedHost, this.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<IssuerBundle>>>() {

        @Override
        public Observable<ServiceResponse<IssuerBundle>> call(Response<ResponseBody> response) {
            try {
                ServiceResponse<IssuerBundle> clientResponse = setCertificateIssuerDelegate(response);
                return Observable.just(clientResponse);
            } catch (Throwable t) {
                return Observable.error(t);
            }
        }
    });
}
Also used : OrganizationDetails(com.microsoft.azure.keyvault.models.OrganizationDetails) IssuerAttributes(com.microsoft.azure.keyvault.models.IssuerAttributes) CertificateIssuerSetParameters(com.microsoft.azure.keyvault.models.CertificateIssuerSetParameters) Observable(rx.Observable) ResponseBody(okhttp3.ResponseBody) Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) IssuerBundle(com.microsoft.azure.keyvault.models.IssuerBundle) ServiceResponse(com.microsoft.rest.ServiceResponse) IssuerCredentials(com.microsoft.azure.keyvault.models.IssuerCredentials)

Aggregations

Observable (rx.Observable)311 ResponseBody (okhttp3.ResponseBody)119 Response (retrofit2.Response)111 ServiceResponse (com.microsoft.rest.ServiceResponse)108 Test (org.junit.Test)59 ArrayList (java.util.ArrayList)57 List (java.util.List)55 IOException (java.io.IOException)46 Subscription (rx.Subscription)34 Func1 (rx.functions.Func1)31 Map (java.util.Map)26 ByteBuf (io.netty.buffer.ByteBuf)24 TimeUnit (java.util.concurrent.TimeUnit)23 Schedulers (rx.schedulers.Schedulers)22 Collections (java.util.Collections)20 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)18 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)18 File (java.io.File)17 HashMap (java.util.HashMap)16 Subscriber (rx.Subscriber)15