org.cloudfoundry.client.lib.CloudFoundryOperations - java examples

Here are the examples of the java api org.cloudfoundry.client.lib.CloudFoundryOperations taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

40 Examples 7

19 View Complete Implementation : CloudFoundryLoginHandler.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/**
 * @return true if there was a proxy update. False any other case.
 * @throws CoreException
 */
public boolean updateProxyInClient(CloudFoundryOperations client) throws CoreException {
    // if (client != null && cloudURL != null) {
    // try {
    // URL actualUrl = new URL(cloudURL);
    // HttpProxyConfiguration proxyConfiguration =
    // CloudFoundryClientFactory.getProxy(actualUrl);
    // // FIXNS: As of CF Java client-lib version 1.0.2, update proxy
    // // API has been removed. Therefore unless a new client
    // // is created on proxy change, or the client indirectly detects
    // // proxy changes via system properties
    // // Proxy support for CF Eclipse will not work unless a user
    // // reconnects the server instance when the client
    // // is created.
    // client.updateHttpProxyConfiguration(proxyConfiguration);
    // 
    // return true;
    // }
    // catch (MalformedURLException e) {
    // throw
    // CloudErrorUtil.toCoreException("Failed to update proxy settings due to "
    // + e.getMessage(), e);
    // }
    // }
    return false;
}

19 View Complete Implementation : CloudFoundryLoginHandler.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public clreplaced CloudFoundryLoginHandler {

    private final CloudFoundryOperations operations;

    private static final String DEFAULT_PROGRESS_LABEL = Messages.CloudFoundryLoginHandler_LABEL_PERFORM_CF_OPERATION;

    private static final int DEFAULT_PROGRESS_TICKS = 100;

    /**
     * @param operations must not be null
     * @param cloudServer can be null if no server has been created yet
     */
    public CloudFoundryLoginHandler(CloudFoundryOperations operations) {
        this.operations = operations;
    }

    /**
     * Attempts to log in once. If login fails, Core exception is thrown
     * @throws CoreException if login failed. The reason for the login failure
     * is contained in the core exception's
     */
    public OAuth2AccessToken login(IProgressMonitor monitor) throws CoreException {
        return login(monitor, 1, 0);
    }

    /**
     * Attempts a log in for the specified amount of attempts, and waits by the
     * specified sleep time between each attempt. If at the end of the attempts,
     * login has failed, Core exception is thrown.
     */
    public OAuth2AccessToken login(IProgressMonitor monitor, int tries, long sleep) throws CoreException {
        return internalLogin(monitor, tries, sleep);
    }

    protected OAuth2AccessToken internalLogin(IProgressMonitor monitor, int tries, long sleep) throws CoreException {
        return new AbstractWaitWithProgressJob<OAuth2AccessToken>(tries, sleep) {

            @Override
            protected OAuth2AccessToken runInWait(IProgressMonitor monitor) throws CoreException {
                // Do not wrap CloudFoundryException or RestClientException in a
                // CoreException.
                // as they are uncaught exceptions and can be inspected directly
                // by the shouldRetryOnError(..) method.
                return operations.login();
            }

            @Override
            protected boolean shouldRetryOnError(Throwable t) {
                return shouldAttemptClientLogin(t);
            }
        }.run(monitor);
    }

    protected SubMonitor getProgressMonitor(IProgressMonitor progressMonitor) {
        return progressMonitor instanceof SubMonitor ? (SubMonitor) progressMonitor : SubMonitor.convert(progressMonitor, DEFAULT_PROGRESS_LABEL, DEFAULT_PROGRESS_TICKS);
    }

    public boolean shouldAttemptClientLogin(Throwable t) {
        return CloudErrorUtil.getInvalidCredentialsError(t) != null;
    }

    /**
     * @return true if there was a proxy update. False any other case.
     * @throws CoreException
     */
    public boolean updateProxyInClient(CloudFoundryOperations client) throws CoreException {
        // if (client != null && cloudURL != null) {
        // try {
        // URL actualUrl = new URL(cloudURL);
        // HttpProxyConfiguration proxyConfiguration =
        // CloudFoundryClientFactory.getProxy(actualUrl);
        // // FIXNS: As of CF Java client-lib version 1.0.2, update proxy
        // // API has been removed. Therefore unless a new client
        // // is created on proxy change, or the client indirectly detects
        // // proxy changes via system properties
        // // Proxy support for CF Eclipse will not work unless a user
        // // reconnects the server instance when the client
        // // is created.
        // client.updateHttpProxyConfiguration(proxyConfiguration);
        // 
        // return true;
        // }
        // catch (MalformedURLException e) {
        // throw
        // CloudErrorUtil.toCoreException("Failed to update proxy settings due to "
        // + e.getMessage(), e);
        // }
        // }
        return false;
    }
}

19 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
protected String getTunnelAuthorisation(CloudFoundryOperations operations) {
    if (operations instanceof CloudFoundryClient) {
        return TunnelHelper.getTunnelAuth((CloudFoundryClient) operations);
    }
    return null;
}

19 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
protected synchronized CloudApplication getCaldecottApp(CloudFoundryOperations client) throws CoreException {
    CloudApplication caldecottApp = null;
    try {
        caldecottApp = client.getApplication(TunnelHelper.getTunnelAppName());
    } catch (Throwable e) {
        throw new CoreException(CloudFoundryPlugin.getErrorStatus(e));
    }
    return caldecottApp;
}

18 View Complete Implementation : BaseClientRequest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/**
 * Perform the actual client operation. The client is guaranteed to be
 * non-null at this stage.
 * @param client non-null client
 * @param progress
 * @return result of operation.
 * @throws CoreException
 */
protected abstract T doRun(CloudFoundryOperations client, SubMonitor progress) throws CoreException;

18 View Complete Implementation : BaseClientRequest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/**
 * Performs a client operation, and if necessary, re-attempts the operation
 * after a certain interval IFF an error occurs based on
 * {@link #getTotalTimeWait()} and
 * {@link #getWaitInterval(Throwable, SubMonitor)}.
 * <p/>
 * The default behaviour is to only attempt a client operation once and quit
 * after an error is encountered. Subclreplacedes may modify this behaviour by
 * overriding {@link #getTotalTimeWait()} and
 * {@link #getWaitInterval(Throwable, SubMonitor)}
 * <p/>
 * Note that reattempts are only decided based on errors thrown by the
 * client invocation, not by results generated by the client invocation.
 * @param client client whose operations are invoked. Never null.
 * @param subProgress
 * @return result of operation. Can be null.
 * @throws CoreException if fatal error occurred while performing the
 * operation (i.e. error that causes the operation to no longer be
 * reattempted)
 * @throws OperationCanceledException if further attempts are cancelled even
 * if time still remains for additional attempts.
 */
protected T runAndWait(CloudFoundryOperations client, SubMonitor subProgress) throws CoreException, OperationCanceledException {
    Throwable error = null;
    boolean reattempt = true;
    long timeLeft = getTotalTimeWait();
    // Either this operation returns a result during the waiting period or
    // an error occurred, and error
    // gets thrown
    while (reattempt) {
        long interval = -1;
        try {
            return doRun(client, subProgress);
        } catch (Throwable e) {
            error = e;
        }
        interval = getWaitInterval(error, subProgress);
        timeLeft -= interval;
        reattempt = !subProgress.isCanceled() && timeLeft >= 0 && interval > 0;
        if (reattempt) {
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
            // Ignore, continue with the next iteration
            }
        }
    }
    if (subProgress.isCanceled()) {
        // check for cancel here, if specialized requests do not do it
        throw new OperationCanceledException(Messages.bind(Messages.OPERATION_CANCELED, label));
    } else if (error instanceof CoreException) {
        throw (CoreException) error;
    } else {
        throw CloudErrorUtil.toCoreException(error);
    }
}

18 View Complete Implementation : HttpTracer.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/**
 * Trace requests in the given client. Generally, this will either register
 * a trace listener to the client, if tracing is enabled, or unregister a
 * trace listener in the client if tracing is disabled.
 * <p/>
 * The trace operation manages the listeners being added, in particular it
 * prevents many listener instances from being added to the same client,
 * therefore trace can be invoke many times (for example, prior to
 * performing a client call) without having to worry about a new listener
 * being added on every call.
 * @param client whose HTTP requests need to be traced. Must not be null
 */
public synchronized void trace(CloudFoundryOperations client) {
    if (client == null) {
        return;
    }
    // To prevent many listeners from being registered in the same client,
    // always unregister the listener, even when enabling tracing. This is a
    // work-around
    // as the client does not have API to check if a listener is already
    // registered.
    if (activeListener != null) {
        client.unRegisterRestLogListener(activeListener);
    }
    if (isEnabled()) {
        if (activeListener == null) {
            activeListener = new PrintingApplicationLogListener();
        }
        client.registerRestLogListener(activeListener);
    }
}

18 View Complete Implementation : BaseClientRequest.java
Copyright Apache License 2.0
Author : PaaS-TA
/**
 * Performs a client operation, and if necessary, re-attempts the operation
 * after a certain interval IFF an error occurs based on
 * {@link #getTotalTimeWait()} and
 * {@link #getWaitInterval(Throwable, SubMonitor)}.
 * <p/>
 * The default behaviour is to only attempt a client operation once and quit
 * after an error is encountered. Subclreplacedes may modify this behaviour by
 * overriding {@link #getTotalTimeWait()} and
 * {@link #getWaitInterval(Throwable, SubMonitor)}
 * <p/>
 * Note that reattempts are only decided based on errors thrown by the
 * client invocation, not by results generated by the client invocation.
 * @param client client whose operations are invoked. Never null.
 * @param subProgress
 * @return result of operation. Can be null.
 * @throws CoreException if fatal error occurred while performing the
 * operation (i.e. error that causes the operation to no longer be
 * reattempted)
 * @throws OperationCanceledException if further attempts are cancelled even
 * if time still remains for additional attempts.
 */
protected T runAndWait(CloudFoundryOperations client, SubMonitor subProgress) throws CoreException, OperationCanceledException {
    Throwable error = null;
    boolean reattempt = true;
    long timeLeft = getTotalTimeWait();
    // Either this operation returns a result during the waiting period or
    // an error occurred, and error
    // gets thrown
    while (reattempt) {
        long interval = -1;
        try {
            return doRun(client, subProgress);
        } catch (Throwable e) {
            error = e;
        }
        interval = getWaitInterval(error, subProgress);
        timeLeft -= interval;
        reattempt = !subProgress.isCanceled() && timeLeft >= 0 && interval > 0;
        if (reattempt) {
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
            // Ignore, continue with the next iteration
            }
        }
    }
    if (subProgress.isCanceled()) {
        throw new OperationCanceledException();
    } else if (error instanceof CoreException) {
        throw (CoreException) error;
    } else {
        throw CloudErrorUtil.toCoreException(error);
    }
}

18 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
protected String getTunnelUri(final CloudFoundryOperations client, IProgressMonitor progress) throws CoreException {
    int attempts = 10;
    long sleep = 3000;
    // $NON-NLS-1$
    progress.setTaskName("Getting tunnel URL");
    String url = new AbstractWaitWithProgressJob<String>(attempts, sleep) {

        @Override
        protected String runInWait(IProgressMonitor monitor) throws CoreException {
            if (client instanceof CloudFoundryClient) {
                return TunnelHelper.getTunnelUri((CloudFoundryClient) client);
            }
            return null;
        }

        protected boolean shouldRetryOnError(Throwable t) {
            // Try several times in case 404 errors are thrown
            return true;
        }
    }.run(progress);
    return url;
}

18 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
/**
 * Retrieves the actual Caldecott Cloud Application from the server. It does
 * not rely on webtools IModule. May be a long running operation and
 * experience network I/O timeouts. SHould only be called when other
 * potential long running operations are performed.
 * @param client
 * @param monitor
 * @return
 */
protected synchronized CloudApplication getOrDeployCaldecottApp(IProgressMonitor monitor, CloudFoundryOperations client) throws CoreException {
    // $NON-NLS-1$
    monitor.setTaskName("Obtaining tunnel application");
    CloudApplication caldecottApp = null;
    try {
        caldecottApp = getCaldecottApp(client);
    } catch (Throwable e) {
    // Ignore all first attempt.
    }
    if (caldecottApp == null) {
        deployCaldecottApp(monitor, client);
    }
    try {
        caldecottApp = client.getApplication(TunnelHelper.getTunnelAppName());
    } catch (Throwable e) {
        throw new CoreException(CloudFoundryPlugin.getErrorStatus(e));
    }
    return caldecottApp;
}

17 View Complete Implementation : CloudAccessTokenTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testFailingRequestAccessTokenErrorClient() throws Exception {
    CloudFoundryOperations client = harness.createExternalClient();
    CloudFoundryLoginHandler handler = new CloudFoundryLoginHandler(client);
    OAuth2AccessToken token = handler.login(new NullProgressMonitor());
    replacedertNotNull(token);
    replacedertFalse(token.isExpired());
    List<CloudApplication> apps = client.getApplications();
    replacedertNotNull(apps);
    longWait();
    Exception error = null;
    try {
        client.getApplications();
    } catch (Exception e) {
        error = e;
    }
    replacedertNotNull("Expected timeout or token access exception from client. Run test again and increase timeout if necessary", error);
    replacedertTrue("Expected access or auth exception from handler", handler.shouldAttemptClientLogin(error));
    OAuth2AccessDeniedException oauthError = error instanceof OAuth2AccessDeniedException ? (OAuth2AccessDeniedException) error : (OAuth2AccessDeniedException) error.getCause();
    replacedertNotNull("Expected OAuth2AccessDeniedException", oauthError);
    token = handler.login(new NullProgressMonitor(), 3, 2000);
    replacedertNotNull(token);
    replacedertFalse(token.isExpired());
    apps = client.getApplications();
    replacedertNotNull(apps);
}

17 View Complete Implementation : CloudFoundryServerBehaviourTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/*
	 * Creates an application through the Cloud Foundry server instance, and
	 * then deletes the application using an external standalone client not
	 * replacedociated with the Cloud Foundry server instance to simulate deleting
	 * the application outside of Eclipse or the runtime workbench.
	 */
public void testDeleteModuleExternally() throws Exception {
    String prefix = "testDeleteModuleExternally";
    String appName = harness.getDefaultWebAppName(prefix);
    createWebApplicationProject();
    deployAndWaitForAppStart(prefix);
    List<CloudApplication> applications = serverBehavior.getApplications(new NullProgressMonitor());
    boolean found = false;
    for (CloudApplication application : applications) {
        if (application.getName().equals(appName)) {
            found = true;
            break;
        }
    }
    replacedertTrue(found);
    // Now create a separate external standalone client (external to the WST
    // CF Server instance) to delete the app
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    client.deleteApplication(appName);
    applications = serverBehavior.getApplications(new NullProgressMonitor());
    found = false;
    for (CloudApplication application : applications) {
        if (application.getName().equals(appName)) {
            found = true;
            break;
        }
    }
    replacedertFalse(found);
}

16 View Complete Implementation : CloudFoundryClientConnectionTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testValidCredentialsLoginHandler() throws Exception {
    CredentialProperties credentials = getTestFixture().getCredentials();
    CloudFoundryOperations client = StsTestUtil.createStandaloneClient(credentials.userEmail, credentials.preplacedword, credentials.organization, credentials.space, getTestFixture().getUrl(), getTestFixture().getSelfSignedCertificate());
    CloudFoundryLoginHandler operationsHandler = new CloudFoundryLoginHandler(client);
    operationsHandler.login(new NullProgressMonitor());
    CloudInfo cloudInfo = client.getCloudInfo();
    replacedert.replacedertNotNull(cloudInfo);
}

16 View Complete Implementation : CloudFoundryClientConnectionTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testValidCredentials() throws Exception {
    CredentialProperties credentials = getTestFixture().getCredentials();
    CloudFoundryOperations client = StsTestUtil.createStandaloneClient(credentials.userEmail, credentials.preplacedword, credentials.organization, credentials.space, getTestFixture().getUrl(), getTestFixture().getSelfSignedCertificate());
    CloudInfo cloudInfo = client.getCloudInfo();
    replacedert.replacedertNotNull(cloudInfo);
}

16 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testUpdateModulesServerBehaviourWrongCloudApp() throws Exception {
    // Update modules API in behaviour will return a
    // CloudFoundryApplicationModule for an existing Cloud application in
    // the Cloud Space. This replacedociated update modules for the Cloud Foundry
    // Server
    // which the behaviour uses is tested separately in a different test
    // case
    String prefix = "testUpdateModulesServerBehaviourWrongCloudApp";
    String expectedAppName = harness.getDefaultWebAppName(prefix);
    // Create the app externally AFTER the server connects in the setup to
    // ensure the tools did not pick up the Cloud application during refresh
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    List<String> urls = new ArrayList<String>();
    urls.add(harness.getExpectedDefaultURL(prefix));
    client.createApplication(expectedAppName, new Staging(), CloudUtil.DEFAULT_MEMORY, urls, new ArrayList<String>());
    // The tool has not refreshed after the app was created with an external
    // client, so there should be no module
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(expectedAppName);
    replacedertNull(appModule);
    CloudFoundryApplicationModule wrongModule = serverBehavior.updateCloudModule("wrongApp", new NullProgressMonitor());
    replacedertNull(wrongModule);
    wrongModule = serverBehavior.updateCloudModuleWithInstances("wrongApp", new NullProgressMonitor());
    replacedertNull(wrongModule);
}

16 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
protected Map<String, String> getTunnelInfo(final CloudFoundryOperations client, final String serviceName, IProgressMonitor monitor) throws CoreException {
    // $NON-NLS-1$
    monitor.setTaskName("Getting tunnel information");
    int attempts = 10;
    long sleepTime = 2000;
    Map<String, String> info = new AbstractWaitWithProgressJob<Map<String, String>>(attempts, sleepTime) {

        @Override
        protected Map<String, String> runInWait(IProgressMonitor monitor) {
            if (client instanceof CloudFoundryClient) {
                return TunnelHelper.getTunnelServiceInfo((CloudFoundryClient) client, serviceName);
            }
            return null;
        }

        @Override
        protected boolean shouldRetryOnError(Throwable t) {
            // Try several times in case 404 errors are thrown
            return true;
        }
    }.run(monitor);
    if (info == null) {
        CloudFoundryPlugin.logError(// $NON-NLS-1$
        "Timeout trying to obtain tunnel information for: " + serviceName + // $NON-NLS-1$
        ". Please wait a few seconds before trying again.");
    }
    return info;
}

16 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
protected void deployCaldecottApp(IProgressMonitor monitor, CloudFoundryOperations client) throws CoreException {
    // $NON-NLS-1$
    monitor.setTaskName("Publishing tunnel application");
    Thread t = Thread.currentThread();
    ClreplacedLoader oldLoader = t.getContextClreplacedLoader();
    boolean deployed = false;
    try {
        t.setContextClreplacedLoader(CloudFoundryServerBehaviour.clreplaced.getClreplacedLoader());
        if (client instanceof CloudFoundryClient) {
            TunnelHelper.deployTunnelApp((CloudFoundryClient) client);
            deployed = true;
        }
    } catch (TunnelException te) {
        CloudFoundryPlugin.logError(te);
    } finally {
        t.setContextClreplacedLoader(oldLoader);
    }
    // refresh the list of modules to create a module for the
    // deployed Caldecott App
    if (deployed) {
        cloudServer.getBehaviour().getRefreshHandler().scheduleRefreshAll();
    }
}

16 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
protected void startCaldecottApp(IProgressMonitor progress, final CloudFoundryOperations client) throws CoreException {
    // $NON-NLS-1$
    progress.setTaskName("Starting tunnel application");
    CloudApplication caldecottApp = getCaldecottApp(client);
    if (caldecottApp == null) {
        // $NON-NLS-1$
        throw CloudErrorUtil.toCoreException("No Caldecott application found. Unable to create tunnel.");
    }
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(caldecottApp.getName());
    if (appModule == null) {
        throw CloudErrorUtil.toCoreException(// $NON-NLS-1$
        "No local Caldecott application module found. Application may not have finished deploying. Unable to create tunnel.");
    }
    cloudServer.getBehaviour().startModule(new IModule[] { appModule.getLocalModule() }, progress);
}

15 View Complete Implementation : BaseClientRequest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/**
 * @return result of client operation
 * @throws CoreException if failure occurred while attempting to execute the
 * client operation.
 */
public T run(IProgressMonitor monitor) throws CoreException {
    SubMonitor subProgress = SubMonitor.convert(monitor);
    subProgress.subTask(getRequestLabel());
    CloudFoundryOperations client = getClient(subProgress);
    if (client == null) {
        throw CloudErrorUtil.toCoreException(NLS.bind(Messages.ERROR_NO_CLIENT, getRequestLabel()));
    }
    HttpTracer.getCurrent().trace(client);
    try {
        return runAndWait(client, subProgress);
    } catch (CoreException ce) {
        // See if it is a connection error. If so, parse it into readable
        // form.
        String connectionError = CloudErrorUtil.getConnectionError(ce);
        if (connectionError != null) {
            throw CloudErrorUtil.asCoreException(connectionError, ce, true);
        } else {
            throw ce;
        }
    } finally {
        subProgress.done();
    }
}

15 View Complete Implementation : CloudFoundryServicesTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testExternalCreatedServiceBehaviour() throws Exception {
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    CloudService service = getCloudServiceToCreate("testExternalCreatedServiceBehaviour", "elephantsql", "turtle");
    client.createService(service);
    List<CloudService> existingServices = serverBehavior.getServices(new NullProgressMonitor());
    replacedertTrue("Expected 1 service", existingServices.size() == 1);
    replacedertEquals("testExternalCreatedServiceBehaviour", existingServices.get(0).getName());
    replacedertEquals("elephantsql", existingServices.get(0).getLabel());
    replacedertEquals("turtle", existingServices.get(0).getPlan());
}

14 View Complete Implementation : CloudFoundryClientConnectionTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testConnectToNonSecureUrl() throws Exception {
    String url = getTestFixture().getUrl();
    URL ur = new URL(url);
    String host = ur.getHost();
    String httpUrl = "http://" + host;
    CredentialProperties credentials = getTestFixture().getCredentials();
    CloudFoundryOperations client = StsTestUtil.createStandaloneClient(credentials.userEmail, credentials.preplacedword, credentials.organization, credentials.space, httpUrl, getTestFixture().getSelfSignedCertificate());
    new CloudFoundryLoginHandler(client).login(new NullProgressMonitor());
    CloudInfo cloudInfo = client.getCloudInfo();
    replacedert.replacedertNotNull(cloudInfo);
}

14 View Complete Implementation : CloudFoundryClientConnectionTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testConnectToSecureUrl() throws Exception {
    String url = getTestFixture().getUrl();
    URL ur = new URL(url);
    String host = ur.getHost();
    String httpUrl = "https://" + host;
    CredentialProperties credentials = getTestFixture().getCredentials();
    CloudFoundryOperations client = StsTestUtil.createStandaloneClient(credentials.userEmail, credentials.preplacedword, credentials.organization, credentials.space, httpUrl, getTestFixture().getSelfSignedCertificate());
    new CloudFoundryLoginHandler(client).login(new NullProgressMonitor());
    CloudInfo cloudInfo = client.getCloudInfo();
    replacedert.replacedertNotNull(cloudInfo);
}

14 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testSingleModuleUpdateExternalCreation() throws Exception {
    String prefix = "testSingleModuleUpdateExternalCreation";
    String appName = harness.getDefaultWebAppName(prefix);
    // After deployment the module must exist and be mapped to an existing
    // CloudApplication
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(appName);
    replacedertNull(appModule);
    appModule = serverBehavior.updateCloudModule(appName, new NullProgressMonitor());
    replacedertNull(appModule);
    // Create separate external client
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    List<String> urls = new ArrayList<String>();
    urls.add(harness.getExpectedDefaultURL(prefix));
    client.createApplication(appName, new Staging(), CloudUtil.DEFAULT_MEMORY, urls, new ArrayList<String>());
    appModule = serverBehavior.updateCloudModule(appName, new NullProgressMonitor());
    replacedertEquals(appName, appModule.getDeployedApplicationName());
    replacedertEquals(appModule.getDeployedApplicationName(), appModule.getApplication().getName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, appModule.getApplication().getMemory());
    replacedertEquals(appModule.getDeploymentInfo().getMemory(), appModule.getApplication().getMemory());
}

14 View Complete Implementation : StartOperation.java
Copyright Apache License 2.0
Author : PaaS-TA
/**
 * This performs the primary operation of creating an application and then
 * pushing the application contents to the server. These are performed in
 * separate requests via the CF client. If the application does not exist,
 * it is first created through an initial request. Once the application is
 * created, or if it already exists, the next step is to upload (push) the
 * application archive containing the application's resources. This is
 * performed in a second separate request.
 * <p/>
 * To avoid replacing the deployment info in the app module, the mapping to
 * the most recent {@link CloudApplication} in the app module is NOT updated
 * with newly created application. It is up to the caller to set the mapping
 * in {@link CloudFoundryApplicationModule}
 * @param client
 * @param appModule valid Cloud module with valid deployment info.
 * @param monitor
 * @throws CoreException if error creating the application
 */
protected void pushApplication(CloudFoundryOperations client, final CloudFoundryApplicationModule appModule, File warFile, ApplicationArchive applicationArchive, final IProgressMonitor monitor) throws CoreException {
    String appName = appModule.getDeploymentInfo().getDeploymentName();
    try {
        // Now push the application content.
        if (warFile != null) {
            client.uploadApplication(appName, warFile);
        } else if (applicationArchive != null) {
            // Handle the incremental publish case separately as it
            // requires
            // a partial war file generation of only the changed
            // resources
            // AFTER
            // the server determines the list of missing file names.
            if (applicationArchive instanceof CachingApplicationArchive) {
                final CachingApplicationArchive cachingArchive = (CachingApplicationArchive) applicationArchive;
                client.uploadApplication(appName, cachingArchive, new UploadStatusCallback() {

                    public void onProcessMatchedResources(int length) {
                    }

                    public void onMatchedFileNames(Set<String> matchedFileNames) {
                        cachingArchive.generatePartialWarFile(matchedFileNames);
                    }

                    public void onCheckResources() {
                    }

                    public boolean onProgress(String status) {
                        return false;
                    }
                });
            // Once the application has run, do a clean up of the
            // sha1
            // cache for deleted resources
            } else {
                client.uploadApplication(appName, applicationArchive, new UploadStatusCallback() {

                    public void onProcessMatchedResources(int length) {
                    }

                    public void onMatchedFileNames(Set<String> matchedFileNames) {
                    // try {
                    // printlnToConsole(appModule, ".", false,
                    // false, monitor);
                    // }
                    // catch (CoreException e) {
                    // CloudFoundryPlugin.logError(e);
                    // }
                    }

                    public void onCheckResources() {
                    }

                    public boolean onProgress(String status) {
                        return false;
                    }
                });
            }
        } else {
            throw CloudErrorUtil.toCoreException(// $NON-NLS-1$
            "Failed to deploy application " + appModule.getDeploymentInfo().getDeploymentName() + // $NON-NLS-1$
            " since no deployable war or application archive file was generated.");
        }
    } catch (IOException e) {
        throw new CoreException(CloudFoundryPlugin.getErrorStatus(// $NON-NLS-1$
        "Failed to deploy application " + appModule.getDeploymentInfo().getDeploymentName() + " due to " + e.getMessage(), // $NON-NLS-1$
        e));
    }
}

13 View Complete Implementation : ClientRequest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/**
 * Attempts to execute the client request by first checking proxy settings,
 * and if unauthorised/forbidden exceptions thrown the first time, will
 * attempt to log in. If that succeeds, it will attempt one more time.
 * Otherwise it will fail and not attempt the request any further.
 * @param client
 * @param cloudServer
 * @param subProgress
 * @return
 * @throws CoreException if attempt to execute failed, even after a second
 * attempt after a client login.
 */
@Override
protected T runAndWait(CloudFoundryOperations client, SubMonitor subProgress) throws CoreException {
    try {
        return super.runAndWait(client, subProgress);
    } catch (CoreException ce) {
        CloudFoundryLoginHandler handler = new CloudFoundryLoginHandler(client);
        CoreException accessError = null;
        String accessErrorMessage = null;
        if (handler.shouldAttemptClientLogin(ce)) {
            CloudFoundryPlugin.logWarning(NLS.bind(Messages.ClientRequest_RETRY_REQUEST, getTokenAccessErrorLabel()));
            accessError = ce;
            int attempts = 3;
            OAuth2AccessToken token = handler.login(subProgress, attempts, CloudOperationsConstants.LOGIN_INTERVAL);
            if (token == null) {
                accessErrorMessage = Messages.ClientRequest_NO_TOKEN;
            } else if (token.isExpired()) {
                accessErrorMessage = Messages.ClientRequest_TOKEN_EXPIRED;
            } else {
                try {
                    return super.runAndWait(client, subProgress);
                } catch (CoreException e) {
                    accessError = e;
                }
            }
        }
        if (accessError != null) {
            Throwable cause = accessError.getCause() != null ? accessError.getCause() : accessError;
            if (accessErrorMessage == null) {
                accessErrorMessage = accessError.getMessage();
            }
            accessErrorMessage = NLS.bind(Messages.ClientRequest_SECOND_ATTEMPT_FAILED, getTokenAccessErrorLabel(), accessErrorMessage);
            throw CloudErrorUtil.toCoreException(accessErrorMessage, cause);
        }
        throw ce;
    }
}

13 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testUpdateModulesCloudServer() throws Exception {
    // Tests the Update modules API in the server that will CREATE or return
    // an existing
    // CloudFoundryApplicationModule ONLY if it is given a CloudApplication.
    String prefix = "testUpdateModulesCloudServer";
    String expectedAppName = harness.getDefaultWebAppName(prefix);
    // Create the app externally AFTER the server connects in the setup to
    // ensure the tools did not pick up the Cloud application during refresh
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    List<String> urls = new ArrayList<String>();
    urls.add(harness.getExpectedDefaultURL(prefix));
    client.createApplication(expectedAppName, new Staging(), CloudUtil.DEFAULT_MEMORY, urls, new ArrayList<String>());
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(expectedAppName);
    // Tooling has not yet been updated so there is no corresponding
    // appModule even though the app exists in the Cloud space
    replacedertNull(appModule);
    // No actual cloud application preplaceded to update therefore no replacedociated
    // CloudFoundryApplicationModule should be found
    appModule = cloudServer.updateModule(null, expectedAppName, new NullProgressMonitor());
    replacedertNull(appModule);
    appModule = cloudServer.updateModule(null, null, new NullProgressMonitor());
    replacedertNull(appModule);
    replacedertTrue(cloudServer.getExistingCloudModules().isEmpty());
    // Get the actual cloud app directly from the Cloud space
    CloudApplication actualApp = client.getApplications().get(0);
    // Now create the CloudFoundryApplicationModule
    appModule = cloudServer.updateModule(actualApp, expectedAppName, new NullProgressMonitor());
    replacedertEquals(expectedAppName, appModule.getDeployedApplicationName());
    replacedertEquals(appModule.getDeployedApplicationName(), appModule.getApplication().getName());
    // Check the mapping is correct
    replacedertEquals(actualApp.getName(), appModule.getApplication().getName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, appModule.getApplication().getMemory());
    replacedertEquals(appModule.getDeploymentInfo().getMemory(), appModule.getApplication().getMemory());
    // It should match what is obtained through getExisting API
    CloudFoundryApplicationModule existingCloudMod = cloudServer.getExistingCloudModule(expectedAppName);
    replacedertEquals(expectedAppName, existingCloudMod.getDeployedApplicationName());
    replacedertEquals(existingCloudMod.getDeployedApplicationName(), existingCloudMod.getApplication().getName());
    // Check the mapping is correct
    replacedertEquals(actualApp.getName(), existingCloudMod.getApplication().getName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, existingCloudMod.getApplication().getMemory());
    replacedertEquals(existingCloudMod.getDeploymentInfo().getMemory(), existingCloudMod.getApplication().getMemory());
    // Check the other existing Modules API
    CloudFoundryApplicationModule sameExistingApp = cloudServer.getExistingCloudModules().iterator().next();
    replacedertEquals(expectedAppName, sameExistingApp.getDeployedApplicationName());
    replacedertEquals(sameExistingApp.getDeployedApplicationName(), sameExistingApp.getApplication().getName());
    // Check the mapping is correct
    replacedertEquals(actualApp.getName(), sameExistingApp.getApplication().getName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, sameExistingApp.getApplication().getMemory());
    replacedertEquals(sameExistingApp.getDeploymentInfo().getMemory(), sameExistingApp.getApplication().getMemory());
}

13 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testUpdateModulesServerBehaviourExistingCloudApp() throws Exception {
    // Update modules API in behaviour will return a
    // CloudFoundryApplicationModule for an existing Cloud application in
    // the Cloud Space. This replacedociated update modules for the Cloud Foundry
    // Server
    // which the behaviour uses is tested separately in a different test
    // case
    String prefix = "testUpdateModulesServerBehaviourExistingCloudApp";
    String expectedAppName = harness.getDefaultWebAppName(prefix);
    // Create the app externally AFTER the server connects in the setup to
    // ensure the tools did not pick up the Cloud application during refresh
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    List<String> urls = new ArrayList<String>();
    urls.add(harness.getExpectedDefaultURL(prefix));
    client.createApplication(expectedAppName, new Staging(), CloudUtil.DEFAULT_MEMORY, urls, new ArrayList<String>());
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(expectedAppName);
    // Tooling has not yet been updated so there is no corresponding
    // appModule even though the app exists in the Cloud space
    replacedertNull(appModule);
    // This will tell the behaviour to fetch the Cloud application from the
    // Cloud space and generate a module
    CloudFoundryApplicationModule updateModule = serverBehavior.updateCloudModule(expectedAppName, new NullProgressMonitor());
    replacedertEquals(expectedAppName, updateModule.getDeployedApplicationName());
    replacedertEquals(updateModule.getDeployedApplicationName(), updateModule.getApplication().getName());
    // Check the mapping is correct
    replacedertEquals(updateModule.getName(), updateModule.getApplication().getName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, updateModule.getApplication().getMemory());
    replacedertEquals(updateModule.getDeploymentInfo().getMemory(), updateModule.getApplication().getMemory());
}

12 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testSingleModuleUpdateExternalAppDeletion() throws Exception {
    String prefix = "testSingleModuleUpdateExternalAppDeletion";
    String appName = harness.getDefaultWebAppName(prefix);
    IProject project = createWebApplicationProject();
    boolean stopMode = false;
    // Configure the test fixture for deployment.
    // This step is a subsreplacedute for the Application deployment wizard
    getTestFixture().configureForApplicationDeployment(appName, CloudUtil.DEFAULT_MEMORY, stopMode);
    IModule module = getModule(project.getName());
    // Push the application.
    cloudServer.getBehaviour().operations().applicationDeployment(new IModule[] { module }, ApplicationAction.PUSH).run(new NullProgressMonitor());
    // After deployment the module must exist and be mapped to an existing
    // CloudApplication
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(appName);
    replacedertEquals(appModule.getDeployedApplicationName(), appModule.getApplication().getName());
    // Delete module externally and verify that module refresh picks up the
    // change
    // Create separate external client
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    client.deleteApplication(appName);
    appModule = serverBehavior.updateCloudModule(appName, new NullProgressMonitor());
    replacedertNull(appModule);
    appModule = cloudServer.getExistingCloudModule(appName);
    replacedertNull(appModule);
    CloudApplication nonexistantApp = null;
    appModule = cloudServer.updateModule(nonexistantApp, appName, new NullProgressMonitor());
    replacedertNull(appModule);
}

12 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testAllModuleUpdateExternalCreation() throws Exception {
    String prefix = "testAllModuleUpdateExternalCreation";
    String appName = harness.getDefaultWebAppName(prefix);
    // After deployment the module must exist and be mapped to an existing
    // CloudApplication
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(appName);
    replacedertNull(appModule);
    appModule = serverBehavior.updateCloudModule(appName, new NullProgressMonitor());
    replacedertNull(appModule);
    // Create separate external client
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    List<String> urls = new ArrayList<String>();
    urls.add(harness.getExpectedDefaultURL(prefix));
    client.createApplication(appName, new Staging(), CloudUtil.DEFAULT_MEMORY, urls, new ArrayList<String>());
    CloudApplication application = client.getApplication(appName);
    Map<String, CloudApplication> allApps = new HashMap<String, CloudApplication>();
    allApps.put(application.getName(), application);
    cloudServer.updateModules(allApps);
    appModule = cloudServer.getExistingCloudModule(appName);
    replacedertEquals(appModule.getDeployedApplicationName(), appModule.getApplication().getName());
    replacedertEquals(appName, appModule.getDeployedApplicationName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, appModule.getApplication().getMemory());
    replacedertEquals(appModule.getDeploymentInfo().getMemory(), appModule.getApplication().getMemory());
    // It should match what is obtained through update cloud module
    appModule = serverBehavior.updateCloudModule(appName, new NullProgressMonitor());
    replacedertNotNull(appModule);
    replacedertNotNull(appModule.getApplication());
    replacedertEquals(appName, appModule.getDeployedApplicationName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, appModule.getApplication().getMemory());
    replacedertEquals(appModule.getDeploymentInfo().getMemory(), appModule.getApplication().getMemory());
}

12 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testModuleRefreshDuringServerConnect2() throws Exception {
    // Deploy and start an application.
    // Disconnect through the server behaviour. Verify through an external
    // client that the app
    // remains deployed and in started mode.
    // Reconnect, and verify that the application is still running (i.e.
    // disconnecting
    // the server should not stop the application).
    String appPrefix = "testModuleRefreshDuringServerConnect2";
    String expectedAppName = harness.getDefaultWebAppName(appPrefix);
    createWebApplicationProject();
    // Note that deploying application fires off an app change event AFTER
    // the deployment is
    // successful. To make sure that the second event listener further down
    // does not accidentally receive the app
    // change event,
    // wait for the app change event from the deploy first, and then
    // schedule the second listener to
    // listen to the expected refresh event
    deployAndWaitForDeploymentEvent(appPrefix);
    // Cloud module should have been created.
    Collection<CloudFoundryApplicationModule> appModules = cloudServer.getExistingCloudModules();
    replacedertEquals(harness.getDefaultWebAppName(appPrefix), appModules.iterator().next().getDeployedApplicationName());
    // Disconnect and verify that there are no cloud foundry application
    // modules
    serverBehavior.disconnect(new NullProgressMonitor());
    appModules = cloudServer.getExistingCloudModules();
    replacedertTrue("Expected empty list of cloud application modules after server disconnect", appModules.isEmpty());
    // Now create an external client to independently check that the
    // application remains deployed and in started mode
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    List<CloudApplication> deployedApplications = client.getApplications();
    replacedertEquals("Expected 1 Cloud application in Cloud space after server disconnect", 1, deployedApplications.size());
    replacedertEquals(expectedAppName, deployedApplications.get(0).getName());
    replacedertTrue(deployedApplications.get(0).getState() == AppState.STARTED);
    // Register a module refresh listener before connecting again to be
    // notified when
    // modules are refreshed
    ModulesRefreshListener listener = getModulesRefreshListener(null, cloudServer, CloudServerEvent.EVENT_SERVER_REFRESHED);
    serverBehavior.connect(new NullProgressMonitor());
    replacedertModuleRefreshedAndDispose(listener, CloudServerEvent.EVENT_SERVER_REFRESHED);
    appModules = cloudServer.getExistingCloudModules();
    CloudFoundryApplicationModule appModule = appModules.iterator().next();
    replacedertEquals(expectedAppName, appModule.getDeployedApplicationName());
    replacedertApplicationIsRunning(appModule);
}

12 View Complete Implementation : TunnelBehaviour.java
Copyright Apache License 2.0
Author : PaaS-TA
protected boolean bindServiceToCaldecottApp(String serviceName, CloudFoundryOperations client, SubMonitor monitor) throws CoreException {
    CloudApplication caldecottApp = getCaldecottApp(client);
    List<String> updateCaldecottServices = new ArrayList<String>();
    List<String> existingServices = caldecottApp.getServices();
    if (existingServices != null) {
        // Must iterate to filter out possible null service names
        for (String existing : existingServices) {
            if (existing != null) {
                updateCaldecottServices.add(existing);
            }
        }
    }
    IModule caldecottModule = getCaldecottModule(monitor.newChild(1));
    if (!updateCaldecottServices.contains(serviceName)) {
        // $NON-NLS-1$ //$NON-NLS-2$
        monitor.setTaskName("Binding service " + serviceName + " to tunnel application");
        updateCaldecottServices.add(serviceName);
        CloudFoundryServerBehaviour behaviour = cloudServer.getBehaviour();
        behaviour.stopModule(new IModule[] { caldecottModule }, monitor.newChild(1));
        setDeploymentServices(serviceName, monitor.newChild(1));
        return caldecottApp.getServices().contains(serviceName);
    } else {
        return true;
    }
}

11 View Complete Implementation : LocalServerRequest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
@Override
public T runAndWait(CloudFoundryOperations client, SubMonitor monitor) throws CoreException {
    CloudFoundryServer cloudServer = getCloudServer();
    if (cloudServer.getUsername() == null || cloudServer.getUsername().length() == 0 || cloudServer.getPreplacedword() == null || cloudServer.getPreplacedword().length() == 0) {
        CloudFoundryPlugin.getCallback().getCredentials(cloudServer);
    }
    Server server = (Server) cloudServer.getServer();
    // Any Server request will require the server to be connected, so update
    // the server state
    if (server.getServerState() == IServer.STATE_STOPPED || server.getServerState() == IServer.STATE_STOPPING) {
        server.setServerState(IServer.STATE_STARTING);
    }
    try {
        T result = super.runAndWait(client, monitor);
        // No errors at this stage, therefore replacedume operation was completed
        // successfully, and update
        // server state accordingly
        if (server.getServerState() != IServer.STATE_STARTED) {
            server.setServerState(IServer.STATE_STARTED);
        }
        return result;
    } catch (CoreException ce) {
        // If the server state was starting and the error is related when
        // the operation was
        // attempted, but the operation failed
        // set the server state back to stopped.
        if (CloudErrorUtil.isConnectionError(ce) && server.getServerState() == IServer.STATE_STARTING) {
            server.setServerState(IServer.STATE_STOPPED);
        }
        // server.setServerPublishState(IServer.PUBLISH_STATE_NONE);
        throw ce;
    }
}

11 View Complete Implementation : CloudFoundryServicesTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testExternalCreatedServiceRefresh() throws Exception {
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    CloudService service = getCloudServiceToCreate("testExternalCreatedServiceRefresh", "elephantsql", "turtle");
    client.createService(service);
    ModulesRefreshListener refreshListener = new ModulesRefreshListener(cloudServer, CloudServerEvent.EVENT_SERVER_REFRESHED);
    serverBehavior.getRefreshHandler().scheduleRefreshAll();
    replacedertTrue(refreshListener.modulesRefreshed(new NullProgressMonitor()));
    replacedertEquals(CloudServerEvent.EVENT_SERVER_REFRESHED, refreshListener.getMatchedEvent().getType());
    replacedertTrue("Expected " + CloudRefreshEvent.clreplaced, refreshListener.getMatchedEvent() instanceof CloudRefreshEvent);
    CloudRefreshEvent cloudEvent = (CloudRefreshEvent) refreshListener.getMatchedEvent();
    List<CloudService> eventServices = cloudEvent.getServices();
    replacedertTrue("Expected 1 service in cloud refresh event", eventServices.size() == 1);
    replacedertEquals("testExternalCreatedServiceRefresh", eventServices.get(0).getName());
    replacedertEquals("elephantsql", eventServices.get(0).getLabel());
    replacedertEquals("turtle", eventServices.get(0).getPlan());
}

11 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testAllModuleUpdateExternalAppDeletion() throws Exception {
    String prefix = "testAllModuleUpdateExternalAppDeletion";
    String appName = harness.getDefaultWebAppName(prefix);
    IProject project = createWebApplicationProject();
    boolean stopMode = false;
    // Configure the test fixture for deployment.
    // This step is a subsreplacedute for the Application deployment wizard
    getTestFixture().configureForApplicationDeployment(appName, CloudUtil.DEFAULT_MEMORY, stopMode);
    IModule module = getModule(project.getName());
    // Push the application.
    cloudServer.getBehaviour().operations().applicationDeployment(new IModule[] { module }, ApplicationAction.PUSH).run(new NullProgressMonitor());
    // After deployment the module must exist and be mapped to an existing
    // CloudApplication
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(appName);
    // Verify the module exists
    replacedertEquals(appModule.getDeployedApplicationName(), appModule.getApplication().getName());
    // Delete module externally and verify that module refresh picks up the
    // change
    // Create separate external client
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    client.deleteApplication(appName);
    // Update through all-modules update, and also verify existing modules
    // matches results
    Map<String, CloudApplication> allApps = new HashMap<String, CloudApplication>();
    cloudServer.updateModules(allApps);
    appModule = cloudServer.getExistingCloudModule(appName);
    replacedertNull(appModule);
    // Update through single-module update, and also verify that existing
    // modules matches the results
    appModule = serverBehavior.updateCloudModule(appName, new NullProgressMonitor());
    replacedertNull(appModule);
    appModule = cloudServer.getExistingCloudModule(appName);
    replacedertNull(appModule);
}

11 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testUpdateModuleInstances() throws Exception {
    // Update modules API in behaviour will return a
    // CloudFoundryApplicationModule for an existing Cloud application in
    // the Cloud Space. This replacedociated update modules for the Cloud Foundry
    // Server
    // which the behaviour uses is tested separately in a different test
    // case
    String prefix = "testUpdateModuleInstances";
    String expectedAppName = harness.getDefaultWebAppName(prefix);
    // Create the app externally AFTER the server connects in the setup to
    // ensure the tools did not pick up the Cloud application during refresh
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    List<String> urls = new ArrayList<String>();
    urls.add(harness.getExpectedDefaultURL(prefix));
    client.createApplication(expectedAppName, new Staging(), CloudUtil.DEFAULT_MEMORY, urls, new ArrayList<String>());
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(expectedAppName);
    // Tooling has not yet been updated so there is no corresponding
    // appModule even though the app exists in the Cloud space
    replacedertNull(appModule);
    // This will tell the behaviour to fetch the Cloud application from the
    // Cloud space and generate a module
    CloudFoundryApplicationModule updateModule = serverBehavior.updateCloudModuleWithInstances(expectedAppName, new NullProgressMonitor());
    replacedertEquals(expectedAppName, updateModule.getDeployedApplicationName());
    replacedertEquals(updateModule.getDeployedApplicationName(), updateModule.getApplication().getName());
    // Check the mapping is correct
    replacedertEquals(updateModule.getName(), updateModule.getApplication().getName());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, updateModule.getApplication().getMemory());
    replacedertEquals(updateModule.getDeploymentInfo().getMemory(), updateModule.getApplication().getMemory());
    replacedertEquals(1, updateModule.getInstanceCount());
    // There is one instance, but since the app was created EXTERNALLY and
    // not started, there should
    // be no instance info
    replacedertEquals(0, updateModule.getApplicationStats().getRecords().size());
    replacedertNull(updateModule.getInstancesInfo());
    updateModule = serverBehavior.updateCloudModuleWithInstances((String) null, new NullProgressMonitor());
    replacedertNull(updateModule);
    updateModule = serverBehavior.updateCloudModuleWithInstances("wrongName", new NullProgressMonitor());
    replacedertNull(updateModule);
    updateModule = serverBehavior.updateCloudModuleWithInstances((IModule) null, new NullProgressMonitor());
    replacedertNull(updateModule);
}

10 View Complete Implementation : StartOperation.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
/**
 * This performs the primary operation of creating an application and then
 * pushing the application contents to the server. These are performed in
 * separate requests via the CF client. If the application does not exist,
 * it is first created through an initial request. Once the application is
 * created, or if it already exists, the next step is to upload (push) the
 * application archive containing the application's resources. This is
 * performed in a second separate request.
 * <p/>
 * To avoid replacing the deployment info in the app module, the mapping to
 * the most recent {@link CloudApplication} in the app module is NOT updated
 * with newly created application. It is up to the caller to set the mapping
 * in {@link CloudFoundryApplicationModule}
 * @param client
 * @param appModule valid Cloud module with valid deployment info.
 * @param monitor
 * @throws CoreException if error creating the application
 */
protected void pushApplication(CloudFoundryOperations client, final CloudFoundryApplicationModule appModule, ApplicationArchive applicationArchive, final IProgressMonitor monitor) throws CoreException {
    String appName = appModule.getDeploymentInfo().getDeploymentName();
    // [95636410] - verify that the application actually exists.
    // Otherwise a cryptic error may be thrown and the user may not
    // know that the upload failed because the application no longer exists
    try {
        getBehaviour().getCloudApplication(appName, monitor);
    } catch (CoreException e) {
        if (CloudErrorUtil.isNotFoundException(e)) {
            throw CloudErrorUtil.toCoreException(NLS.bind(Messages.ERROR_FAILED_TO_PUSH_APP_DOES_NOT_EXIST, appName), e);
        } else {
            throw e;
        }
    }
    try {
        // Now push the application content.
        if (applicationArchive != null) {
            // Handle the incremental publish case separately as it
            // requires
            // a partial war file generation of only the changed
            // resources
            // AFTER
            // the server determines the list of missing file names.
            try {
                if (applicationArchive instanceof CachingApplicationArchive) {
                    final CachingApplicationArchive cachingArchive = (CachingApplicationArchive) applicationArchive;
                    client.uploadApplication(appName, cachingArchive, new UploadStatusCallback() {

                        public void onProcessMatchedResources(int length) {
                        }

                        public void onMatchedFileNames(Set<String> matchedFileNames) {
                            cachingArchive.generatePartialWarFile(matchedFileNames);
                        }

                        public void onCheckResources() {
                        }

                        public boolean onProgress(String status) {
                            return false;
                        }
                    });
                // Once the application has run, do a clean up of the
                // sha1
                // cache for deleted resources
                } else {
                    client.uploadApplication(appName, applicationArchive, new UploadStatusCallback() {

                        public void onProcessMatchedResources(int length) {
                        }

                        public void onMatchedFileNames(Set<String> matchedFileNames) {
                        // try {
                        // printlnToConsole(appModule, ".", false,
                        // false, monitor);
                        // }
                        // catch (CoreException e) {
                        // CloudFoundryPlugin.logError(e);
                        // }
                        }

                        public void onCheckResources() {
                        }

                        public boolean onProgress(String status) {
                            return false;
                        }
                    });
                }
                // Check for cancel
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException(Messages.bind(Messages.OPERATION_CANCELED, getOperationName()));
                }
            } finally {
                if (applicationArchive instanceof CloudApplicationArchive) {
                    try {
                        ((CloudApplicationArchive) applicationArchive).close();
                    } catch (CoreException e) {
                        // Don't let errors in closing the archive stop the
                        // publish operation
                        CloudFoundryPlugin.logError(e);
                    }
                }
            }
        } else {
            throw CloudErrorUtil.toCoreException(// $NON-NLS-1$
            "Failed to deploy application " + appModule.getDeploymentInfo().getDeploymentName() + // $NON-NLS-1$
            " since no deployable war or application archive file was generated.");
        }
    } catch (IOException e) {
        throw new CoreException(CloudFoundryPlugin.getErrorStatus(// $NON-NLS-1$
        "Failed to deploy application " + appModule.getDeploymentInfo().getDeploymentName() + " due to " + e.getMessage(), // $NON-NLS-1$
        e));
    }
}

10 View Complete Implementation : ModuleRefreshTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testModuleUpdatesExternalChanges() throws Exception {
    // Tests various module update scenarios due to external changes.
    // This is performed in one test to avoid multiple application creations
    // and deployments during junit setups which are slow
    // Tests the following cases:
    // 1. Push application for the first time - Module should be created and
    // mapped to a CloudApplication
    // 2. Update the application externally and update through behaviour API
    // - Module and mapping to CloudApplication should be updated
    // 3. Update the application externally and refresh all Modules - Module
    // and mapping to CloudApplication should be updated.
    String prefix = "testModuleUpdatesExternalChanges";
    String appName = harness.getDefaultWebAppName(prefix);
    IProject project = createWebApplicationProject();
    boolean stopMode = false;
    // Configure the test fixture for deployment.
    // This step is a subsreplacedute for the Application deployment wizard
    getTestFixture().configureForApplicationDeployment(appName, CloudUtil.DEFAULT_MEMORY, stopMode);
    IModule module = getModule(project.getName());
    // Push the application
    cloudServer.getBehaviour().operations().applicationDeployment(new IModule[] { module }, ApplicationAction.PUSH).run(new NullProgressMonitor());
    // After deployment the module must exist and be mapped to an existing
    // CloudApplication
    CloudFoundryApplicationModule appModule = cloudServer.getExistingCloudModule(appName);
    replacedertNotNull(appModule);
    // Test that the mapping to the actual application in the Cloud space is
    // present. Since a
    // CloudApplication is not created by the underlying client unless it
    // exists, this also
    // indirectly tests that the CloudApplication was successfully created
    // indicating the application
    // exists in the Cloud space.
    replacedertNotNull(appModule.getApplication());
    replacedertEquals(appModule.getDeployedApplicationName(), appModule.getApplication().getName());
    // To test update on external changes, verify the current memory
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, appModule.getDeploymentInfo().getMemory());
    // Verify that the CloudApplication in the Cloud space exists through
    // the list of all CloudApplications
    List<CloudApplication> applications = serverBehavior.getApplications(new NullProgressMonitor());
    boolean found = false;
    for (CloudApplication application : applications) {
        if (application.getName().equals(appName)) {
            found = true;
            break;
        }
    }
    replacedertTrue("Expected CloudApplication for " + appName + " to exist in the Cloud space", found);
    // Now modify the application externally and verify that when performing
    // a module update
    // that the new changes are picked up by the tooling
    // Create separate external client
    CloudFoundryOperations externalClient = harness.createExternalClient();
    externalClient.login();
    // Refresh Module through behaviour to check if it picks up changes
    // 1. Test via single-module update
    externalClient.updateApplicationMemory(appName, 737);
    CloudApplication updatedCloudApplicationFromClient = externalClient.getApplication(appName);
    appModule = serverBehavior.updateCloudModule(appName, new NullProgressMonitor());
    replacedertEquals(appName, appModule.getDeployedApplicationName());
    replacedertEquals(appModule.getDeployedApplicationName(), updatedCloudApplicationFromClient.getName());
    replacedertEquals(737, updatedCloudApplicationFromClient.getMemory());
    replacedertEquals(appModule.getApplication().getMemory(), updatedCloudApplicationFromClient.getMemory());
    replacedertEquals(appModule.getDeploymentInfo().getMemory(), updatedCloudApplicationFromClient.getMemory());
    // 2. Test via single-module update and it's instances
    externalClient.updateApplicationMemory(appName, 555);
    updatedCloudApplicationFromClient = externalClient.getApplication(appName);
    appModule = serverBehavior.updateCloudModuleWithInstances(appName, new NullProgressMonitor());
    replacedertEquals(appName, appModule.getDeployedApplicationName());
    replacedertEquals(appModule.getDeployedApplicationName(), updatedCloudApplicationFromClient.getName());
    replacedertEquals(appModule.getDeployedApplicationName(), updatedCloudApplicationFromClient.getName());
    replacedertEquals(555, updatedCloudApplicationFromClient.getMemory());
    replacedertEquals(appModule.getApplication().getMemory(), updatedCloudApplicationFromClient.getMemory());
    replacedertEquals(appModule.getDeploymentInfo().getMemory(), updatedCloudApplicationFromClient.getMemory());
    // 3. Test via module refresh of all modules
    externalClient.updateApplicationMemory(appName, 345);
    updatedCloudApplicationFromClient = externalClient.getApplication(appName);
    Map<String, CloudApplication> allApps = new HashMap<String, CloudApplication>();
    allApps.put(updatedCloudApplicationFromClient.getName(), updatedCloudApplicationFromClient);
    cloudServer.updateModules(allApps);
    appModule = cloudServer.getExistingCloudModule(appName);
    replacedertEquals(appName, appModule.getDeployedApplicationName());
    replacedertEquals(appModule.getDeployedApplicationName(), updatedCloudApplicationFromClient.getName());
    replacedertEquals(appModule.getDeployedApplicationName(), updatedCloudApplicationFromClient.getName());
    replacedertEquals(345, updatedCloudApplicationFromClient.getMemory());
    replacedertEquals(appModule.getApplication().getMemory(), updatedCloudApplicationFromClient.getMemory());
    replacedertEquals(appModule.getDeploymentInfo().getMemory(), updatedCloudApplicationFromClient.getMemory());
}

8 View Complete Implementation : PushApplicationOperation.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
@Override
protected void pushApplication(CloudFoundryOperations client, final CloudFoundryApplicationModule appModule, ApplicationArchive applicationArchive, final IProgressMonitor monitor) throws CoreException {
    String appName = appModule.getDeploymentInfo().getDeploymentName();
    List<CloudApplication> existingApps = client.getApplications();
    boolean found = false;
    for (CloudApplication existingApp : existingApps) {
        if (existingApp.getName().equals(appName)) {
            found = true;
            break;
        }
    }
    // Create the application if it doesn't already exist
    if (!found) {
        String creatingAppLabel = NLS.bind(Messages.CONSOLE_APP_CREATION, appName);
        getBehaviour().printlnToConsole(appModule, creatingAppLabel);
        // BUG - [87862532]: Fetch all the information BEFORE
        // creating the application. The reason for this
        // is to prevent any other operation that updates the module from
        // clearing the deploymentinfo after the application is created
        // but before other properties are updated like environment
        // variables
        // and instances
        Staging staging = appModule.getDeploymentInfo().getStaging();
        List<String> uris = appModule.getDeploymentInfo().getUris() != null ? appModule.getDeploymentInfo().getUris() : new ArrayList<String>(0);
        List<String> services = appModule.getDeploymentInfo().replacederviceBindingList();
        List<EnvironmentVariable> variables = appModule.getDeploymentInfo().getEnvVariables();
        int instances = appModule.getDeploymentInfo().getInstances();
        if (staging == null) {
            // For v2, a non-null staging is required.
            staging = new Staging();
        }
        CoreException cloudAppCreationClientError = null;
        // Guard against host taken errors and other errors that may
        // create the app but
        // prevent further deployment. If the app was still created
        // attempt to set env vars and instaces
        SubMonitor subMonitor = SubMonitor.convert(monitor, 50);
        subMonitor.subTask(creatingAppLabel);
        try {
            client.createApplication(appName, staging, appModule.getDeploymentInfo().getMemory(), uris, services);
        } catch (Exception e) {
            String hostTaken = CloudErrorUtil.getHostTakenError(e);
            if (hostTaken != null) {
                cloudAppCreationClientError = CloudErrorUtil.toCoreException(hostTaken);
            } else {
                cloudAppCreationClientError = CloudErrorUtil.toCoreException(e);
            }
        }
        subMonitor.worked(30);
        // [87881946] - Try setting the env vars and instances even if an
        // error was thrown while creating the application
        // as the application may still have been created in the Cloud space
        // in spite of the error
        try {
            CloudApplication actualApp = getBehaviour().getCloudApplication(appName, subMonitor.newChild(20));
            if (actualApp != null) {
                SubMonitor updateMonitor = SubMonitor.convert(subMonitor, 100);
                getBehaviour().getUpdateEnvVarRequest(appName, variables).run(updateMonitor.newChild(50));
                // Update instances if it is more than 1. By default, app
                // starts
                // with 1 instance.
                if (instances > 1) {
                    getBehaviour().updateApplicationInstances(appName, instances, updateMonitor.newChild(50));
                } else {
                    updateMonitor.worked(50);
                }
            }
        } catch (CoreException ce) {
            if (cloudAppCreationClientError == null) {
                throw ce;
            }
        }
        // Even if application was created in the Cloud space, and env vars
        // and instances set, if an exception
        // was thrown while creating the client, throw it
        if (cloudAppCreationClientError != null) {
            throw cloudAppCreationClientError;
        }
    }
    super.pushApplication(client, appModule, applicationArchive, monitor);
}

8 View Complete Implementation : PushApplicationOperation.java
Copyright Apache License 2.0
Author : PaaS-TA
@Override
protected void pushApplication(CloudFoundryOperations client, final CloudFoundryApplicationModule appModule, File warFile, ApplicationArchive applicationArchive, final IProgressMonitor monitor) throws CoreException {
    String appName = appModule.getDeploymentInfo().getDeploymentName();
    List<CloudApplication> existingApps = client.getApplications();
    boolean found = false;
    for (CloudApplication existingApp : existingApps) {
        if (existingApp.getName().equals(appName)) {
            found = true;
            break;
        }
    }
    // Create the application if it doesn't already exist
    if (!found) {
        String creatingAppLabel = NLS.bind(Messages.CONSOLE_APP_CREATION, appName);
        getBehaviour().printlnToConsole(appModule, creatingAppLabel);
        // BUG - [87862532]: Fetch all the information BEFORE
        // creating the application. The reason for this
        // is to prevent any other operation that updates the module from
        // clearing the deploymentinfo after the application is created
        // but before other properties are updated like environment
        // variables
        // and instances
        Staging staging = appModule.getDeploymentInfo().getStaging();
        List<String> uris = appModule.getDeploymentInfo().getUris() != null ? appModule.getDeploymentInfo().getUris() : new ArrayList<String>(0);
        List<String> services = appModule.getDeploymentInfo().replacederviceBindingList();
        List<EnvironmentVariable> variables = appModule.getDeploymentInfo().getEnvVariables();
        int instances = appModule.getDeploymentInfo().getInstances();
        if (staging == null) {
            // For v2, a non-null staging is required.
            staging = new Staging();
        }
        CoreException cloudAppCreationClientError = null;
        // Guard against host taken errors and other errors that may
        // create the app but
        // prevent further deployment. If the app was still created
        // attempt to set env vars and instaces
        SubMonitor subMonitor = SubMonitor.convert(monitor, 50);
        subMonitor.subTask(creatingAppLabel);
        try {
            client.createApplication(appName, staging, appModule.getDeploymentInfo().getMemory(), uris, services);
        } catch (Exception e) {
            String hostTaken = CloudErrorUtil.getHostTakenError(e);
            if (hostTaken != null) {
                cloudAppCreationClientError = CloudErrorUtil.toCoreException(hostTaken);
            } else {
                cloudAppCreationClientError = CloudErrorUtil.toCoreException(e);
            }
        }
        subMonitor.worked(30);
        // [87881946] - Try setting the env vars and instances even if an
        // error was thrown while creating the application
        // as the application may still have been created in the Cloud space
        // in spite of the error
        try {
            CloudApplication actualApp = getBehaviour().getCloudApplication(appName, subMonitor.newChild(20));
            if (actualApp != null) {
                SubMonitor updateMonitor = SubMonitor.convert(subMonitor, 100);
                getBehaviour().getUpdateEnvVarRequest(appName, variables).run(updateMonitor.newChild(50));
                // Update instances if it is more than 1. By default, app
                // starts
                // with 1 instance.
                if (instances > 1) {
                    getBehaviour().updateApplicationInstances(appName, instances, updateMonitor.newChild(50));
                } else {
                    updateMonitor.worked(50);
                }
            }
        } catch (CoreException ce) {
            if (cloudAppCreationClientError == null) {
                throw ce;
            }
        }
        // Even if application was created in the Cloud space, and env vars
        // and instances set, if an exception
        // was thrown while creating the client, throw it
        if (cloudAppCreationClientError != null) {
            throw cloudAppCreationClientError;
        }
    }
    super.pushApplication(client, appModule, warFile, applicationArchive, monitor);
}

6 View Complete Implementation : CloudFoundryServerBehaviourTest.java
Copyright Apache License 2.0
Author : cloudfoundry-attic
public void testApplicationDeploymentInfo() throws Exception {
    String prefix = "testApplicationDeploymentInfo";
    String expectedAppName = harness.getDefaultWebAppName(prefix);
    CloudFoundryOperations client = harness.createExternalClient();
    client.login();
    CloudService service = getCloudServiceToCreate("sqlService", "elephantsql", "turtle");
    List<CloudService> servicesToBind = new ArrayList<CloudService>();
    servicesToBind.add(service);
    client.createService(service);
    EnvironmentVariable variable = new EnvironmentVariable();
    variable.setVariable("JAVA_OPTS");
    variable.setValue("-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n");
    List<EnvironmentVariable> vars = new ArrayList<EnvironmentVariable>();
    vars.add(variable);
    createWebApplicationProject();
    CloudFoundryApplicationModule appModule = deployApplication(prefix, CloudUtil.DEFAULT_MEMORY, false, vars, servicesToBind);
    waitForApplicationToStart(appModule.getLocalModule(), prefix);
    appModule = cloudServer.getExistingCloudModule(appModule.getDeployedApplicationName());
    replacedertNotNull(appModule.getApplication());
    replacedertNotNull(appModule.getDeploymentInfo());
    CloudApplication actualApp = appModule.getApplication();
    replacedertEquals(appModule.getDeployedApplicationName(), actualApp.getName());
    replacedertEquals(expectedAppName, actualApp.getName());
    ApplicationDeploymentInfo info = appModule.getDeploymentInfo();
    replacedertEquals(expectedAppName, info.getDeploymentName());
    // Verify that both the deployment info and the actual Cloud application
    // contain
    // the same information
    replacedertEquals(actualApp.getInstances(), info.getInstances());
    replacedertEquals(1, info.getInstances());
    String expectedUrl = harness.getExpectedDefaultURL(prefix);
    replacedertEquals(actualApp.getUris().get(0), info.getUris().get(0));
    replacedertEquals(expectedUrl, info.getUris().get(0));
    replacedertEquals(actualApp.getMemory(), info.getMemory());
    replacedertEquals(CloudUtil.DEFAULT_MEMORY, info.getMemory());
    replacedertEquals("JAVA_OPTS", appModule.getDeploymentInfo().getEnvVariables().get(0).getVariable());
    replacedertEquals("-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n", appModule.getDeploymentInfo().getEnvVariables().get(0).getValue());
    replacedertTrue(actualApp.getEnvAsMap().containsKey("JAVA_OPTS"));
    replacedertEquals("-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n", actualApp.getEnvAsMap().get("JAVA_OPTS"));
    replacedertEquals("sqlService", appModule.getDeploymentInfo().getServices().get(0).getName());
    replacedertEquals("sqlService", actualApp.getServices().get(0));
}