Projects >> cf-java-client >>a6c487420e788eb595f2b6c347268de036f3e08f

Chunk
Conflicting content
	private String email;

 */
public class CloudCredentials {

<<<<<<< HEAD
	private boolean refreshable = true;

	private String password;

	private String clientId = "cf";

	private String clientSecret = "";

	private OAuth2AccessToken token;

	private String proxyUser;

	/**
	 * Create credentials using email and password.
	 *
	 * @param email email to authenticate with
	 * @param password the password
	 */
	public CloudCredentials(String email, String password) {
		this.email = email;
		this.password = password;
	}

	/**
	 * Create credentials using email, password, and client ID.
	 *
	 * @param email email to authenticate with
	 * @param password the password
	 * @param clientId the client ID to use for authorization
	 */
	public CloudCredentials(String email, String password, String clientId) {
		this.email = email;
		this.password = password;
		this.clientId = clientId;
	}

	/**
	 * Create credentials using email, password and client ID.
	 * @param email email to authenticate with
	 * @param password the password
	 * @param clientId the client ID to use for authorization
	 * @param clientSecret the secret for the given client
	 */
	public CloudCredentials(String email, String password, String clientId, String clientSecret) {
		this.email = email;
		this.password = password;
		this.clientId = clientId;
		this.clientSecret = clientSecret;
	}

	/**
	 * Create credentials using a token.
	 *
	 * @param token token to use for authorization
	 */
	public CloudCredentials(OAuth2AccessToken token) {
		this.token = token;
	}

    /**
     * Create credentials using a token and indicates if the token is
     * refreshable or not.
     *
     * @param token token to use for authorization
     * @param refreshable indicates if the token can be refreshed or not
     */
    public CloudCredentials(OAuth2AccessToken token, boolean refreshable) {
        this.token = token;
        this.refreshable=refreshable;
    }

	/**
	 * Create credentials using a token.
	 *
	 * @param token token to use for authorization
	 * @param clientId the client ID to use for authorization
	 */
	public CloudCredentials(OAuth2AccessToken token, String clientId) {
		this.token = token;
		this.clientId = clientId;
	}

	/**
	 * Create credentials using a token.
	 *
	 * @param token token to use for authorization
	 * @param clientId the client ID to use for authorization
	 * @param clientSecret the password for the specified client
	 */
	public CloudCredentials(OAuth2AccessToken token, String clientId, String clientSecret) {
		this.token = token;
		this.clientId = clientId;
		this.clientSecret = clientSecret;
	}

	/**
	 * Create proxy credentials.
	 *
	 * @param cloudCredentials credentials to use
	 * @param proxyForUser user to be proxied
	 */
	public CloudCredentials(CloudCredentials cloudCredentials, String proxyForUser) {
		this.email = cloudCredentials.getEmail();
		this.password = cloudCredentials.getPassword();
		this.clientId = cloudCredentials.getClientId();
		this.token = cloudCredentials.getToken();
		this.proxyUser = proxyForUser;
	}

	/**
	 * Get the email.
	 *
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * Get the password.
	 *
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * Get the token.
	 *
	 * @return the token
	 */
	public OAuth2AccessToken getToken() {
		return token;
	}

	/**
	 * Get the client ID.
	 *
	 * @return the client ID
	 */
	public String getClientId() {
		return clientId;
	}

	/**
	 * Get the client secret
	 *
	 * @return the client secret
	 */
	public String getClientSecret() {
		return clientSecret;
	}

	/**
	 * Get the proxy user.
	 *
	 * @return the proxy user
	 */
	public String getProxyUser() {
		return proxyUser;
	}

	/**
	 * Is this a proxied set of credentials?
	 *
	 * @return whether a proxy user is set
	 */
	public boolean isProxyUserSet()  {
		return proxyUser != null;
	}

	/**
	 * Run commands as a different user.  The authenticated user must be
	 * privileged to run as this user.

	 * @param user the user to proxy for
	 * @return credentials for the proxied user
	 */
	public CloudCredentials proxyForUser(String user) {
		return new CloudCredentials(this, user);
	}

	/**
	 * Indicates weather the token stored in the cloud credentials can be
	 * refreshed or not. This is useful when the token stored in this
	 * object was obtained via implicit OAuth2 authentication and therefore
	 * can not be refreshed.
	 *
	 * @return weather the token can be refreshed
	 */
	public boolean isRefreshable() {
		return refreshable;
	}
=======
    private String clientId = "cf";

    private String clientSecret = "";

    private String email;

    private String password;

    private String proxyUser;

    private OAuth2AccessToken token;

    /**
     * Create credentials using email and password.
     *
     * @param email    email to authenticate with
     * @param password the password
     */
    public CloudCredentials(String email, String password) {
        this.email = email;
        this.password = password;
    }

    /**
     * Create credentials using email, password, and client ID.
     *
     * @param email    email to authenticate with
     * @param password the password
     * @param clientId the client ID to use for authorization
     */
    public CloudCredentials(String email, String password, String clientId) {
        this.email = email;
        this.password = password;
        this.clientId = clientId;
    }

    /**
     * Create credentials using email, password and client ID.
     *
     * @param email        email to authenticate with
     * @param password     the password
     * @param clientId     the client ID to use for authorization
     * @param clientSecret the secret for the given client
     */
    public CloudCredentials(String email, String password, String clientId, String clientSecret) {
        this.email = email;
        this.password = password;
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    }

    /**
     * Create credentials using a token.
     *
     * @param token token to use for authorization
     */
    public CloudCredentials(OAuth2AccessToken token) {
        this.token = token;
    }

    /**
     * Create credentials using a token.
     *
     * @param token    token to use for authorization
     * @param clientId the client ID to use for authorization
     */
    public CloudCredentials(OAuth2AccessToken token, String clientId) {
        this.token = token;
        this.clientId = clientId;
    }

    /**
     * Create credentials using a token.
     *
     * @param token        token to use for authorization
     * @param clientId     the client ID to use for authorization
     * @param clientSecret the password for the specified client
     */
    public CloudCredentials(OAuth2AccessToken token, String clientId, String clientSecret) {
        this.token = token;
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    }

    /**
     * Create proxy credentials.
     *
     * @param cloudCredentials credentials to use
     * @param proxyForUser     user to be proxied
     */
    public CloudCredentials(CloudCredentials cloudCredentials, String proxyForUser) {
        this.email = cloudCredentials.getEmail();
        this.password = cloudCredentials.getPassword();
        this.clientId = cloudCredentials.getClientId();
        this.token = cloudCredentials.getToken();
        this.proxyUser = proxyForUser;
    }

    /**
     * Get the client ID.
     *
     * @return the client ID
     */
    public String getClientId() {
        return clientId;
    }

    /**
     * Get the client secret
     *
     * @return the client secret
     */
    public String getClientSecret() {
        return clientSecret;
    }

    /**
     * Get the email.
     *
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * Get the password.
     *
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * Get the proxy user.
     *
     * @return the proxy user
     */
    public String getProxyUser() {
        return proxyUser;
    }

    /**
     * Get the token.
     *
     * @return the token
     */
    public OAuth2AccessToken getToken() {
        return token;
    }

    /**
     * Is this a proxied set of credentials?
     *
     * @return whether a proxy user is set
     */
    public boolean isProxyUserSet() {
        return proxyUser != null;
    }

    /**
     * Run commands as a different user.  The authenticated user must be privileged to run as this user.
     *
     * @param user the user to proxy for
     * @return credentials for the proxied user
     */
    public CloudCredentials proxyForUser(String user) {
        return new CloudCredentials(this, user);
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
 */
public class CloudCredentials {

    private String clientId = "cf";

    private String clientSecret = "";

    private String email;

    private String password;

    private String proxyUser;

    private boolean refreshable = true;

    private OAuth2AccessToken token;

    /**
     * Create credentials using email and password.
     *
     * @param email    email to authenticate with
     * @param password the password
     */
    public CloudCredentials(String email, String password) {
        this.email = email;
        this.password = password;
    }

    /**
     * Create credentials using email, password, and client ID.
     *
     * @param email    email to authenticate with
     * @param password the password
     * @param clientId the client ID to use for authorization
     */
    public CloudCredentials(String email, String password, String clientId) {
        this.email = email;
        this.password = password;
        this.clientId = clientId;
    }

    /**
     * Create credentials using email, password and client ID.
     *
     * @param email        email to authenticate with
     * @param password     the password
     * @param clientId     the client ID to use for authorization
     * @param clientSecret the secret for the given client
     */
    public CloudCredentials(String email, String password, String clientId, String clientSecret) {
        this.email = email;
        this.password = password;
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    /**
    }

    /**
     * Create credentials using a token.
     *
     * @param token token to use for authorization
     */
    public CloudCredentials(OAuth2AccessToken token) {
        this.token = token;
    }

    /**
     * Create credentials using a token and indicates if the token is refreshable or not.
     *
     * @param token       token to use for authorization
     * @param refreshable indicates if the token can be refreshed or not
     */
    public CloudCredentials(OAuth2AccessToken token, boolean refreshable) {
        this.token = token;
        this.refreshable = refreshable;
    }

    /**
     * Create credentials using a token.
     *
     * @param token    token to use for authorization
     * @param clientId the client ID to use for authorization
     */
    public CloudCredentials(OAuth2AccessToken token, String clientId) {
        this.token = token;
        this.clientId = clientId;
    }

    /**
     * Create credentials using a token.
     *
     * @param token        token to use for authorization
     * @param clientId     the client ID to use for authorization
     * @param clientSecret the password for the specified client
     */
    public CloudCredentials(OAuth2AccessToken token, String clientId, String clientSecret) {
        this.token = token;
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    }

    /**
     * Create proxy credentials.
     *
     * @param cloudCredentials credentials to use
     * @param proxyForUser     user to be proxied
     */
    public CloudCredentials(CloudCredentials cloudCredentials, String proxyForUser) {
        this.email = cloudCredentials.getEmail();
        this.password = cloudCredentials.getPassword();
        this.clientId = cloudCredentials.getClientId();
        this.token = cloudCredentials.getToken();
        this.proxyUser = proxyForUser;
    }

    /**
     * Get the client ID.
     *
     * @return the client ID
     */
    public String getClientId() {
        return clientId;
    }

    /**
     * Get the client secret
     *
     * @return the client secret
     */
    public String getClientSecret() {
        return clientSecret;
    }

    /**
     * Get the email.
     *
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * Get the password.
     *
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * Get the proxy user.
     *
     * @return the proxy user
     */
    public String getProxyUser() {
        return proxyUser;
    }

    /**
     * Get the token.
     *
     * @return the token
     */
    public OAuth2AccessToken getToken() {
        return token;
    }

     * Is this a proxied set of credentials?
     *
     * @return whether a proxy user is set
     */
    public boolean isProxyUserSet() {
        return proxyUser != null;
    }

    /**
     * Indicates weather the token stored in the cloud credentials can be refreshed or not. This is useful when the
     * token stored in this object was obtained via implicit OAuth2 authentication and therefore can not be refreshed.
     *
     * @return weather the token can be refreshed
     */
    public boolean isRefreshable() {
        return refreshable;
    }

    /**
     * Run commands as a different user.  The authenticated user must be privileged to run as this user.
     *
     * @param user the user to proxy for
     * @return credentials for the proxied user
     */
    public CloudCredentials proxyForUser(String user) {
        return new CloudCredentials(this, user);
    }
}
File
CloudCredentials.java
Developer's decision
Manual
Kind of conflict
Attribute
Comment
Method declaration
Chunk
Conflicting content
	}
 */
public class CloudFoundryClient implements CloudFoundryOperations {

<<<<<<< HEAD
	private CloudControllerClient cc;

	private CloudInfo info;

	/**
	 * Construct client for anonymous user. Useful only to get to the '/info' endpoint.
	 */

	public CloudFoundryClient(URL cloudControllerUrl) {
		this(null, cloudControllerUrl, null, (HttpProxyConfiguration) null, false);
	}

	public CloudFoundryClient(URL cloudControllerUrl, boolean trustSelfSignedCerts) {
		this(null, cloudControllerUrl, null, (HttpProxyConfiguration) null, trustSelfSignedCerts);
	}

	public CloudFoundryClient(URL cloudControllerUrl, HttpProxyConfiguration httpProxyConfiguration) {
		this(null, cloudControllerUrl, null, httpProxyConfiguration, false);


	public CloudFoundryClient(URL cloudControllerUrl, HttpProxyConfiguration httpProxyConfiguration,
	                          boolean trustSelfSignedCerts) {
		this(null, cloudControllerUrl, null, httpProxyConfiguration, trustSelfSignedCerts);
	}

	/**
	 * Construct client without a default org and space.
	 */

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl) {
		this(credentials, cloudControllerUrl, null, (HttpProxyConfiguration) null, false);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
	                          boolean trustSelfSignedCerts) {
		this(credentials, cloudControllerUrl, null, (HttpProxyConfiguration) null, trustSelfSignedCerts);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
	                          HttpProxyConfiguration httpProxyConfiguration) {
		this(credentials, cloudControllerUrl, null, httpProxyConfiguration, false);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
	                          HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
		this(credentials, cloudControllerUrl, null, httpProxyConfiguration, trustSelfSignedCerts);
	}

	/**
	 * Construct a client with a default CloudSpace.
	 */

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace) {
		this(credentials, cloudControllerUrl, sessionSpace, null, false);
    }

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
	                          boolean trustSelfSignedCerts) {
		this(credentials, cloudControllerUrl, sessionSpace, null, trustSelfSignedCerts);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
	                          HttpProxyConfiguration httpProxyConfiguration) {
		this(credentials, cloudControllerUrl, sessionSpace, httpProxyConfiguration, false);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
		return cc.getApplicationEnvironment(appGuid);
	}
	                          HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
		Assert.notNull(cloudControllerUrl, "URL for cloud controller cannot be null");
		CloudControllerClientFactory cloudControllerClientFactory =
				new CloudControllerClientFactory(httpProxyConfiguration, trustSelfSignedCerts);
		this.cc = cloudControllerClientFactory.newCloudController(cloudControllerUrl, credentials, sessionSpace);
	}

	/**
	 * Construct a client with a default space name and org name.
	 */

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName) {
		this(credentials, cloudControllerUrl, orgName, spaceName, null, false);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
	                          boolean trustSelfSignedCerts) {
		this(credentials, cloudControllerUrl, orgName, spaceName, null, trustSelfSignedCerts);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
							  HttpProxyConfiguration httpProxyConfiguration) {
		this(credentials, cloudControllerUrl, orgName, spaceName, httpProxyConfiguration, false);
	}

	public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
	                          HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
		Assert.notNull(cloudControllerUrl, "URL for cloud controller cannot be null");
		CloudControllerClientFactory cloudControllerClientFactory =
				new CloudControllerClientFactory(httpProxyConfiguration, trustSelfSignedCerts);
		this.cc = cloudControllerClientFactory.newCloudController(cloudControllerUrl, credentials, orgName, spaceName);
	}

	/**
	 * Construct a client with a pre-configured CloudControllerClient
	 */

	public CloudFoundryClient(CloudControllerClient cc) {
		this.cc = cc;
	}

	public void setResponseErrorHandler(ResponseErrorHandler errorHandler) {
		cc.setResponseErrorHandler(errorHandler);
	}

	public URL getCloudControllerUrl() {
		return cc.getCloudControllerUrl();
	}

	public CloudInfo getCloudInfo() {
		if (info == null) {
			info = cc.getInfo();
		}
		return info;
	}

	public List getSpaces() {
		return cc.getSpaces();
	}

	public List getOrganizations() {
		return cc.getOrganizations();
	}

	public void register(String email, String password) {
		cc.register(email, password);
	}

	public void updatePassword(String newPassword) {
		cc.updatePassword(newPassword);
	}

	public void updatePassword(CloudCredentials credentials, String newPassword) {
		cc.updatePassword(credentials, newPassword);
	}

	public void unregister() {
		cc.unregister();
	}

	public OAuth2AccessToken login() {
		return cc.login();
	}

	public void logout() {
		cc.logout();
	}

	public List getApplications() {
		return cc.getApplications();
	}

	public CloudApplication getApplication(String appName) {
		return cc.getApplication(appName);
	}

	public CloudApplication getApplication(UUID appGuid) {
		return cc.getApplication(appGuid);
	}

	public Map getApplicationEnvironment(UUID appGuid) {
   	public Map getApplicationEnvironment(String appName) {
    	return cc.getApplicationEnvironment(appName);
	}

	public ApplicationStats getApplicationStats(String appName) {
		return cc.getApplicationStats(appName);
	}

	public void createApplication(String appName, Staging staging, Integer memory, List uris,
								  List serviceNames) {
		cc.createApplication(appName, staging, memory, uris, serviceNames);
	}

	public void createApplication(String appName, Staging staging, Integer disk, Integer memory, List uris,
								  List serviceNames) {
		cc.createApplication(appName, staging, disk, memory, uris, serviceNames);
	}

	public void createService(CloudService service) {
		cc.createService(service);
	}

	public void createUserProvidedService(CloudService service, Map credentials) {
		cc.createUserProvidedService(service, credentials);
	}

	public void createUserProvidedService(CloudService service, Map credentials, String syslogDrainUrl) {
		cc.createUserProvidedService(service, credentials, syslogDrainUrl);
	}

	@Override
	public List deleteOrphanedRoutes() {
    	return cc.deleteOrphanedRoutes();
	}

	public void uploadApplication(String appName, String file) throws IOException {
		cc.uploadApplication(appName, new File(file), null);
	}

	public void uploadApplication(String appName, File file) throws IOException {
		cc.uploadApplication(appName, file, null);
	}
	public void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException {
		cc.uploadApplication(appName, file, callback);
	}

	public void uploadApplication(String appName, String fileName, InputStream inputStream) throws IOException {
		cc.uploadApplication(appName, fileName, inputStream, null);
	}

	public void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback callback) throws IOException {
		cc.uploadApplication(appName, fileName, inputStream, callback);
	}

	public void uploadApplication(String appName, ApplicationArchive archive) throws IOException {
		cc.uploadApplication(appName, archive, null);
	}

	public void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws IOException {
		cc.uploadApplication(appName, archive, callback);
	}

	public StartingInfo startApplication(String appName) {
		return cc.startApplication(appName);
	}

	public void debugApplication(String appName, DebugMode mode) {
		cc.debugApplication(appName, mode);
	}

	public void stopApplication(String appName) {
		cc.stopApplication(appName);
	}

	public StartingInfo restartApplication(String appName) {
		return cc.restartApplication(appName);
	}

	public void deleteApplication(String appName) {
		cc.deleteApplication(appName);
	}

	public void deleteAllApplications() {
		cc.deleteAllApplications();
	}

	public void deleteAllServices() {
		cc.deleteAllServices();
	}

	public void updateApplicationDiskQuota(String appName, int disk) {
		cc.updateApplicationDiskQuota(appName, disk);
	}

	public void updateApplicationMemory(String appName, int memory) {
		cc.updateApplicationMemory(appName, memory);
	}

	public void updateApplicationInstances(String appName, int instances) {
		cc.updateApplicationInstances(appName, instances);
	}

	public void updateApplicationServices(String appName, List services) {
		cc.updateApplicationServices(appName, services);
	}

	public void updateApplicationStaging(String appName, Staging staging) {
		cc.updateApplicationStaging(appName, staging);
	}

	public void updateApplicationUris(String appName, List uris) {
		cc.updateApplicationUris(appName, uris);
	}

	public void updateApplicationEnv(String appName, Map env) {
		cc.updateApplicationEnv(appName, env);
	}

	public void updateApplicationEnv(String appName, List env) {
		cc.updateApplicationEnv(appName, env);
	}

	public List getEvents() {
		return cc.getEvents();
	}

	public List getApplicationEvents(String appName) {
		return cc.getApplicationEvents(appName);
	}

	/**
	 * @deprecated use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
	 */
	public Map getLogs(String appName) {
		return cc.getLogs(appName);
	}

	public StreamingLogToken streamLogs(String appName, ApplicationLogListener listener) {
	    return cc.streamLogs(appName, listener);
	}

	public List getRecentLogs(String appName) {
		return cc.getRecentLogs(appName);
	}

	/**
	 * @deprecated use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
	 */
	public Map getCrashLogs(String appName) {
		return cc.getCrashLogs(appName);
	}

	public String getStagingLogs(StartingInfo info, int offset) {
		return cc.getStagingLogs(info, offset);
	}

	public String getFile(String appName, int instanceIndex, String filePath) {
		return cc.getFile(appName, instanceIndex, filePath, 0, -1);
	}

	public String getFile(String appName, int instanceIndex, String filePath, int startPosition) {
		Assert.isTrue(startPosition >= 0,
				startPosition + " is not a valid value for start position, it should be 0 or greater.");
		return cc.getFile(appName, instanceIndex, filePath, startPosition, -1);
	}

	public String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition) {
		Assert.isTrue(startPosition >= 0,
				startPosition + " is not a valid value for start position, it should be 0 or greater.");
		Assert.isTrue(endPosition > startPosition,
				endPosition + " is not a valid value for end position, it should be greater than startPosition " +
						"which is " + startPosition + ".");
		return cc.getFile(appName, instanceIndex, filePath, startPosition, endPosition - 1);
	}

	public void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback callback) {
		cc.openFile(appName, instanceIndex, filePath, callback);
	}

	public String getFileTail(String appName, int instanceIndex, String filePath, int length) {
		Assert.isTrue(length > 0, length + " is not a valid value for length, it should be 1 or greater.");
		return cc.getFile(appName, instanceIndex, filePath, -1, length);
	}

	// list services, un/provision services, modify instance

	public List getServices() {
		return cc.getServices();
	}

	public List getServiceBrokers() {
		return cc.getServiceBrokers();
	}

	public CloudServiceBroker getServiceBroker(String name) {
		return cc.getServiceBroker(name);
	}

	public void createServiceBroker(CloudServiceBroker serviceBroker) {
		cc.createServiceBroker(serviceBroker);
	}

	public void updateServiceBroker(CloudServiceBroker serviceBroker) {
		cc.updateServiceBroker(serviceBroker);
	}

	@Override
	public void deleteServiceBroker(String name) {
		cc.deleteServiceBroker(name);
	}

	@Override
	public void updateServicePlanVisibilityForBroker(String name, boolean visibility) {
		cc.updateServicePlanVisibilityForBroker(name, visibility);
	}

	public CloudService getService(String service) {
		return cc.getService(service);
	}

    public CloudServiceInstance getServiceInstance(String service) {
		return cc.getServiceInstance(service);
	}

	public void deleteService(String service) {
		cc.deleteService(service);
	}
=======
    private CloudControllerClient cc;

    private CloudInfo info;

    /**
     * Construct client for anonymous user. Useful only to get to the '/info' endpoint.
     */

    public CloudFoundryClient(URL cloudControllerUrl) {
        this(null, cloudControllerUrl, null, (HttpProxyConfiguration) null, false);
    }

    public CloudFoundryClient(URL cloudControllerUrl, boolean trustSelfSignedCerts) {
        this(null, cloudControllerUrl, null, (HttpProxyConfiguration) null, trustSelfSignedCerts);
    }


    public CloudFoundryClient(URL cloudControllerUrl, HttpProxyConfiguration httpProxyConfiguration) {
        this(null, cloudControllerUrl, null, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(URL cloudControllerUrl, HttpProxyConfiguration httpProxyConfiguration,
                              boolean trustSelfSignedCerts) {
        this(null, cloudControllerUrl, null, httpProxyConfiguration, trustSelfSignedCerts);
    }

    /**
     * Construct client without a default org and space.
     */

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl) {
        this(credentials, cloudControllerUrl, null, (HttpProxyConfiguration) null, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
                              boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, null, (HttpProxyConfiguration) null, trustSelfSignedCerts);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
                              HttpProxyConfiguration httpProxyConfiguration) {
        this(credentials, cloudControllerUrl, null, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
                              HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, null, httpProxyConfiguration, trustSelfSignedCerts);
    }

    /**
     * Construct a client with a default CloudSpace.
     */

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace) {
        this(credentials, cloudControllerUrl, sessionSpace, null, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
                              boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, sessionSpace, null, trustSelfSignedCerts);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
                              HttpProxyConfiguration httpProxyConfiguration) {

        this(credentials, cloudControllerUrl, sessionSpace, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
                              HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
        Assert.notNull(cloudControllerUrl, "URL for cloud controller cannot be null");
        CloudControllerClientFactory cloudControllerClientFactory =
                new CloudControllerClientFactory(httpProxyConfiguration, trustSelfSignedCerts);
        this.cc = cloudControllerClientFactory.newCloudController(cloudControllerUrl, credentials, sessionSpace);
    }

    /**
     * Construct a client with a default space name and org name.
     */

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName) {
        this(credentials, cloudControllerUrl, orgName, spaceName, null, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
                              boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, orgName, spaceName, null, trustSelfSignedCerts);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
                              HttpProxyConfiguration httpProxyConfiguration) {
        this(credentials, cloudControllerUrl, orgName, spaceName, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
                              HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
        Assert.notNull(cloudControllerUrl, "URL for cloud controller cannot be null");
        CloudControllerClientFactory cloudControllerClientFactory =
                new CloudControllerClientFactory(httpProxyConfiguration, trustSelfSignedCerts);
        this.cc = cloudControllerClientFactory.newCloudController(cloudControllerUrl, credentials, orgName, spaceName);
    }

    /**
     * Construct a client with a pre-configured CloudControllerClient
     */
    public CloudFoundryClient(CloudControllerClient cc) {
        this.cc = cc;
    }

    public void addDomain(String domainName) {
        cc.addDomain(domainName);
    }

    public void addRoute(String host, String domainName) {
        cc.addRoute(host, domainName);
    }

    public void bindService(String appName, String serviceName) {
        cc.bindService(appName, serviceName);
    }

    public void createApplication(String appName, Staging staging, Integer memory, List uris,
                                  List serviceNames) {
        cc.createApplication(appName, staging, memory, uris, serviceNames);
    }

    public void createApplication(String appName, Staging staging, Integer disk, Integer memory, List uris,
                                  List serviceNames) {
        cc.createApplication(appName, staging, disk, memory, uris, serviceNames);
    }

    public void createQuota(CloudQuota quota) {
        cc.createQuota(quota);
    }

    public void createService(CloudService service) {
        cc.createService(service);
    }

    public void createServiceBroker(CloudServiceBroker serviceBroker) {
        cc.createServiceBroker(serviceBroker);
    }

    @Override
    public void createSpace(String spaceName) {
        cc.createSpace(spaceName);
    }

    public void createUserProvidedService(CloudService service, Map credentials) {
        cc.createUserProvidedService(service, credentials);
    }

    public void createUserProvidedService(CloudService service, Map credentials, String
            syslogDrainUrl) {

        cc.createUserProvidedService(service, credentials, syslogDrainUrl);
    }

    public void debugApplication(String appName, DebugMode mode) {
        cc.debugApplication(appName, mode);
    }

    public void deleteAllApplications() {
        cc.deleteAllApplications();
    }

    public void deleteAllServices() {
        cc.deleteAllServices();
    }

    public void deleteApplication(String appName) {
        cc.deleteApplication(appName);
    }

    public void deleteDomain(String domainName) {
        cc.deleteDomain(domainName);
    }

    @Override
    public List deleteOrphanedRoutes() {
        return cc.deleteOrphanedRoutes();
    }

    public void deleteQuota(String quotaName) {
        cc.deleteQuota(quotaName);
    }

    public void deleteRoute(String host, String domainName) {
        cc.deleteRoute(host, domainName);
    }

    public void deleteService(String service) {
        cc.deleteService(service);
    }

    @Override
    public void deleteServiceBroker(String name) {
        cc.deleteServiceBroker(name);
    }

    @Override
    public void deleteSpace(String spaceName) {
        cc.deleteSpace(spaceName);
    }

    public CloudApplication getApplication(String appName) {
        return cc.getApplication(appName);
    }

    public CloudApplication getApplication(UUID appGuid) {
        return cc.getApplication(appGuid);
    }

    public InstancesInfo getApplicationInstances(String appName) {
        return cc.getApplicationInstances(appName);
    }

    public InstancesInfo getApplicationInstances(CloudApplication app) {
        return cc.getApplicationInstances(app);
    }

    public ApplicationStats getApplicationStats(String appName) {
        return cc.getApplicationStats(appName);
    }

    public List getApplications() {
        return cc.getApplications();
    }

    public URL getCloudControllerUrl() {
        return cc.getCloudControllerUrl();
    }

    public CloudInfo getCloudInfo() {
        if (info == null) {
            info = cc.getInfo();
        }
        return info;
    }

    /**
     * @deprecated use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
     */
    public Map getCrashLogs(String appName) {
        return cc.getCrashLogs(appName);
    }

    public CrashesInfo getCrashes(String appName) {
        return cc.getCrashes(appName);
    }

    public CloudDomain getDefaultDomain() {
        return cc.getDefaultDomain();
    }

    public List getDomains() {
        return cc.getDomains();
    }

    public List getDomainsForOrg() {
        return cc.getDomainsForOrg();
    }

    public String getFile(String appName, int instanceIndex, String filePath) {
        return cc.getFile(appName, instanceIndex, filePath, 0, -1);
    }
    public String getFile(String appName, int instanceIndex, String filePath, int startPosition) {
        Assert.isTrue(startPosition >= 0,
                startPosition + " is not a valid value for start position, it should be 0 or greater.");
        return cc.getFile(appName, instanceIndex, filePath, startPosition, -1);
    }

    public String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition) {
        Assert.isTrue(startPosition >= 0,
                startPosition + " is not a valid value for start position, it should be 0 or greater.");
        Assert.isTrue(endPosition > startPosition,
                endPosition + " is not a valid value for end position, it should be greater than startPosition " +
                        "which is " + startPosition + ".");
        return cc.getFile(appName, instanceIndex, filePath, startPosition, endPosition - 1);
    }

    public String getFileTail(String appName, int instanceIndex, String filePath, int length) {
        Assert.isTrue(length > 0, length + " is not a valid value for length, it should be 1 or greater.");
        return cc.getFile(appName, instanceIndex, filePath, -1, length);
    }

    /**
     * @deprecated use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
     */
    public Map getLogs(String appName) {
        return cc.getLogs(appName);
    }

    public CloudOrganization getOrgByName(String orgName, boolean required) {
        return cc.getOrgByName(orgName, required);
    }

    public List getOrganizations() {
        return cc.getOrganizations();
    }

    public List getPrivateDomains() {
        return cc.getPrivateDomains();
    }
    public CloudQuota getQuotaByName(String quotaName, boolean required) {
        return cc.getQuotaByName(quotaName, required);
    }

    public List getQuotas() {
        return cc.getQuotas();
    }

    public List getRecentLogs(String appName) {
        return cc.getRecentLogs(appName);
    }

    public List getRoutes(String domainName) {
        return cc.getRoutes(domainName);
    }

    public CloudService getService(String service) {
        return cc.getService(service);
    }

    public CloudServiceBroker getServiceBroker(String name) {
        return cc.getServiceBroker(name);
    }

    public List getServiceBrokers() {
        return cc.getServiceBrokers();
    }

    public List getServiceOfferings() {
        return cc.getServiceOfferings();
    }

    public List getServices() {
        return cc.getServices();
    }

    public List getSharedDomains() {
        return cc.getSharedDomains();
    }

    // list services, un/provision services, modify instance

    @Override
    public CloudSpace getSpace(String spaceName) {
        return cc.getSpace(spaceName);
    }

    public List getSpaces() {
        return cc.getSpaces();
    }

    public CloudStack getStack(String name) {
        return cc.getStack(name);
    }

    public List getStacks() {
        return cc.getStacks();
    }

    public String getStagingLogs(StartingInfo info, int offset) {
        return cc.getStagingLogs(info, offset);
    }
    public OAuth2AccessToken login() {
        return cc.login();
    }

    public void logout() {
        cc.logout();
    }

    public void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback callback) {
        cc.openFile(appName, instanceIndex, filePath, callback);
    }

    public void register(String email, String password) {
        cc.register(email, password);
    }

    public void registerRestLogListener(RestLogCallback callBack) {
        cc.registerRestLogListener(callBack);
    }

    public void removeDomain(String domainName) {
        cc.removeDomain(domainName);
    }

    public void rename(String appName, String newName) {
        cc.rename(appName, newName);
    }

    public StartingInfo restartApplication(String appName) {
        return cc.restartApplication(appName);
    }

    public void setQuotaToOrg(String orgName, String quotaName) {
        cc.setQuotaToOrg(orgName, quotaName);
    }

    public void setResponseErrorHandler(ResponseErrorHandler errorHandler) {
        cc.setResponseErrorHandler(errorHandler);
    }

    public StartingInfo startApplication(String appName) {
        return cc.startApplication(appName);
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    public void stopApplication(String appName) {
        cc.stopApplication(appName);
Solution content
 */
public class CloudFoundryClient implements CloudFoundryOperations {

    private CloudControllerClient cc;

    private CloudInfo info;

    /**
     * Construct client for anonymous user. Useful only to get to the '/info' endpoint.
     */

    public CloudFoundryClient(URL cloudControllerUrl) {
        this(null, cloudControllerUrl, null, (HttpProxyConfiguration) null, false);
    }

    public CloudFoundryClient(URL cloudControllerUrl, boolean trustSelfSignedCerts) {
        this(null, cloudControllerUrl, null, (HttpProxyConfiguration) null, trustSelfSignedCerts);
    }

    public CloudFoundryClient(URL cloudControllerUrl, HttpProxyConfiguration httpProxyConfiguration) {
        this(null, cloudControllerUrl, null, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(URL cloudControllerUrl, HttpProxyConfiguration httpProxyConfiguration,
                              boolean trustSelfSignedCerts) {
        this(null, cloudControllerUrl, null, httpProxyConfiguration, trustSelfSignedCerts);
    }

    /**
     * Construct client without a default org and space.
     */

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl) {
        this(credentials, cloudControllerUrl, null, (HttpProxyConfiguration) null, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
                              boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, null, (HttpProxyConfiguration) null, trustSelfSignedCerts);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
                              HttpProxyConfiguration httpProxyConfiguration) {
        this(credentials, cloudControllerUrl, null, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl,
                              HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, null, httpProxyConfiguration, trustSelfSignedCerts);
    }

    /**
     * Construct a client with a default CloudSpace.
     */

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace) {
        this(credentials, cloudControllerUrl, sessionSpace, null, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
                              boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, sessionSpace, null, trustSelfSignedCerts);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
                              HttpProxyConfiguration httpProxyConfiguration) {
        this(credentials, cloudControllerUrl, sessionSpace, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, CloudSpace sessionSpace,
                              HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
        Assert.notNull(cloudControllerUrl, "URL for cloud controller cannot be null");
        CloudControllerClientFactory cloudControllerClientFactory =
                new CloudControllerClientFactory(httpProxyConfiguration, trustSelfSignedCerts);
        this.cc = cloudControllerClientFactory.newCloudController(cloudControllerUrl, credentials, sessionSpace);
    }

    /**
     * Construct a client with a default space name and org name.
     */

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName) {
        this(credentials, cloudControllerUrl, orgName, spaceName, null, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
                              boolean trustSelfSignedCerts) {
        this(credentials, cloudControllerUrl, orgName, spaceName, null, trustSelfSignedCerts);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
                              HttpProxyConfiguration httpProxyConfiguration) {
        this(credentials, cloudControllerUrl, orgName, spaceName, httpProxyConfiguration, false);
    }

    public CloudFoundryClient(CloudCredentials credentials, URL cloudControllerUrl, String orgName, String spaceName,
                              HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
        Assert.notNull(cloudControllerUrl, "URL for cloud controller cannot be null");
        CloudControllerClientFactory cloudControllerClientFactory =
                new CloudControllerClientFactory(httpProxyConfiguration, trustSelfSignedCerts);
        this.cc = cloudControllerClientFactory.newCloudController(cloudControllerUrl, credentials, orgName, spaceName);
    }

    /**
     * Construct a client with a pre-configured CloudControllerClient
     */
    public CloudFoundryClient(CloudControllerClient cc) {
        this.cc = cc;
    }

    public void addDomain(String domainName) {
        cc.addDomain(domainName);
    }

    public void addRoute(String host, String domainName) {
        cc.addRoute(host, domainName);
    }

    @Override
    public void associateAuditorWithSpace(String spaceName) {
        cc.associateAuditorWithSpace(null, spaceName, null);
    }

    @Override
    public void associateAuditorWithSpace(String orgName, String spaceName) {
        cc.associateAuditorWithSpace(orgName, spaceName, null);
    }

    @Override
    public void associateAuditorWithSpace(String orgName, String spaceName, String userGuid) {
        cc.associateAuditorWithSpace(orgName, spaceName, userGuid);
    }

    @Override
    public void associateDeveloperWithSpace(String spaceName) {
        cc.associateDeveloperWithSpace(null, spaceName, null);
    }

    @Override
    public void associateDeveloperWithSpace(String orgName, String spaceName) {
        cc.associateDeveloperWithSpace(orgName, spaceName, null);
    }

    @Override
    public void associateDeveloperWithSpace(String orgName, String spaceName, String userGuid) {
        cc.associateDeveloperWithSpace(orgName, spaceName, userGuid);
    }

    @Override
    public void associateManagerWithSpace(String spaceName) {
        cc.associateManagerWithSpace(null, spaceName, null);
    }

    @Override
    public void associateManagerWithSpace(String orgName, String spaceName) {
    }
        cc.associateManagerWithSpace(orgName, spaceName, null);
    }

    @Override
    public void associateManagerWithSpace(String orgName, String spaceName, String userGuid) {
        cc.associateManagerWithSpace(orgName, spaceName, userGuid);
    }

    @Override
    public void bindRunningSecurityGroup(String securityGroupName) {
        cc.bindRunningSecurityGroup(securityGroupName);
    }

    @Override
    public void bindSecurityGroup(String orgName, String spaceName, String securityGroupName) {
        cc.bindSecurityGroup(orgName, spaceName, securityGroupName);
    }

    public void bindService(String appName, String serviceName) {
        cc.bindService(appName, serviceName);
    }

    @Override
    public void bindStagingSecurityGroup(String securityGroupName) {
        cc.bindStagingSecurityGroup(securityGroupName);
    }

    public void createApplication(String appName, Staging staging, Integer memory, List uris,
                                  List serviceNames) {
        cc.createApplication(appName, staging, memory, uris, serviceNames);
    }

    public void createApplication(String appName, Staging staging, Integer disk, Integer memory, List uris,
                                  List serviceNames) {
        cc.createApplication(appName, staging, disk, memory, uris, serviceNames);
    }

    public void createQuota(CloudQuota quota) {
        cc.createQuota(quota);
    }

    @Override
    public void createSecurityGroup(CloudSecurityGroup securityGroup) {
        cc.createSecurityGroup(securityGroup);
    }

    @Override
    public void createSecurityGroup(String name, InputStream jsonRulesFile) {
        cc.createSecurityGroup(name, jsonRulesFile);
    }

    public void createService(CloudService service) {
        cc.createService(service);
    }

    public void createServiceBroker(CloudServiceBroker serviceBroker) {
        cc.createServiceBroker(serviceBroker);
    }

    @Override
    public void createSpace(String spaceName) {
        cc.createSpace(spaceName);
    }

    public void createUserProvidedService(CloudService service, Map credentials) {
        cc.createUserProvidedService(service, credentials);
    }

    public void createUserProvidedService(CloudService service, Map credentials, String
            syslogDrainUrl) {
        cc.createUserProvidedService(service, credentials, syslogDrainUrl);
    }

    public void debugApplication(String appName, DebugMode mode) {
        cc.debugApplication(appName, mode);
    }

    public void deleteAllApplications() {
        cc.deleteAllApplications();
    }

    public void deleteAllServices() {
        cc.deleteAllServices();
    }

    public void deleteApplication(String appName) {
        cc.deleteApplication(appName);
    }

    public void deleteDomain(String domainName) {
        cc.deleteDomain(domainName);
    }

    @Override
    public List deleteOrphanedRoutes() {
        return cc.deleteOrphanedRoutes();
    }

    public void deleteQuota(String quotaName) {
        cc.deleteQuota(quotaName);
    }

    public void deleteRoute(String host, String domainName) {
        cc.deleteRoute(host, domainName);

    @Override
    public void deleteSecurityGroup(String securityGroupName) {
        cc.deleteSecurityGroup(securityGroupName);
    }

    public void deleteService(String service) {
        cc.deleteService(service);
    }

    @Override
    public void deleteServiceBroker(String name) {
        cc.deleteServiceBroker(name);
    }

    @Override
    public void deleteSpace(String spaceName) {
        cc.deleteSpace(spaceName);
    }

    public CloudApplication getApplication(String appName) {
        return cc.getApplication(appName);
    }

    public CloudApplication getApplication(UUID appGuid) {
        return cc.getApplication(appGuid);
    }

    public Map getApplicationEnvironment(UUID appGuid) {
        return cc.getApplicationEnvironment(appGuid);
    }

    public Map getApplicationEnvironment(String appName) {
        return cc.getApplicationEnvironment(appName);
    }

    public List getApplicationEvents(String appName) {
        return cc.getApplicationEvents(appName);
    }

    public InstancesInfo getApplicationInstances(String appName) {
        return cc.getApplicationInstances(appName);
    }

    public InstancesInfo getApplicationInstances(CloudApplication app) {
        return cc.getApplicationInstances(app);
    }

    public ApplicationStats getApplicationStats(String appName) {
        return cc.getApplicationStats(appName);
    }

    public List getApplications() {
        return cc.getApplications();
    }

    public URL getCloudControllerUrl() {
        return cc.getCloudControllerUrl();
    }

    public CloudInfo getCloudInfo() {
        if (info == null) {
            info = cc.getInfo();
        }
        return info;
    }

    /**
     * @deprecated use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
     */
    public Map getCrashLogs(String appName) {
        return cc.getCrashLogs(appName);
    }

    public CrashesInfo getCrashes(String appName) {
        return cc.getCrashes(appName);
    }

    public CloudDomain getDefaultDomain() {
        return cc.getDefaultDomain();
    }

    public List getDomains() {
        return cc.getDomains();
    }

    public List getDomainsForOrg() {
        return cc.getDomainsForOrg();
    }

    public List getEvents() {
        return cc.getEvents();
    }

    public String getFile(String appName, int instanceIndex, String filePath) {
        return cc.getFile(appName, instanceIndex, filePath, 0, -1);
    }

    public String getFile(String appName, int instanceIndex, String filePath, int startPosition) {
        Assert.isTrue(startPosition >= 0,
                startPosition + " is not a valid value for start position, it should be 0 or greater.");
        return cc.getFile(appName, instanceIndex, filePath, startPosition, -1);
    }

    public String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition) {
        Assert.isTrue(startPosition >= 0,
                startPosition + " is not a valid value for start position, it should be 0 or greater.");
        Assert.isTrue(endPosition > startPosition,
                endPosition + " is not a valid value for end position, it should be greater than startPosition " +
                        "which is " + startPosition + ".");
        return cc.getFile(appName, instanceIndex, filePath, startPosition, endPosition - 1);
    }

    // list services, un/provision services, modify instance

    public String getFileTail(String appName, int instanceIndex, String filePath, int length) {
        Assert.isTrue(length > 0, length + " is not a valid value for length, it should be 1 or greater.");
        return cc.getFile(appName, instanceIndex, filePath, -1, length);
    }

    /**
     * @deprecated use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
     */
    public Map getLogs(String appName) {
        return cc.getLogs(appName);
    }

    public CloudOrganization getOrgByName(String orgName, boolean required) {
        return cc.getOrgByName(orgName, required);
    }

    @Override
    public Map getOrganizationUsers(String orgName) {
        return cc.getOrganizationUsers(orgName);
    }

    public List getOrganizations() {
        return cc.getOrganizations();
    }

    public List getPrivateDomains() {
        return cc.getPrivateDomains();
    }

    public CloudQuota getQuotaByName(String quotaName, boolean required) {
        return cc.getQuotaByName(quotaName, required);
    }

    public List getQuotas() {
        return cc.getQuotas();
    }

    public List getRecentLogs(String appName) {
        return cc.getRecentLogs(appName);
    }

    public List getRoutes(String domainName) {
        return cc.getRoutes(domainName);
    }

    @Override
    public List getRunningSecurityGroups() {
        return cc.getRunningSecurityGroups();
    }

    @Override
    public CloudSecurityGroup getSecurityGroup(String securityGroupName) {
        return cc.getSecurityGroup(securityGroupName);
    }

    @Override
    public List getSecurityGroups() {
        return cc.getSecurityGroups();
    }

    public CloudService getService(String service) {
        return cc.getService(service);
    }

    public CloudServiceBroker getServiceBroker(String name) {
        return cc.getServiceBroker(name);
    }

    public List getServiceBrokers() {
        return cc.getServiceBrokers();
    }

    public CloudServiceInstance getServiceInstance(String service) {
        return cc.getServiceInstance(service);
    }

    public List getServiceOfferings() {
        return cc.getServiceOfferings();
    }

    public List getServices() {
        return cc.getServices();
    }

    public List getSharedDomains() {
        return cc.getSharedDomains();
    }

    @Override
    public CloudSpace getSpace(String spaceName) {
        return cc.getSpace(spaceName);
    }

    @Override
    public List getSpaceAuditors(String spaceName) {
        return cc.getSpaceAuditors(null, spaceName);
    }

    @Override
    public List getSpaceAuditors(String orgName, String spaceName) {
        return cc.getSpaceAuditors(orgName, spaceName);
    }

    @Override
    public List getSpaceDevelopers(String spaceName) {
        return cc.getSpaceDevelopers(null, spaceName);
    }

    @Override
    public List getSpaceDevelopers(String orgName, String spaceName) {
        return cc.getSpaceDevelopers(orgName, spaceName);
    }

    @Override
    public List getSpaceManagers(String spaceName) {
        return cc.getSpaceManagers(null, spaceName);
    }

    @Override
    public List getSpaceManagers(String orgName, String spaceName) {
        return cc.getSpaceManagers(orgName, spaceName);
    }

    public List getSpaces() {
        return cc.getSpaces();
    }

    @Override
    public List getSpacesBoundToSecurityGroup(String securityGroupName) {
        return cc.getSpacesBoundToSecurityGroup(securityGroupName);
    }

    public CloudStack getStack(String name) {
        return cc.getStack(name);
    }

    public List getStacks() {
        return cc.getStacks();
    }

    public String getStagingLogs(StartingInfo info, int offset) {
        return cc.getStagingLogs(info, offset);
    }

    @Override
    public List getStagingSecurityGroups() {
        return cc.getStagingSecurityGroups();
    }

    public OAuth2AccessToken login() {
        return cc.login();
    }

    public void logout() {
        cc.logout();
    }

    public void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback callback) {
        cc.openFile(appName, instanceIndex, filePath, callback);
    }

    public void register(String email, String password) {
        cc.register(email, password);
    }

    public void registerRestLogListener(RestLogCallback callBack) {
        cc.registerRestLogListener(callBack);
    }

    public void removeDomain(String domainName) {
        cc.removeDomain(domainName);
    }

    public void rename(String appName, String newName) {
        cc.rename(appName, newName);
    }

    public StartingInfo restartApplication(String appName) {
        return cc.restartApplication(appName);
    }

    public void setQuotaToOrg(String orgName, String quotaName) {
        cc.setQuotaToOrg(orgName, quotaName);
    }

    public void setResponseErrorHandler(ResponseErrorHandler errorHandler) {
        cc.setResponseErrorHandler(errorHandler);
    }

    public StartingInfo startApplication(String appName) {
        return cc.startApplication(appName);
    }

    public void stopApplication(String appName) {
        cc.stopApplication(appName);
File
CloudFoundryClient.java
Developer's decision
Manual
Kind of conflict
Annotation
Attribute
Comment
Method declaration
Chunk
Conflicting content
        cc.updateApplicationMemory(appName, memory);
    }

<<<<<<< HEAD
	public CrashesInfo getCrashes(String appName) {
		return cc.getCrashes(appName);
	}

	public List getStacks() {
		return cc.getStacks();
	}

	public CloudStack getStack(String name) {
		return cc.getStack(name);
	}

	public void rename(String appName, String newName) {
		cc.rename(appName, newName);
	}

	public List getDomainsForOrg() {
		return cc.getDomainsForOrg();
	}

	public List getPrivateDomains() {
		return cc.getPrivateDomains();
	}

	public List getSharedDomains() {
		return cc.getSharedDomains();
	}

	public List getDomains() {
		return cc.getDomains();
	}

	public CloudDomain getDefaultDomain() {
		return cc.getDefaultDomain();
	}

	public void addDomain(String domainName) {
		cc.addDomain(domainName);
	}

	public void deleteDomain(String domainName) {
		cc.deleteDomain(domainName);
	}

	public void removeDomain(String domainName) {
		cc.removeDomain(domainName);
	}

	public List getRoutes(String domainName) {
		return cc.getRoutes(domainName);
	}

	public void addRoute(String host, String domainName) {
		cc.addRoute(host, domainName);
	}

	public void deleteRoute(String host, String domainName) {
		cc.deleteRoute(host, domainName);
	}

	public void registerRestLogListener(RestLogCallback callBack) {
		cc.registerRestLogListener(callBack);
	}

	public void unRegisterRestLogListener(RestLogCallback callBack) {
		cc.unRegisterRestLogListener(callBack);
	}

	public CloudOrganization getOrgByName(String orgName, boolean required){
    	return cc.getOrgByName(orgName, required);
    }

	public List getQuotas() {
		return cc.getQuotas();
	}

	public CloudQuota getQuotaByName(String quotaName, boolean required) {
		return cc.getQuotaByName(quotaName, required);
	}

	public void setQuotaToOrg(String orgName, String quotaName) {
		cc.setQuotaToOrg(orgName, quotaName);
	}

	public void createQuota(CloudQuota quota) {
		cc.createQuota(quota);
	}

	public void deleteQuota(String quotaName) {
		cc.deleteQuota(quotaName);
	}

	public void updateQuota(CloudQuota quota, String name) {
		cc.updateQuota(quota, name);
	}
	@Override
	public void createSpace(String spaceName) {
		cc.createSpace(spaceName);
	}

	@Override
	public void deleteSpace(String spaceName) {
		cc.deleteSpace(spaceName);
	}


	@Override
	public CloudSpace getSpace(String spaceName) {
		return cc.getSpace(spaceName);
	}


	@Override
	public List getSpaceManagers(String spaceName) {
		return cc.getSpaceManagers(null, spaceName);
	}

	@Override
	public List getSpaceDevelopers(String spaceName) {
		return cc.getSpaceDevelopers(null, spaceName);
	}

	@Override
	public List getSpaceAuditors(String spaceName) {
		return cc.getSpaceAuditors(null, spaceName);
	}

	@Override
	public List getSpaceManagers(String orgName, String spaceName) {
		return cc.getSpaceManagers(orgName, spaceName);
	}

	@Override
	public List getSpaceDevelopers(String orgName, String spaceName) {
		return cc.getSpaceDevelopers(orgName, spaceName);
	}

	@Override
	public List getSpaceAuditors(String orgName, String spaceName) {
		return cc.getSpaceAuditors(orgName, spaceName);
	}

	@Override
	public void associateManagerWithSpace(String spaceName) {
		cc.associateManagerWithSpace(null, spaceName, null);
	}

	@Override
	public void associateDeveloperWithSpace(String spaceName) {
		cc.associateDeveloperWithSpace(null, spaceName, null);
	}

	@Override
	public void associateAuditorWithSpace(String spaceName) {
		cc.associateAuditorWithSpace(null, spaceName, null);
	}

	@Override
	public void associateManagerWithSpace(String orgName, String spaceName) {
		cc.associateManagerWithSpace(orgName, spaceName, null);
	}

	@Override
	public void associateDeveloperWithSpace(String orgName, String spaceName) {
		cc.associateDeveloperWithSpace(orgName, spaceName, null);
	}

	@Override
	public void associateAuditorWithSpace(String orgName, String spaceName) {
		cc.associateAuditorWithSpace(orgName, spaceName, null);
	}

	@Override
	public void associateManagerWithSpace(String orgName, String spaceName, String userGuid) {
		cc.associateManagerWithSpace(orgName, spaceName, userGuid);
	}

	@Override
	public void associateDeveloperWithSpace(String orgName, String spaceName, String userGuid) {
		cc.associateDeveloperWithSpace(orgName, spaceName, userGuid);
	}

	@Override
	public void associateAuditorWithSpace(String orgName, String spaceName, String userGuid) {
		cc.associateAuditorWithSpace(orgName, spaceName, userGuid);
	}

	@Override
	public List getSecurityGroups() {
		return cc.getSecurityGroups();
	}

	@Override
	public CloudSecurityGroup getSecurityGroup(String securityGroupName) {
		return cc.getSecurityGroup(securityGroupName);
	}

	@Override
	public void createSecurityGroup(CloudSecurityGroup securityGroup){
		cc.createSecurityGroup(securityGroup);
	}

	@Override
	public void createSecurityGroup(String name, InputStream jsonRulesFile) {
		cc.createSecurityGroup(name, jsonRulesFile);
	}

	@Override
	public void updateSecurityGroup(CloudSecurityGroup securityGroup) {
		cc.updateSecurityGroup(securityGroup);
	}

	@Override
	public void updateSecurityGroup(String name, InputStream jsonRulesFile) {
		cc.updateSecurityGroup(name, jsonRulesFile);
	}

	@Override
	public void deleteSecurityGroup(String securityGroupName) {
		cc.deleteSecurityGroup(securityGroupName);
	}

	@Override
	public List getStagingSecurityGroups() {
		return cc.getStagingSecurityGroups();
	}

	@Override
	public void bindStagingSecurityGroup(String securityGroupName) {
		cc.bindStagingSecurityGroup(securityGroupName);
	}

	@Override
	public void unbindStagingSecurityGroup(String securityGroupName) {
		cc.unbindStagingSecurityGroup(securityGroupName);
	}

	@Override
	public List getRunningSecurityGroups() {
		return cc.getRunningSecurityGroups();
	}

	@Override
	public void bindRunningSecurityGroup(String securityGroupName) {
		cc.bindRunningSecurityGroup(securityGroupName);
	}

	@Override
	public void unbindRunningSecurityGroup(String securityGroupName) {
		cc.unbindRunningSecurityGroup(securityGroupName);
	}

	@Override
	public void bindSecurityGroup(String orgName, String spaceName, String securityGroupName) {
		cc.bindSecurityGroup(orgName, spaceName, securityGroupName);
	}

	@Override
	public void unbindSecurityGroup(String orgName, String spaceName, String securityGroupName) {
		cc.unbindSecurityGroup(orgName, spaceName, securityGroupName);
	}

	@Override
	public Map getOrganizationUsers(String orgName) {
		return cc.getOrganizationUsers(orgName);
	}

	@Override
	public List getSpacesBoundToSecurityGroup(String securityGroupName) {
		return cc.getSpacesBoundToSecurityGroup(securityGroupName);
	}
=======
    public void updateApplicationServices(String appName, List services) {
        cc.updateApplicationServices(appName, services);
    }

    public void updateApplicationStaging(String appName, Staging staging) {
        cc.updateApplicationStaging(appName, staging);
    }

    public void updateApplicationUris(String appName, List uris) {
        cc.updateApplicationUris(appName, uris);
    }

    public void updatePassword(String newPassword) {
        cc.updatePassword(newPassword);
    }

    public void updatePassword(CloudCredentials credentials, String newPassword) {
        cc.updatePassword(credentials, newPassword);
    }

    public void updateQuota(CloudQuota quota, String name) {
        cc.updateQuota(quota, name);
    }

    public void updateServiceBroker(CloudServiceBroker serviceBroker) {
        cc.updateServiceBroker(serviceBroker);
    }

    @Override
    public void updateServicePlanVisibilityForBroker(String name, boolean visibility) {
        cc.updateServicePlanVisibilityForBroker(name, visibility);
    }

    public void uploadApplication(String appName, String file) throws IOException {
        cc.uploadApplication(appName, new File(file), null);
    }

    public void uploadApplication(String appName, File file) throws IOException {
        cc.uploadApplication(appName, file, null);
    }

    public void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException {
        cc.uploadApplication(appName, file, callback);
    }

    public void uploadApplication(String appName, String fileName, InputStream inputStream) throws IOException {
        cc.uploadApplication(appName, fileName, inputStream, null);
    }

    public void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback
            callback) throws IOException {
        cc.uploadApplication(appName, fileName, inputStream, callback);
    }

    public void uploadApplication(String appName, ApplicationArchive archive) throws IOException {
        cc.uploadApplication(appName, archive, null);
    }

    public void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws
            IOException {
        cc.uploadApplication(appName, archive, callback);
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
        cc.updateApplicationMemory(appName, memory);
    }

    public void updateApplicationServices(String appName, List services) {
        cc.updateApplicationServices(appName, services);
    }

    public void updateApplicationStaging(String appName, Staging staging) {
        cc.updateApplicationStaging(appName, staging);
    }

    public void updateApplicationUris(String appName, List uris) {
        cc.updateApplicationUris(appName, uris);
    }

    public void updatePassword(String newPassword) {
        cc.updatePassword(newPassword);
    }

    public void updatePassword(CloudCredentials credentials, String newPassword) {
        cc.updatePassword(credentials, newPassword);
    }

    public void updateQuota(CloudQuota quota, String name) {
        cc.updateQuota(quota, name);
    }

    @Override
    public void updateSecurityGroup(CloudSecurityGroup securityGroup) {
        cc.updateSecurityGroup(securityGroup);
    }

    @Override
    public void updateSecurityGroup(String name, InputStream jsonRulesFile) {
        cc.updateSecurityGroup(name, jsonRulesFile);
    }

    public void updateServiceBroker(CloudServiceBroker serviceBroker) {
        cc.updateServiceBroker(serviceBroker);
    }

    @Override
    public void updateServicePlanVisibilityForBroker(String name, boolean visibility) {
        cc.updateServicePlanVisibilityForBroker(name, visibility);
    }

    public void uploadApplication(String appName, String file) throws IOException {
        cc.uploadApplication(appName, new File(file), null);
    }

    public void uploadApplication(String appName, File file) throws IOException {
        cc.uploadApplication(appName, file, null);
    }

    public void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException {
        cc.uploadApplication(appName, file, callback);
    }

    public void uploadApplication(String appName, String fileName, InputStream inputStream) throws IOException {
        cc.uploadApplication(appName, fileName, inputStream, null);
    }

    public void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback
            callback) throws IOException {
        cc.uploadApplication(appName, fileName, inputStream, callback);
    }

    public void uploadApplication(String appName, ApplicationArchive archive) throws IOException {
        cc.uploadApplication(appName, archive, null);
    }

    public void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws
            IOException {
        cc.uploadApplication(appName, archive, callback);
    }
}
File
CloudFoundryClient.java
Developer's decision
Combination
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
package org.cloudfoundry.client.lib;

<<<<<<< HEAD
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.UUID;

=======
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
import org.cloudfoundry.client.lib.archive.ApplicationArchive;
import org.cloudfoundry.client.lib.domain.ApplicationLog;
import org.cloudfoundry.client.lib.domain.ApplicationStats;
Solution content
package org.cloudfoundry.client.lib;

import org.cloudfoundry.client.lib.archive.ApplicationArchive;
import org.cloudfoundry.client.lib.domain.ApplicationLog;
import org.cloudfoundry.client.lib.domain.ApplicationStats;
File
CloudFoundryOperations.java
Developer's decision
Version 2
Kind of conflict
Import
Chunk
Conflicting content
	/**
 */
public interface CloudFoundryOperations {

<<<<<<< HEAD
	/**
	 * Override the default REST response error handler with a custom error handler.
	 *
	 * @param errorHandler
	 */
	void setResponseErrorHandler(ResponseErrorHandler errorHandler);

	/**
	 * Get the URL used for the cloud controller.
	 *
	 * @return the cloud controller URL
	 */
	URL getCloudControllerUrl();

	/**
	 * Get CloudInfo for the current cloud.
	 *
	 * @return CloudInfo object containing the cloud info
	 */
	CloudInfo getCloudInfo();

	/**
	 * Get list of CloudSpaces for the current cloud.
	 *
	 * @return List of CloudSpace objects containing the space info
	 */
	List getSpaces();

	/**
	 * Get list of space manager UUID  for the space.
	 *
	 * @param spaceName name of the space
	 * @return List of space manager UUID
	 */
	List getSpaceManagers(String spaceName);

	/**
	 * Get list of space developer UUID  for the space.
	 *
	 * @param spaceName name of the space
	 * @return List of space developer UUID
	 */
	List getSpaceDevelopers(String spaceName);

	/**
	 * Get list of space auditor UUID  for the space.
	 *
	 * @param spaceName name of the space
	 * @return List of space auditor UUID
	 */
	List getSpaceAuditors(String spaceName);

	/**
	 * Get list of space manager UUID  for the space.
	 *
	 * @param orgName name of the organization containing the space
	 * @param spaceName name of the space
	 * @return List of space manager UUID
	 */
	List getSpaceManagers(String orgName, String spaceName);

	/**
	 * Get list of space developer UUID  for the space.
	 *
	 * @param orgName name of the organization containing the space
	 * @param spaceName name of the space
	 * @return List of space developer UUID
	 */
	List getSpaceDevelopers(String orgName, String spaceName);

	/**
	 * Get list of space auditor UUID  for the space.
	 *
	 * @param orgName name of the organization containing the space
	 * @param spaceName name of the space
	 * @return List of space auditor UUID
	 */
	List getSpaceAuditors(String orgName, String spaceName);

	/**
	 * Associate current user to the space auditors role
	 *
	 * @param spaceName name of the space
	 */
	void associateAuditorWithSpace(String spaceName);

	/**
	 * Associate current user to the space developer role
	 *
	 * @param spaceName name of the space
	 */
	void associateDeveloperWithSpace(String spaceName);

	/**
	 * Associate current user to the space managers role
	 *
	 * @param spaceName name of the space
	 */
	void associateManagerWithSpace(String spaceName);

	/**
	 * Associate current user to the space auditors role
	 *
	 * @param orgName name of the organization containing the space
	 * @param spaceName name of the space
	 */
	void associateAuditorWithSpace(String orgName, String spaceName);

	/**
	 * Associate current user to the space developer role
	 *
	 * @param orgName name of the organization containing the space
	 * @param spaceName name of the space
	 */
	void associateDeveloperWithSpace(String orgName, String spaceName);

	/**
	 * Associate current user to the space managers role
	 *
	 * @param orgName name of the organization containing the space
	 * @param spaceName name of the space
	 */
	void associateManagerWithSpace(String orgName, String spaceName);

	/**
	 * Associate a user to the space auditors role
	 *
	 * @param orgName   name of the organization containing the space
	 * @param spaceName name of the space
	 * @param userGuid  guid of the user. If null, use current user. To retrieve user guid, use {@link #getOrganizationUsers(String) getOrganizationUsers } and search for username
	 */
	void associateAuditorWithSpace(String orgName, String spaceName, String userGuid);

	/**
	 * Associate a user to the space developer role
	 *
	 * @param orgName   name of the organization containing the space
	 * @param spaceName name of the space
	 * @param userGuid  guid of the user. If null, use current user. To retrieve user guid, use {@link #getOrganizationUsers(String) getOrganizationUsers } and search for username
	 */
	void associateDeveloperWithSpace(String orgName, String spaceName, String userGuid);

	/**
	 * Associate a user to the space managers role
	 *
	 * @param orgName   name of the organization containing the space
	 * @param spaceName name of the space
	 * @param userGuid  guid of the user. If null, use current user. To retrieve user guid, use {@link #getOrganizationUsers(String) getOrganizationUsers } and search for username
	 */
	void associateManagerWithSpace(String orgName, String spaceName, String userGuid);

	/**
	 * Create a space with the specified name
	 * @param spaceName
	 */
	void createSpace(String spaceName);

	/**
	 * Get space name with the specified name.
	 *
	 * @param spaceName name of the space
	 * @return the cloud space
	 */
	CloudSpace getSpace(String spaceName);

	/**
	 * Delete a space with the specified name
	 *
	 * @param spaceName name of the space
	 */
	void deleteSpace(String spaceName);

	/**
	 * Get list of CloudOrganizations for the current cloud.
	 *
	 * @return List of CloudOrganizations objects containing the organization info
	 */
	List getOrganizations();

	/**
	 * Get the organization with the specified name.
	 *
	 * @param orgName name of organization
	 * @param required if true, and organization is not found, throw an exception
	 * @return
	 */
	CloudOrganization getOrgByName(String orgName, boolean required);

	/**
	 * Register new user account with the provided credentials.
	 *
	 * @param email the email account
	 * @param password the password
	 */
	void register(String email, String password);

	/**
	 * Update the password for the logged in user.
	 *
	 * @param newPassword the new password
	 */
	void updatePassword(String newPassword);

	/**
	 * Update the password for the logged in user using
	 * the username/old_password provided in the credentials.
	 *
	 * @param credentials current credentials
	 * @param newPassword the new password
	 */
	void updatePassword(CloudCredentials credentials, String newPassword);

	/**
	 * Unregister and log out the currently logged in user
	 */
	void unregister();

	/**
	 * Login using the credentials already set for the client.
	 *
	 * @return authentication token
	 */
	OAuth2AccessToken login();

	/**
	 * Logout closing the current session.
	 */
	void logout();

	/**
	 * Get all cloud applications.
	 *
	 * @return list of cloud applications
	 */
	List getApplications();

	/**
	 * Get cloud application with the specified name.
	 *
	 * @param appName name of the app
	 * @return the cloud application
	 */
	CloudApplication getApplication(String appName);

	/**
	 * Get cloud application with the specified GUID.
	 *
	 * @param guid GUID of the app
	 * @return the cloud application
	 */
	CloudApplication getApplication(UUID guid);

	/**
	 * Get application stats for the app with the specified name.
	 *
	 * @param appName name of the app
	 * @return the cloud application stats
	 */
	ApplicationStats getApplicationStats(String appName);

	/**
	 * Get application environment variables for the app with the specified name.
	 *
	 * @param appName name of the app
	 * @return the cloud application environment variables
	 */
	Map getApplicationEnvironment(String appName);

	/**
	 * Get application environment variables for the app with the specified GUID.
	 *
	 * @param appGuid GUID of the app
	 * @return the cloud application environment variables
	 */
	Map getApplicationEnvironment(UUID appGuid);

	/**
	 * Create application.
	 *
	 * @param appName application name
	 * @param staging staging info
	 * @param memory memory to use in MB
	 * @param uris list of URIs for the app
	 * @param serviceNames list of service names to bind to app
	 */
	void createApplication(String appName, Staging staging, Integer memory, List uris,
                           List serviceNames);

	/**
	 * Create application.
	 *
	 * @param appName      application name
	 * @param staging      staging info
	 * @param disk         disk quota to use in MB
	 * @param memory       memory to use in MB
	 * @param uris         list of URIs for the app
	 * @param serviceNames list of service names to bind to app
	 */
	public void createApplication(String appName, Staging staging, Integer disk, Integer memory, List uris,
	                              List serviceNames);

	/**
	 * Create a service.
	 *
	 * @param service cloud service info
	 */
	void createService(CloudService service);

	/**
	 * Create a user-provided service.
	 *
	 * @param service cloud service info
	 * @param credentials the user-provided service credentials
	 */
	void createUserProvidedService(CloudService service, Map credentials);

	/**
	 * Create a user-provided service for logging.
	 *
	 * @param service cloud service info
	 * @param credentials the user-provided service credentials
	 * @param syslogDrainUrl for a logging service
	 */
	void createUserProvidedService(CloudService service, Map credentials, String syslogDrainUrl);

	/**
	 * Delete routes that do not have any application which is assigned to them.
	 */
	List deleteOrphanedRoutes();

	/**
	 * Upload an application to Cloud Foundry.
	 *
	 * @param appName application name
	 * @param file path to the application archive or folder
	 * @throws java.io.IOException
	 */
	void uploadApplication(String appName, String file) throws IOException;

	/**
	 * Upload an application to Cloud Foundry.
	 *
	 * @param appName the application name
	 * @param file the application archive or folder
	 * @throws java.io.IOException
	 */
	void uploadApplication(String appName, File file) throws IOException;

	/**
	 * Upload an application to Cloud Foundry.
	 *
	 * @param appName the application name
	 * @param file the application archive
	 * @param callback a callback interface used to provide progress information or null
	 * @throws java.io.IOException
	 */
	void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException;

	/**
	 * Upload an application to Cloud Foundry.
	 *
	 * This form of uploadApplication will read the passed InputStream and copy the contents to a
	 * temporary file for upload.
	 *
	 * @param appName the application name
	 * @param fileName the logical name of the application file
	 * @param inputStream the InputStream to read from
	 * @throws java.io.IOException
	 */
	void uploadApplication(String appName, String fileName, InputStream inputStream) throws IOException;

	/**
	 * Upload an application to Cloud Foundry.
	 *
	 * This form of uploadApplication will read the passed InputStream and copy the contents to a
	 * temporary file for upload.
	 *
	 * @param appName the application name
	 * @param fileName the logical name of the application file
	 * @param inputStream the InputStream to read from
	 * @param callback a callback interface used to provide progress information or null
	 * @throws java.io.IOException
	 */
	void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback callback) throws IOException;

	/**
	/**
	 * Upload an application to Cloud Foundry.
	 *
	 * @param appName the application name
	 * @param archive the application archive
	 * @throws java.io.IOException
	 */
	void uploadApplication(String appName, ApplicationArchive archive) throws IOException;

	/**
	 * Upload an application to Cloud Foundry.
	 *
	 * @param appName the application name
	 * @param archive the application archive
	 * @param callback a callback interface used to provide progress information or null
	 * @throws java.io.IOException
	 */
	void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws IOException;

	/**
	 * Start application. May return starting info if the response obtained after the start request contains headers.
	 * If the response does not contain headers, null is returned instead.
	 *
	 * @param appName
	 *            name of application
	 * @return Starting info containing response headers, if headers are present in the response. If there are no headers, return null.
	 */
	StartingInfo startApplication(String appName);

	/**
	 * Debug application.
	 *
	 * @param appName name of application
	 * @param mode debug mode info
	 */
	void debugApplication(String appName, CloudApplication.DebugMode mode);

	/**
	 * Stop application.
	 *
	 * @param appName name of application
	 */
	void stopApplication(String appName);

	/**
	 * Restart application.
	 *
	 * @param appName name of application
	 */
	StartingInfo restartApplication(String appName);

	/**
	 * Delete application.
	 *
	 * @param appName name of application
	 */
	void deleteApplication(String appName);

	/**
	 * Delete all applications.
	 */
	void deleteAllApplications();

	/**
	 * Delete all services.
	 */
	void deleteAllServices();

	/**
	 * Update application disk quota.
	 *
	 * @param appName name of application
	 * @param disk new disk setting in MB
	 */
	void updateApplicationDiskQuota(String appName, int disk);

	/**
	 * Update application memory.
	 *
	 * @param appName name of application
	 * @param memory new memory setting in MB
	 */
	void updateApplicationMemory(String appName, int memory);

	/**
	 * Update application instances.
	 *
	 * @param appName name of application
	 * @param instances number of instances to use
	 */
	void updateApplicationInstances(String appName, int instances);

	/**
	 * Update application services.
	 *
	 * @param appName name of appplication
	 * @param services list of services that should be bound to app
	 */
	void updateApplicationServices(String appName, List services);

	/**
	 * Update application staging information.
	 *
	 * @param appName name of appplication
	 * @param staging staging information for the app
	 */
	void updateApplicationStaging(String appName, Staging staging);

	/**
	 * Update application URIs.
	 *
	 * @param appName name of application
	 * @param uris list of URIs the app should use
	 */
	void updateApplicationUris(String appName, List uris);

	/**
	 * Update application env using a map where the key specifies the name of the environment variable
	 * and the value the value of the environment variable..
	 *
	 * @param appName name of application
	 * @param env map of environment settings
	 */
	void updateApplicationEnv(String appName, Map env);

	/**
	 * Update application env using a list of strings each with one environment setting.
	 *
	 * @param appName name of application
	 * @param env list of environment settings
	 */
	void updateApplicationEnv(String appName, List env);

	/**
	 * Get system events.
	 *
	 * @return all system events
	 */
	List getEvents();

	/**
	 * Get application events.
	 *
	 * @param appName name of application
	 * @return application events
	 */
	List getApplicationEvents(String appName);

	/**
	 * Get logs from the deployed application. The logs
	 * will be returned in a Map keyed by the path of the log file
	 * (logs/stderr.log, logs/stdout.log).
	 * @param appName name of the application
	 * @return a Map containing the logs. The logs will be returned with the path to the log file used as the key and
	 * the full content of the log file will be returned as a String value for the corresponding key.
	 * @deprecated Use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
	 */
	Map getLogs(String appName);

	/**
	 * Stream application logs produced after this method is called.
	 *
	 * This method has 'tail'-like behavior. Every time there is a new log entry,
	 * it notifies the listener.
	 *
	 * @param appName the name of the application
	 * @param listener listener object to be notified
	 * @return token than can be used to cancel listening for logs
	 */
	StreamingLogToken streamLogs(String appName, ApplicationLogListener listener);

	/**
	 * Stream recent log entries.
	 *
	 * Stream logs that were recently produced for an app.
	 *
	 * @param appName the name of the application
	 * @return the list of recent log entries
	 */
	List getRecentLogs(String appName);

	/**
	 * Get logs from most recent crash of the deployed application. The logs
	 * will be returned in a Map keyed by the path of the log file
	 * (logs/stderr.log, logs/stdout.log).
	 *
	 * @param appName name of the application
	 * @return a Map containing the logs. The logs will be returned with the path to the log file used as the key and
	 * the full content of the log file will be returned as a String value for the corresponding key.
	 * @deprecated Use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)}
	 */
	Map getCrashLogs(String appName);

	/**
	 * Get the staging log while an application is starting. A null
	 * value indicates that no further checks for staging logs should occur as
	 * staging logs are no longer available.
	 *
	 * @param info
	 *            starting information containing staging log file URL. Obtained
	 *            after starting an application.
	 * @param offset
	 *            starting position from where content should be retrieved.
	 * @return portion of the staging log content starting from the offset. It
	 *         may contain multiple lines. Returns null if no further content is
	 *         available.
	 */
	String getStagingLogs(StartingInfo info, int offset);


	 * Get the list of stacks available for staging applications.
	 *
	 * @return the list of available stacks
	 */
	List getStacks();

	/**
	 * Get a stack by name.
	 *
	 * @param name the name of the stack to get
	 * @return the stack, or null if not found
	 */
	CloudStack getStack(String name);

	/**
	 * Get file from the deployed application.
	 *
	 * @param appName name of the application
	 * @param instanceIndex instance index
	 * @param filePath path to the file
	 * @return the contents of the file
	 */
	String getFile(String appName, int instanceIndex, String filePath);

	/**
	 * Get a the content, starting at a specific position, of a file from the deployed application.
	 *
	 * @param appName name of the application
	 * @param instanceIndex instance index
	 * @param filePath path to the file
	 * @param startPosition the starting position of the file contents (inclusive)
	 * @return the contents of the file
	 */
	String getFile(String appName, int instanceIndex, String filePath, int startPosition);

	/**
	 * Get a range of content of a file from the deployed application. The range begins at the specified startPosition
	 * and extends to the character at endPosition - 1.
	 *
	 * @param appName name of the application
	 * @param instanceIndex instance index
	 * @param filePath path to the file
	 * @param startPosition the starting position of the file contents (inclusive)
	 * @param endPosition the ending position of the file contents (exclusive)
	 * @return the contents of the file
	 */
	String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition);

	/**
	 * Get a the last bytes, with length as specified, of content of a file from the deployed application.
	 *
	 * @param appName name of the application
	 * @param instanceIndex instance index
	 * @param filePath path to the file
	 * @param length the length of the file contents to retrieve
	 *
	 * @return the contents of the file
	 */
	String getFileTail(String appName, int instanceIndex, String filePath, int length);

	/**
	 * Provide the content of a file from the deployed application via callbacks.
	 *
	 * @param appName name of the application
	 * @param instanceIndex instance index
	 * @param filePath path to the file
	 * @param clientHttpResponseCallback callback object to receive file contents
	 */
	void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback clientHttpResponseCallback);

	/**
	 * Get list of cloud services.
	 *
	 * @return list of cloud services
	 */
	List getServices();

	/**
	 * Get cloud service.
	 *
	 * @param service name of service
	 * @return the cloud service info
	 */
	CloudService getService(String service);


	/**
	 * Get a service instance.
	 *
	 * @param service name of the service instance
	 * @return the service instance info
	 */
	CloudServiceInstance getServiceInstance(String service);

	/**
	 * Delete cloud service.
	 *
	 * @param service name of service
	 */
	void deleteService(String service);

	/**
	 * Get all service offerings.
	 *
	 * @return list of service offerings
	 */
	List getServiceOfferings();

	/**
	 * Get all service brokers.
	 *
	 * @return
	 */
	List getServiceBrokers();

	/**
	 * Get a service broker.
	 *
	 * @param name the service broker name
	 * @return the service broker
	 */
	CloudServiceBroker getServiceBroker(String name);

	/**
	 * Create a service broker.
	 *
	 * @param serviceBroker cloud service broker info
	 */
	void createServiceBroker(CloudServiceBroker serviceBroker);

	/**
	 * Update a service broker (unchanged forces catalog refresh).
	 *
	 * @param serviceBroker cloud service broker info
	 */
	void updateServiceBroker(CloudServiceBroker serviceBroker);

	/**
	 * Delete a service broker.
	 *
	 * @param name the service broker name
	 */
	void deleteServiceBroker(String name);


	/**
	 * Service plans are private by default when a service broker's catalog is
	 * fetched/updated. This method will update the visibility of all plans for
	 * a broker to either public or private.
	 *
	 * @param name       the service broker name
	 * @param visibility true for public, false for private
	 */
	void updateServicePlanVisibilityForBroker(String name, boolean visibility);

	/**
	 * Associate (provision) a service with an application.
	 *
	 * @param appName the application name
	 * @param serviceName the service name
	 */
	void bindService(String appName, String serviceName);

	/**
	 * Un-associate (unprovision) a service from an application.
	 * @param appName the application name
	 * @param serviceName the service name
	 */
	void unbindService(String appName, String serviceName);

	/**
	 * Get application instances info for application.
	 *
	 * @param appName name of application.
	 * @return instances info
	 */
	InstancesInfo getApplicationInstances(String appName);

	/**
	 * Get application instances info for application.
	 *
	 * @param app the application.
	 * @return instances info
	 */
	InstancesInfo getApplicationInstances(CloudApplication app);

	/**
	 * Get crashes info for application.
	 * @param appName name of application
	 * @return crashes info
	 */
	CrashesInfo getCrashes(String appName);

	/**
	 * Rename an application.
	 *
	 * @param appName the current name
	 * @param newName the new name
	 */
	void rename(String appName, String newName);

	/**
	 * Get list of all domain registered for the current organization.
	 *
	 * @return list of domains
	 */
	List getDomainsForOrg();

	/**
	 * Get list of all private domains.
	 *
	 * @return list of private domains
	 */
	List getPrivateDomains();

	/**
	 * Get list of all shared domains.
	 *
	 * @return list of shared domains
	 */
	List getSharedDomains();

	/**
	 * Get list of all domain shared and private domains.
	 *
	 * @return list of domains
	 */
	List getDomains();

	/**
	 * Gets the default domain for the current org, which is the first shared domain.
	 *
	 * @return the default domain
	 */
	CloudDomain getDefaultDomain();

	/**
	 * Add a private domain in the current organization.
	 *
	 * @param domainName the domain to add
	 */
	void addDomain(String domainName);

	/**
	 * Delete a private domain in the current organization.
	 *
	 * @param domainName the domain to remove
	 * @deprecated alias for {@link #deleteDomain}
	 */
	void removeDomain(String domainName);

	/**
	 * Delete a private domain in the current organization.
	 *
	 * @param domainName the domain to delete
	 */
	void deleteDomain(String domainName);

	/**
	 * Get the info for all routes for a domain.
	 *
	 * @param domainName the domain the routes belong to
	 * @return list of routes
	 */
	List getRoutes(String domainName);

	/**
	 * Register a new route to the a domain.
	 *
	 * @param host the host of the route to register
	 * @param domainName the domain of the route to register
	 */
	void addRoute(String host, String domainName);

	/**
	 * Delete a registered route from the space of the current session.
	 *
	 * @param host the host of the route to delete
	 * @param domainName the domain of the route to delete
	 */
	void deleteRoute(String host, String domainName);

	/**
	 * Register a new RestLogCallback
	 * @param callBack the callback to be registered
	 */
	void registerRestLogListener(RestLogCallback callBack);

	/**
	 * Un-register a RestLogCallback
	 *
	 * @param callBack the callback to be un-registered
	 */
	void unRegisterRestLogListener(RestLogCallback callBack);

	/**
	 * Get quota by name
	 *
	 * @param quotaName
	 * @param required
	 * @return CloudQuota instance
	 */
	CloudQuota getQuotaByName(String quotaName, boolean required);


	/**
	 * Set quota to organization
	 *
	 * @param orgName
	 * @param quotaName
	 */
	void setQuotaToOrg(String orgName, String quotaName);

	/**
	 * Create quota
	 *
	 * @param quota
	 */
	void createQuota(CloudQuota quota);

	/**
	 * Delete quota by name
	 *
	 * @param quotaName
	 */
	void deleteQuota(String quotaName);

	/**
	 * Get quota definitions
	 *
	 * @return List
	 */
	List getQuotas();

	/**
	 * Update Quota definition
	 *
	 * @param quota
	 * @param name
	 */
	void updateQuota(CloudQuota quota, String name);

	/**
	 * Get a List of all application security groups.
	 * 

* This method requires the logged in user to have admin permissions in the cloud controller. * * @return a list of all the {@link CloudSecurityGroup}s in the system */ List getSecurityGroups(); /** * Get a specific security group by name. *

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param securityGroupName The name of the security group * @return the CloudSecurityGroup or null if no security groups exist with the * given name */ CloudSecurityGroup getSecurityGroup(String securityGroupName); /** * Create a new CloudSecurityGroup. *

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param securityGroup */ void createSecurityGroup(CloudSecurityGroup securityGroup); /** * Create a new CloudSecurityGroup using a JSON rules file. This is equivalent to cf create-security-group SECURITY-GROUP PATH-TO-RULES-FILE * when using the cf command line. See the Application Security Group documentation for more details. *

* Example JSON-formatted rules file: *

	 * {@code
	 * [
	 *  {
	 * 		"protocol":"tcp",
	 * 		"destination":"10.0.11.0/24",
	 * 		"ports":"1-65535"
	 *  },
	 *  {
	 *  	"protocol":"udp",
	 *  	"destination":"10.0.11.0/24",
	 *  	"ports":"1-65535"
	 *  }
	 * ]
	 *  }
	 * 
*

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param name the name for the security group * @param jsonRulesFile An input stream that has a single array with JSON objects inside describing the rules * @see http://docs.cloudfoundry.org/adminguide/app-sec-groups.html */ void createSecurityGroup(String name, InputStream jsonRulesFile); /** * Update an existing security group. *

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param securityGroup * @throws IllegalArgumentException if a security group does not exist with the name of the given CloudSecurityGroup */ void updateSecurityGroup(CloudSecurityGroup securityGroup); /** * Updates a existing CloudSecurityGroup using a JSON rules file. This is equivalent to cf update-security-group SECURITY-GROUP PATH-TO-RULES-FILE * when using the cf command line. See the Application Security Group documentation for more details. *

* Example JSON-formatted rules file: *

	 * {@code
	 * [
	 *  {
	 * 		"protocol":"tcp",
	 * 		"destination":"10.0.11.0/24",
	 * 		"ports":"1-65535"
	 *  },
	 *  {
	 *  	"protocol":"udp",
	 *  	"destination":"10.0.11.0/24",
	 *  	"ports":"1-65535"
	 *  }
	 * ]
	 *  }
	 * 
*

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param jsonRulesFile An input stream that has a single array with JSON objects inside describing the rules * @throws IllegalArgumentException if a security group does not exist with the given name * @see http://docs.cloudfoundry.org/adminguide/app-sec-groups.html */ void updateSecurityGroup(String name, InputStream jsonRulesFile); * Deletes the security group with the given name. *

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param securityGroupName * @throws IllegalArgumentException if a security group does not exist with the given name */ void deleteSecurityGroup(String securityGroupName); /** * Lists security groups in the staging set for applications. *

* This method requires the logged in user to have admin permissions in the cloud controller. */ List getStagingSecurityGroups(); /** * Bind a security group to the list of security groups to be used for staging applications. *

* This method requires the logged in user to have admin permissions in the cloud controller. */ void bindStagingSecurityGroup(String securityGroupName); /** * Unbind a security group from the set of security groups for staging applications. *

* This method requires the logged in user to have admin permissions in the cloud controller. */ void unbindStagingSecurityGroup(String securityGroupName); /** * List security groups in the set of security groups for running applications. *

* This method requires the logged in user to have admin permissions in the cloud controller. */ List getRunningSecurityGroups(); /** * Bind a security group to the list of security groups to be used for running applications. *

* This method requires the logged in user to have admin permissions in the cloud controller. */ void bindRunningSecurityGroup(String securityGroupName); /** * Unbind a security group from the set of security groups for running applications. *

* This method requires the logged in user to have admin permissions in the cloud controller. */ void unbindRunningSecurityGroup(String securityGroupName); /** * Gets all the spaces that are bound to the given security group. *

* This method requires the logged in user to have admin permissions in the cloud controller. */ List getSpacesBoundToSecurityGroup(String securityGroupName); /** * Bind a security group to a space. *

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param orgName The name of the organization that the space is in. * @param spaceName The name of the space * @param securityGroupName The name of the security group to bind to the space * @throws IllegalArgumentException if the org, space, or security group do not exist */ void bindSecurityGroup(String orgName, String spaceName, String securityGroupName); /** * Unbind a security group from a space. *

* This method requires the logged in user to have admin permissions in the cloud controller. * * @param orgName The name of the organization that the space is in. * @param spaceName The name of the space * @param securityGroupName The name of the security group to bind to the space * @throws IllegalArgumentException if the org, space, or security group do not exist */ void unbindSecurityGroup(String orgName, String spaceName, String securityGroupName); /** * Get all users in the specified organization * * @param orgName organization name * @return a Map CloudUser with username as key * @throws IllegalArgumentException if the org do not exist */ Map getOrganizationUsers(String orgName); ======= /** * Add a private domain in the current organization. * * @param domainName the domain to add */ void addDomain(String domainName); /** * Register a new route to the a domain. * * @param host the host of the route to register * @param domainName the domain of the route to register */ void addRoute(String host, String domainName); /** * Associate (provision) a service with an application. * * @param appName the application name * @param serviceName the service name */ void bindService(String appName, String serviceName); /** * Create application. * * @param appName application name * @param staging staging info * @param memory memory to use in MB * @param uris list of URIs for the app * @param serviceNames list of service names to bind to app */ void createApplication(String appName, Staging staging, Integer memory, List uris, List serviceNames); /** * Create application. * * @param appName application name * @param staging staging info * @param disk disk quota to use in MB * @param memory memory to use in MB * @param uris list of URIs for the app * @param serviceNames list of service names to bind to app */ public void createApplication(String appName, Staging staging, Integer disk, Integer memory, List uris, List serviceNames); /** * Create quota * * @param quota */ void createQuota(CloudQuota quota); /** * Create a service. * * @param service cloud service info */ void createService(CloudService service); /** * Create a service broker. * * @param serviceBroker cloud service broker info */ void createServiceBroker(CloudServiceBroker serviceBroker); /** * Create a space with the specified name * * @param spaceName */ void createSpace(String spaceName); /** * Create a user-provided service. * * @param service cloud service info * @param credentials the user-provided service credentials */ void createUserProvidedService(CloudService service, Map credentials); /** * Create a user-provided service for logging. * * @param service cloud service info * @param credentials the user-provided service credentials * @param syslogDrainUrl for a logging service */ void createUserProvidedService(CloudService service, Map credentials, String syslogDrainUrl); /** * Debug application. * * @param appName name of application * @param mode debug mode info */ void debugApplication(String appName, CloudApplication.DebugMode mode); /** * Delete all applications. */ void deleteAllApplications(); /** * Delete all services. */ void deleteAllServices(); /** * Delete application. * * @param appName name of application */ void deleteApplication(String appName); /** * Delete a private domain in the current organization. * * @param domainName the domain to delete */ void deleteDomain(String domainName); /** * Delete routes that do not have any application which is assigned to them. */ List deleteOrphanedRoutes(); /** * Delete quota by name * * @param quotaName */ void deleteQuota(String quotaName); /** * Delete a registered route from the space of the current session. * * @param host the host of the route to delete * @param domainName the domain of the route to delete */ void deleteRoute(String host, String domainName); /** * Delete cloud service. * * @param service name of service */ void deleteService(String service); /** * Delete a service broker. * * @param name the service broker name */ void deleteServiceBroker(String name); /** * Delete a space with the specified name * * @param spaceName name of the space */ void deleteSpace(String spaceName); /** * Get cloud application with the specified name. * * @param appName name of the app * @return the cloud application */ CloudApplication getApplication(String appName); /** * Get application instances info for application. * * @param appName name of application. * @return instances info */ InstancesInfo getApplicationInstances(String appName); /** * Get application instances info for application. * * @param app the application. * @return instances info */ InstancesInfo getApplicationInstances(CloudApplication app); /** * Get application stats for the app with the specified name. * * @param appName name of the app * @return the cloud application stats */ ApplicationStats getApplicationStats(String appName); /** * Get all cloud applications. * * @return list of cloud applications */ List getApplications(); /** * Get the URL used for the cloud controller. * * @return the cloud controller URL */ URL getCloudControllerUrl(); /** * Get CloudInfo for the current cloud. * * @return CloudInfo object containing the cloud info */ CloudInfo getCloudInfo(); /** * Get logs from most recent crash of the deployed application. The logs will be returned in a Map keyed by the * path * of the log file (logs/stderr.log, logs/stdout.log). * * @param appName name of the application /** * @return a Map containing the logs. The logs will be returned with the path to the log file used as the key and * the full content of the log file will be returned as a String value for the corresponding key. * @deprecated Use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)} */ Map getCrashLogs(String appName); /** * Get crashes info for application. * * @param appName name of application * @return crashes info */ CrashesInfo getCrashes(String appName); /** * Gets the default domain for the current org, which is the first shared domain. * * @return the default domain */ CloudDomain getDefaultDomain(); /** * Get list of all domain shared and private domains. * * @return list of domains */ List getDomains(); /** * Get list of all domain registered for the current organization. * * @return list of domains */ List getDomainsForOrg(); /** * Get file from the deployed application. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @return the contents of the file */ String getFile(String appName, int instanceIndex, String filePath); /** * Get a the content, starting at a specific position, of a file from the deployed application. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @param startPosition the starting position of the file contents (inclusive) * @return the contents of the file */ String getFile(String appName, int instanceIndex, String filePath, int startPosition); /** * Get a range of content of a file from the deployed application. The range begins at the specified startPosition * and extends to the character at endPosition - 1. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @param startPosition the starting position of the file contents (inclusive) * @param endPosition the ending position of the file contents (exclusive) * @return the contents of the file */ String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition); /** * Get a the last bytes, with length as specified, of content of a file from the deployed application. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @param length the length of the file contents to retrieve * @return the contents of the file */ String getFileTail(String appName, int instanceIndex, String filePath, int length); /** * Get logs from the deployed application. The logs will be returned in a Map keyed by the path of the log file * (logs/stderr.log, logs/stdout.log). * * @param appName name of the application * @return a Map containing the logs. The logs will be returned with the path to the log file used as the key and * the full content of the log file will be returned as a String value for the corresponding key. * @deprecated Use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)} */ Map getLogs(String appName); /** * Get list of CloudOrganizations for the current cloud. * List getStacks(); * @return List of CloudOrganizations objects containing the organization info */ List getOrganizations(); /** * Get list of all private domains. * * @return list of private domains */ List getPrivateDomains(); /** * Get quota by name * * @param quotaName * @param required * @return CloudQuota instance */ CloudQuota getQuotaByName(String quotaName, boolean required); /** * Get quota definitions * * @return List */ List getQuotas(); /** * Stream recent log entries. * * Stream logs that were recently produced for an app. * * @param appName the name of the application * @return the list of recent log entries */ List getRecentLogs(String appName); /** * Get the info for all routes for a domain. * * @param domainName the domain the routes belong to * @return list of routes */ List getRoutes(String domainName); /** * Get cloud service. * * @param service name of service * @return the cloud service info */ CloudService getService(String service); /** * Get a service broker. * * @param name the service broker name * @return the service broker */ CloudServiceBroker getServiceBroker(String name); /** * Get all service brokers. * * @return */ List getServiceBrokers(); /** * Get all service offerings. * * @return list of service offerings */ List getServiceOfferings(); /** * Get list of cloud services. * * @return list of cloud services */ List getServices(); /** * Get list of all shared domains. * * @return list of shared domains */ List getSharedDomains(); /** * Get space name with the specified name. * * @param spaceName name of the space * @return the cloud space */ CloudSpace getSpace(String spaceName); /** * Get list of CloudSpaces for the current cloud. * * @return List of CloudSpace objects containing the space info */ List getSpaces(); /** * Get a stack by name. * * @param name the name of the stack to get * @return the stack, or null if not found */ CloudStack getStack(String name); /** * Get the list of stacks available for staging applications. * * @return the list of available stacks */ * Get the staging log while an application is starting. A null value indicates that no further checks for staging * logs should occur as staging logs are no longer available. * * @param info starting information containing staging log file URL. Obtained after starting an application. * @param offset starting position from where content should be retrieved. * @return portion of the staging log content starting from the offset. It may contain multiple lines. Returns null * if no further content is available. */ String getStagingLogs(StartingInfo info, int offset); /** * Login using the credentials already set for the client. * * @return authentication token */ OAuth2AccessToken login(); /** * Logout closing the current session. */ void logout(); /** * Register new user account with the provided credentials. * * @param email the email account * @param password the password */ void register(String email, String password); /** * Register a new RestLogCallback * * @param callBack the callback to be registered */ void registerRestLogListener(RestLogCallback callBack); /** * Delete a private domain in the current organization. * * @param domainName the domain to remove * @deprecated alias for {@link #deleteDomain} */ void removeDomain(String domainName); /** * Rename an application. * * @param appName the current name * @param newName the new name */ void rename(String appName, String newName); /** * Restart application. * * @param appName name of application */ StartingInfo restartApplication(String appName); /** * Set quota to organization * * @param orgName * @param quotaName */ void setQuotaToOrg(String orgName, String quotaName); /** * Override the default REST response error handler with a custom error handler. * * @param errorHandler */ void setResponseErrorHandler(ResponseErrorHandler errorHandler); /** * Start application. May return starting info if the response obtained after the start request contains headers * . If * the response does not contain headers, null is returned instead. * * @param appName name of application * @return Starting info containing response headers, if headers are present in the response. If there are no * headers, return null. */ StartingInfo startApplication(String appName); /** * Stop application. * * @param appName name of application */ void stopApplication(String appName); /** * Stream application logs produced after this method is called. * * This method has 'tail'-like behavior. Every time there is a new log entry, it notifies the listener. * * @param appName the name of the application * @param listener listener object to be notified * @return token than can be used to cancel listening for logs */ StreamingLogToken streamLogs(String appName, ApplicationLogListener listener); /** * Un-register a RestLogCallback * * @param callBack the callback to be un-registered */ void unRegisterRestLogListener(RestLogCallback callBack); /** * Un-associate (unprovision) a service from an application. * * @param appName the application name * @param serviceName the service name */ void unbindService(String appName, String serviceName); /** * Unregister and log out the currently logged in user */ void unregister(); /** * Update application disk quota. * * @param appName name of application * @param disk new disk setting in MB */ void updateApplicationDiskQuota(String appName, int disk); /** * Update application env using a map where the key specifies the name of the environment variable and the value the * value of the environment variable.. * * @param appName name of application * @param env map of environment settings */ void updateApplicationEnv(String appName, Map env); /** * Update application env using a list of strings each with one environment setting. * * @param appName name of application * @param env list of environment settings */ void updateApplicationEnv(String appName, List env); /** * Update application instances. * * @param appName name of application * @param instances number of instances to use */ void updateApplicationInstances(String appName, int instances); /** * Update application memory. * * @param appName name of application * @param memory new memory setting in MB */ void updateApplicationMemory(String appName, int memory); /** * Update application services. * * @param appName name of appplication * @param services list of services that should be bound to app */ void updateApplicationServices(String appName, List services); /** * Update application staging information. * * @param appName name of appplication * @param staging staging information for the app */ void updateApplicationStaging(String appName, Staging staging); /** * Update application URIs. * * @param appName name of application * @param uris list of URIs the app should use */ void updateApplicationUris(String appName, List uris); /** * Update the password for the logged in user. * * @param newPassword the new password */ void updatePassword(String newPassword); /** * Update the password for the logged in user using the username/old_password provided in the credentials. * * @param credentials current credentials * @param newPassword the new password */ void updatePassword(CloudCredentials credentials, String newPassword); /** * Update Quota definition * * @param quota * @param name */ void updateQuota(CloudQuota quota, String name); /** * Update a service broker (unchanged forces catalog refresh). * * @param serviceBroker cloud service broker info */ void updateServiceBroker(CloudServiceBroker serviceBroker); /** * Service plans are private by default when a service broker's catalog is fetched/updated. This method will update * the visibility of all plans for a broker to either public or private. * * @param name the service broker name * @param visibility true for public, false for private */ void updateServicePlanVisibilityForBroker(String name, boolean visibility); /** * Upload an application to Cloud Foundry. * * @param appName application name * @param file path to the application archive or folder * @throws java.io.IOException */ void uploadApplication(String appName, String file) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param file the application archive or folder * @throws java.io.IOException */ void uploadApplication(String appName, File file) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param file the application archive * @param callback a callback interface used to provide progress information or null * @throws java.io.IOException */ void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException; /** * Upload an application to Cloud Foundry. * * This form of uploadApplication will read the passed InputStream and copy the contents to a * temporary file for upload. * * @param appName the application name * @param fileName the logical name of the application file * @param inputStream the InputStream to read from * @throws java.io.IOException */ void uploadApplication(String appName, String fileName, InputStream inputStream) throws IOException; /** * Upload an application to Cloud Foundry. * * This form of uploadApplication will read the passed InputStream and copy the contents to a * temporary file for upload. * * @param appName the application name * @param fileName the logical name of the application file * @param inputStream the InputStream to read from * @param callback a callback interface used to provide progress information or null * @throws java.io.IOException */ void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback callback) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param archive the application archive * @throws java.io.IOException */ void uploadApplication(String appName, ApplicationArchive archive) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param archive the application archive * @param callback a callback interface used to provide progress information or null * @throws java.io.IOException */ void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws IOException; >>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d }

Solution content
 */
public interface CloudFoundryOperations {

    /**
     * Add a private domain in the current organization.
     *
     * @param domainName the domain to add
     */
    void addDomain(String domainName);

    /**
     * Register a new route to the a domain.
     *
     * @param host       the host of the route to register
     * @param domainName the domain of the route to register
     */
    void addRoute(String host, String domainName);

    /**
     * Associate current user to the space auditors role
     *
     * @param spaceName name of the space
     */
    void associateAuditorWithSpace(String spaceName);

    /**
     * Associate current user to the space auditors role
     *
     * @param orgName   name of the organization containing the space
     * @param spaceName name of the space
     */
    void associateAuditorWithSpace(String orgName, String spaceName);

    /**
     * Associate a user to the space auditors role
     *
     * @param orgName   name of the organization containing the space
     * @param spaceName name of the space
     * @param userGuid  guid of the user. If null, use current user. To retrieve user guid, use {@link
     *                  #getOrganizationUsers(String) getOrganizationUsers } and search for username
     */
    void associateAuditorWithSpace(String orgName, String spaceName, String userGuid);

    /**
     * Associate current user to the space developer role
     *
     * @param spaceName name of the space
     */
    void associateDeveloperWithSpace(String spaceName);

    /**
     * Associate current user to the space developer role
     *
     * @param orgName   name of the organization containing the space
     * @param spaceName name of the space
     */
    void associateDeveloperWithSpace(String orgName, String spaceName);

    /**
     * Associate a user to the space developer role
     *
     * @param orgName   name of the organization containing the space
     * @param spaceName name of the space
     * @param userGuid  guid of the user. If null, use current user. To retrieve user guid, use {@link
     *                  #getOrganizationUsers(String) getOrganizationUsers } and search for username
     */
    void associateDeveloperWithSpace(String orgName, String spaceName, String userGuid);

    /**
     * Associate current user to the space managers role
     *
     * @param spaceName name of the space
     */
    void associateManagerWithSpace(String spaceName);

    /**
     * Associate current user to the space managers role
     *
     * @param orgName   name of the organization containing the space
     * @param spaceName name of the space
     */
    void associateManagerWithSpace(String orgName, String spaceName);

    /**
     * Associate a user to the space managers role
     *
     * @param orgName   name of the organization containing the space
     * @param spaceName name of the space
     * @param userGuid  guid of the user. If null, use current user. To retrieve user guid, use {@link
     *                  #getOrganizationUsers(String) getOrganizationUsers } and search for username
     */
    void associateManagerWithSpace(String orgName, String spaceName, String userGuid);

    /**
     * Bind a security group to the list of security groups to be used for running applications. 

This method * requires the logged in user to have admin permissions in the cloud controller. */ void bindRunningSecurityGroup(String securityGroupName); /** * Bind a security group to a space.

This method requires the logged in user to have admin permissions in the * cloud controller. * * @param orgName The name of the organization that the space is in. * @param spaceName The name of the space * @param securityGroupName The name of the security group to bind to the space * @throws IllegalArgumentException if the org, space, or security group do not exist */ void bindSecurityGroup(String orgName, String spaceName, String securityGroupName); /** * Associate (provision) a service with an application. * * @param appName the application name * @param serviceName the service name */ void bindService(String appName, String serviceName); /** /** * Bind a security group to the list of security groups to be used for staging applications.

This method * requires the logged in user to have admin permissions in the cloud controller. */ void bindStagingSecurityGroup(String securityGroupName); /** * Create application. * * @param appName application name * @param staging staging info * @param memory memory to use in MB * @param uris list of URIs for the app * @param serviceNames list of service names to bind to app */ void createApplication(String appName, Staging staging, Integer memory, List uris, List serviceNames); /** * Create application. * * @param appName application name * @param staging staging info * @param disk disk quota to use in MB * @param memory memory to use in MB * @param uris list of URIs for the app * @param serviceNames list of service names to bind to app */ public void createApplication(String appName, Staging staging, Integer disk, Integer memory, List uris, List serviceNames); /** * Create quota * * @param quota */ void createQuota(CloudQuota quota); /** * Create a new CloudSecurityGroup.

This method requires the logged in user to have admin permissions in the * cloud controller. * * @param securityGroup */ void createSecurityGroup(CloudSecurityGroup securityGroup); /** * Create a new CloudSecurityGroup using a JSON rules file. This is equivalent to cf create-security-group * SECURITY-GROUP PATH-TO-RULES-FILE when using the cf command line. See the Application Security Group * documentation for more details.

Example JSON-formatted rules file: *

     * {@code
     * [
     *  {
     * 		"protocol":"tcp",
     * 		"destination":"10.0.11.0/24",
     * 		"ports":"1-65535"
     *  },
     *  {
     *  	"protocol":"udp",
     *  	"destination":"10.0.11.0/24",
     *  	"ports":"1-65535"
     *  }
     * ]
     *  }
     * 
*

This method requires the logged in user to have admin permissions in the cloud controller. * * @param name the name for the security group * @param jsonRulesFile An input stream that has a single array with JSON objects inside describing the rules * @see http://docs.cloudfoundry.org/adminguide/app-sec-groups.html */ void createSecurityGroup(String name, InputStream jsonRulesFile); /** * Create a service. * * @param service cloud service info */ void createService(CloudService service); /** * Create a service broker. * * @param serviceBroker cloud service broker info */ void createServiceBroker(CloudServiceBroker serviceBroker); /** * Create a space with the specified name * * @param spaceName */ void createSpace(String spaceName); /** * Create a user-provided service. * * @param service cloud service info * @param credentials the user-provided service credentials */ void createUserProvidedService(CloudService service, Map credentials); * Create a user-provided service for logging. * * @param service cloud service info * @param credentials the user-provided service credentials * @param syslogDrainUrl for a logging service */ void createUserProvidedService(CloudService service, Map credentials, String syslogDrainUrl); /** * Debug application. * * @param appName name of application * @param mode debug mode info */ void debugApplication(String appName, CloudApplication.DebugMode mode); /** * Delete all applications. */ void deleteAllApplications(); /** * Delete all services. */ void deleteAllServices(); /** * Delete application. * * @param appName name of application */ void deleteApplication(String appName); /** * Delete a private domain in the current organization. * * @param domainName the domain to delete */ void deleteDomain(String domainName); /** * Delete routes that do not have any application which is assigned to them. */ List deleteOrphanedRoutes(); /** * Delete quota by name * * @param quotaName */ void deleteQuota(String quotaName); /** * Delete a registered route from the space of the current session. * * @param host the host of the route to delete * @param domainName the domain of the route to delete */ void deleteRoute(String host, String domainName); /** * Deletes the security group with the given name.

This method requires the logged in user to have admin * permissions in the cloud controller. * * @param securityGroupName * @throws IllegalArgumentException if a security group does not exist with the given name */ void deleteSecurityGroup(String securityGroupName); /** * Delete cloud service. * * @param service name of service */ void deleteService(String service); /** * Delete a service broker. * * @param name the service broker name */ void deleteServiceBroker(String name); /** * Delete a space with the specified name * * @param spaceName name of the space */ void deleteSpace(String spaceName); /** * Get cloud application with the specified name. * * @param appName name of the app * @return the cloud application */ CloudApplication getApplication(String appName); /** * Get cloud application with the specified GUID. * * @param guid GUID of the app * @return the cloud application */ CloudApplication getApplication(UUID guid); /** * Get application environment variables for the app with the specified name. * * @param appName name of the app * @return the cloud application environment variables */ Map getApplicationEnvironment(String appName); /** * Get application environment variables for the app with the specified GUID. * * @param appGuid GUID of the app * @return the cloud application environment variables */ Map getApplicationEnvironment(UUID appGuid); /** * Get application events. * * @param appName name of application * @return application events */ List getApplicationEvents(String appName); /** * Get application instances info for application. * * @param appName name of application. * @return instances info */ InstancesInfo getApplicationInstances(String appName); /** * Get application instances info for application. * * @param app the application. * @return instances info */ InstancesInfo getApplicationInstances(CloudApplication app); /** * Get application stats for the app with the specified name. * * @param appName name of the app * @return the cloud application stats */ ApplicationStats getApplicationStats(String appName); /** * Get all cloud applications. * * @return list of cloud applications */ List getApplications(); /** * Get the URL used for the cloud controller. * * @return the cloud controller URL */ URL getCloudControllerUrl(); /** * Get CloudInfo for the current cloud. * * @return CloudInfo object containing the cloud info */ CloudInfo getCloudInfo(); /** * Get logs from most recent crash of the deployed application. The logs will be returned in a Map keyed by the path * of the log file (logs/stderr.log, logs/stdout.log). * * @param appName name of the application * @return a Map containing the logs. The logs will be returned with the path to the log file used as the key and * the full content of the log file will be returned as a String value for the corresponding key. * @deprecated Use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)} */ Map getCrashLogs(String appName); /** * Get crashes info for application. * * @param appName name of application * @return crashes info */ CrashesInfo getCrashes(String appName); /** * Gets the default domain for the current org, which is the first shared domain. * * @return the default domain */ CloudDomain getDefaultDomain(); /** * Get list of all domain shared and private domains. * * @return list of domains */ List getDomains(); /** * Get list of all domain registered for the current organization. * * @return list of domains */ List getDomainsForOrg(); /** * Get system events. * * @return all system events */ List getEvents(); /** * Get file from the deployed application. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @return the contents of the file */ String getFile(String appName, int instanceIndex, String filePath); /** * Get a the content, starting at a specific position, of a file from the deployed application. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @param startPosition the starting position of the file contents (inclusive) * @return the contents of the file */ String getFile(String appName, int instanceIndex, String filePath, int startPosition); /** * Get a range of content of a file from the deployed application. The range begins at the specified startPosition * and extends to the character at endPosition - 1. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @param startPosition the starting position of the file contents (inclusive) * @param endPosition the ending position of the file contents (exclusive) * @return the contents of the file */ String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition); /** * Get a the last bytes, with length as specified, of content of a file from the deployed application. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @param length the length of the file contents to retrieve * @return the contents of the file */ String getFileTail(String appName, int instanceIndex, String filePath, int length); /** * Get logs from the deployed application. The logs will be returned in a Map keyed by the path of the log file * (logs/stderr.log, logs/stdout.log). * * @param appName name of the application * @return a Map containing the logs. The logs will be returned with the path to the log file used as the key and * the full content of the log file will be returned as a String value for the corresponding key. * @deprecated Use {@link #streamLogs(String, ApplicationLogListener)} or {@link #getRecentLogs(String)} */ Map getLogs(String appName); /** * Get the organization with the specified name. * * @param orgName name of organization * @param required if true, and organization is not found, throw an exception * @return */ CloudOrganization getOrgByName(String orgName, boolean required); /** * Get all users in the specified organization * * @param orgName organization name * @return a Map CloudUser with username as key * @throws IllegalArgumentException if the org do not exist */ Map getOrganizationUsers(String orgName); /** * Get list of CloudOrganizations for the current cloud. * * @return List of CloudOrganizations objects containing the organization info */ List getOrganizations(); /** * Get list of all private domains. * * @return list of private domains */ List getPrivateDomains(); /** * Get quota by name * * @param quotaName * @param required * @return CloudQuota instance */ CloudQuota getQuotaByName(String quotaName, boolean required); /** * Get quota definitions * * @return List */ List getQuotas(); /** * Stream recent log entries. * * Stream logs that were recently produced for an app. * * @param appName the name of the application * @return the list of recent log entries */ List getRecentLogs(String appName); /** * Get the info for all routes for a domain. * * @param domainName the domain the routes belong to * @return list of routes */ List getRoutes(String domainName); /** * List security groups in the set of security groups for running applications.

This method requires the logged * in user to have admin permissions in the cloud controller. */ List getRunningSecurityGroups(); /** * Get a specific security group by name.

This method requires the logged in user to have admin permissions in * the cloud controller. * * @param securityGroupName The name of the security group * @return the CloudSecurityGroup or null if no security groups exist with the given name */ CloudSecurityGroup getSecurityGroup(String securityGroupName); /** * Get a List of all application security groups.

This method requires the logged in user to have admin * permissions in the cloud controller. * * @return a list of all the {@link CloudSecurityGroup}s in the system */ List getSecurityGroups(); /** * Get cloud service. * * @param service name of service * @return the cloud service info */ CloudService getService(String service); /** * Get a service broker. * * @param name the service broker name * @return the service broker */ CloudServiceBroker getServiceBroker(String name); /** * Get all service brokers. * * @return */ List getServiceBrokers(); /** * Get a service instance. * * @param service name of the service instance * @return the service instance info */ CloudServiceInstance getServiceInstance(String service); /** * Get all service offerings. * * @return list of service offerings */ List getServiceOfferings(); /** * Get list of cloud services. * * @return list of cloud services */ List getServices(); /** * Get list of all shared domains. * * @return list of shared domains */ List getSharedDomains(); /** * Get space name with the specified name. * * @param spaceName name of the space * @return the cloud space */ CloudSpace getSpace(String spaceName); /** * Get list of space auditor UUID for the space. * * @param spaceName name of the space * @return List of space auditor UUID */ List getSpaceAuditors(String spaceName); /** * Get list of space auditor UUID for the space. * * @param orgName name of the organization containing the space * @param spaceName name of the space * @return List of space auditor UUID */ List getSpaceAuditors(String orgName, String spaceName); /** * Get list of space developer UUID for the space. * * @param spaceName name of the space * @return List of space developer UUID */ List getSpaceDevelopers(String spaceName); /** * Get list of space developer UUID for the space. * * @param orgName name of the organization containing the space * @param spaceName name of the space * @return List of space developer UUID */ List getSpaceDevelopers(String orgName, String spaceName); /** * Get list of space manager UUID for the space. * * @param spaceName name of the space * @return List of space manager UUID */ List getSpaceManagers(String spaceName); /** * Get list of space manager UUID for the space. * * @param orgName name of the organization containing the space * @param spaceName name of the space * @return List of space manager UUID */ List getSpaceManagers(String orgName, String spaceName); /** * Get list of CloudSpaces for the current cloud. * * @return List of CloudSpace objects containing the space info */ List getSpaces(); /** * Gets all the spaces that are bound to the given security group.

This method requires the logged in user to * have admin permissions in the cloud controller. */ List getSpacesBoundToSecurityGroup(String securityGroupName); /** * Get a stack by name. * * @param name the name of the stack to get * @return the stack, or null if not found */ CloudStack getStack(String name); /** * Get the list of stacks available for staging applications. * * @return the list of available stacks */ List getStacks(); /** * Get the staging log while an application is starting. A null value indicates that no further checks for staging * logs should occur as staging logs are no longer available. * * @param info starting information containing staging log file URL. Obtained after starting an application. * @param offset starting position from where content should be retrieved. * @return portion of the staging log content starting from the offset. It may contain multiple lines. Returns null * if no further content is available. */ String getStagingLogs(StartingInfo info, int offset); /** * Lists security groups in the staging set for applications.

This method requires the logged in user to have * admin permissions in the cloud controller. */ List getStagingSecurityGroups(); /** * Login using the credentials already set for the client. * * @return authentication token */ OAuth2AccessToken login(); /** * Logout closing the current session. */ void logout(); /** * Provide the content of a file from the deployed application via callbacks. * * @param appName name of the application * @param instanceIndex instance index * @param filePath path to the file * @param clientHttpResponseCallback callback object to receive file contents */ void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback clientHttpResponseCallback); /** * Register new user account with the provided credentials. * * @param email the email account * @param password the password */ void register(String email, String password); /** * Register a new RestLogCallback * * @param callBack the callback to be registered */ void registerRestLogListener(RestLogCallback callBack); /** * Delete a private domain in the current organization. * * @param domainName the domain to remove * @deprecated alias for {@link #deleteDomain} */ void removeDomain(String domainName); /** * Rename an application. * * @param appName the current name * @param newName the new name */ void rename(String appName, String newName); /** * Restart application. * * @param appName name of application */ StartingInfo restartApplication(String appName); /** * Set quota to organization * * @param orgName * @param quotaName */ void setQuotaToOrg(String orgName, String quotaName); /** * Override the default REST response error handler with a custom error handler. * * @param errorHandler */ void setResponseErrorHandler(ResponseErrorHandler errorHandler); /** * Start application. May return starting info if the response obtained after the start request contains headers . * If the response does not contain headers, null is returned instead. * * @param appName name of application * @return Starting info containing response headers, if headers are present in the response. If there are no * headers, return null. */ StartingInfo startApplication(String appName); /** * Stop application. * * @param appName name of application */ void stopApplication(String appName); /** * Stream application logs produced after this method is called. * * This method has 'tail'-like behavior. Every time there is a new log entry, it notifies the listener. * * @param appName the name of the application * @param listener listener object to be notified * @return token than can be used to cancel listening for logs */ StreamingLogToken streamLogs(String appName, ApplicationLogListener listener); /** * Un-register a RestLogCallback * * @param callBack the callback to be un-registered */ void unRegisterRestLogListener(RestLogCallback callBack); /** * Unbind a security group from the set of security groups for running applications.

This method requires the * logged in user to have admin permissions in the cloud controller. */ void unbindRunningSecurityGroup(String securityGroupName); /** * Unbind a security group from a space.

This method requires the logged in user to have admin permissions in * the cloud controller. * * @param orgName The name of the organization that the space is in. * @param spaceName The name of the space * @param securityGroupName The name of the security group to bind to the space * @throws IllegalArgumentException if the org, space, or security group do not exist */ void unbindSecurityGroup(String orgName, String spaceName, String securityGroupName); /** * Un-associate (unprovision) a service from an application. * * @param appName the application name * @param serviceName the service name */ void unbindService(String appName, String serviceName); /** * Unbind a security group from the set of security groups for staging applications.

This method requires the * logged in user to have admin permissions in the cloud controller. */ void unbindStagingSecurityGroup(String securityGroupName); /** * Unregister and log out the currently logged in user */ void unregister(); /** * Update application disk quota. * * @param appName name of application * @param disk new disk setting in MB */ void updateApplicationDiskQuota(String appName, int disk); /** * Update application env using a map where the key specifies the name of the environment variable and the value the * value of the environment variable.. * * @param appName name of application * @param env map of environment settings */ void updateApplicationEnv(String appName, Map env); /** * Update application env using a list of strings each with one environment setting. * * @param appName name of application * @param env list of environment settings */ void updateApplicationEnv(String appName, List env); /** * Update application instances. * * @param appName name of application * @param instances number of instances to use */ void updateApplicationInstances(String appName, int instances); /** * Update application memory. * * @param appName name of application * @param memory new memory setting in MB */ void updateApplicationMemory(String appName, int memory); /** * Update application services. * * @param appName name of appplication * @param services list of services that should be bound to app */ void updateApplicationServices(String appName, List services); /** * Update application staging information. * * @param appName name of appplication * @param staging staging information for the app */ void updateApplicationStaging(String appName, Staging staging); /** * Update application URIs. * * @param appName name of application * @param uris list of URIs the app should use */ void updateApplicationUris(String appName, List uris); /** * Update the password for the logged in user. * * @param newPassword the new password */ void updatePassword(String newPassword); /** * Update the password for the logged in user using the username/old_password provided in the credentials. * * @param credentials current credentials * @param newPassword the new password */ void updatePassword(CloudCredentials credentials, String newPassword); /** * Update Quota definition * * @param quota * @param name */ void updateQuota(CloudQuota quota, String name); /** * Update an existing security group.

This method requires the logged in user to have admin permissions in the * cloud controller. * * @param securityGroup * @throws IllegalArgumentException if a security group does not exist with the name of the given * CloudSecurityGroup */ void updateSecurityGroup(CloudSecurityGroup securityGroup); /** * Updates a existing CloudSecurityGroup using a JSON rules file. This is equivalent to cf * update-security-group SECURITY-GROUP PATH-TO-RULES-FILE when using the cf command line. See the * Application Security Group documentation for more details.

Example JSON-formatted rules file: *

     * {@code
     * [
     *  {
     * 		"protocol":"tcp",
     * 		"destination":"10.0.11.0/24",
     * 		"ports":"1-65535"
     *  },
     *  {
     *  	"protocol":"udp",
     *  	"destination":"10.0.11.0/24",
     *  	"ports":"1-65535"
     *  }
     * ]
     *  }
     * 
*

This method requires the logged in user to have admin permissions in the cloud controller. * * @param jsonRulesFile An input stream that has a single array with JSON objects inside describing the rules * @throws IllegalArgumentException if a security group does not exist with the given name * @see http://docs.cloudfoundry.org/adminguide/app-sec-groups.html */ void updateSecurityGroup(String name, InputStream jsonRulesFile); /** * Update a service broker (unchanged forces catalog refresh). * * @param serviceBroker cloud service broker info */ void updateServiceBroker(CloudServiceBroker serviceBroker); /** * Service plans are private by default when a service broker's catalog is fetched/updated. This method will update * the visibility of all plans for a broker to either public or private. * * @param name the service broker name * @param visibility true for public, false for private */ void updateServicePlanVisibilityForBroker(String name, boolean visibility); /** * Upload an application to Cloud Foundry. * * @param appName application name * @param file path to the application archive or folder * @throws java.io.IOException */ void uploadApplication(String appName, String file) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param file the application archive or folder * @throws java.io.IOException */ void uploadApplication(String appName, File file) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param file the application archive * @param callback a callback interface used to provide progress information or null * @throws java.io.IOException */ void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException; /** * Upload an application to Cloud Foundry. * * This form of uploadApplication will read the passed InputStream and copy the contents to a * temporary file for upload. * * @param appName the application name * @param fileName the logical name of the application file * @param inputStream the InputStream to read from * @throws java.io.IOException */ void uploadApplication(String appName, String fileName, InputStream inputStream) throws IOException; /** * Upload an application to Cloud Foundry. * * This form of uploadApplication will read the passed InputStream and copy the contents to a * temporary file for upload. * * @param appName the application name * @param fileName the logical name of the application file * @param inputStream the InputStream to read from * @param callback a callback interface used to provide progress information or null * @throws java.io.IOException */ void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback callback) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param archive the application archive * @throws java.io.IOException */ void uploadApplication(String appName, ApplicationArchive archive) throws IOException; /** * Upload an application to Cloud Foundry. * * @param appName the application name * @param archive the application archive * @param callback a callback interface used to provide progress information or null * @throws java.io.IOException */ void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws IOException; }

File
CloudFoundryOperations.java
Developer's decision
Manual
Kind of conflict
Comment
Method interface
Chunk
Conflicting content
        .NONE)
public class CloudApplication extends CloudEntity {

<<<<<<< HEAD
	private static final String COMMAND_KEY = "command";
	private static final String BUILDPACK_URL_KEY = "buildpack";
	private static final String DETECTED_BUILDPACK_KEY = "detected_buildpack";
	private static final String MEMORY_KEY = "memory";
	private static final String DISK_KEY = "disk_quota";

	private CloudSpace space;
	private Staging staging;
	private int instances;
	private int memory;
	private int diskQuota;
	private List uris;
	private List services;
	private AppState state;
	private DebugMode debug;
	private int runningInstances;
	private List env = new ArrayList();

	public CloudApplication(Meta meta, String name) {
		super(meta, name);
	}

	public CloudApplication(String name, String command, String buildpackUrl, int memory, int instances,
						List uris, List serviceNames,
						AppState state) {
		super(CloudEntity.Meta.defaultMeta(), name);
		this.staging = new Staging(command, buildpackUrl);
		this.memory = memory;
		this.instances = instances;
		this.uris = uris;
		this.services = serviceNames;
		this.state = state;
	}

	@SuppressWarnings("unchecked")
	public CloudApplication(Map attributes) {
		super(CloudEntity.Meta.defaultMeta(), parse(attributes.get("name")));
		instances = (Integer)attributes.get("instances");
		Integer runningInstancesAttribute = (Integer) attributes.get("runningInstances");
		if (runningInstancesAttribute != null) {
			runningInstances = runningInstancesAttribute;
		}
		uris = (List)attributes.get("uris");
		services = (List)attributes.get("services");
		state = AppState.valueOf((String) attributes.get("state"));
		if (attributes.containsKey("memory")) {
			memory = (Integer) attributes.get("memory");
		}
		if (attributes.containsKey("disk_quota")) {
			diskQuota = (Integer) attributes.get("disk_quota");
		}
		env = (List) attributes.get("env");

		Map metaValue = parse(Map.class,
				attributes.get("meta"));
		if (metaValue != null) {
			String debugAttribute = (String) metaValue.get("debug");
			if (debugAttribute != null) {
				debug = DebugMode.valueOf(debugAttribute);
			}
			long created = parse(Long.class, metaValue.get("created"));
			Date createdDate = created != 0 ? new Date(created * 1000) : null;
			setMeta(new Meta(null, createdDate, null));

			String command = null;
			if (metaValue.containsKey(COMMAND_KEY)) {
				command = (String) metaValue.get(COMMAND_KEY);
			}
			String buildpackUrl = null;
			if (metaValue.containsKey(BUILDPACK_URL_KEY)) {
				buildpackUrl = (String) metaValue.get(BUILDPACK_URL_KEY);
			}
			String detectedBuildpack = null;
			if (metaValue.containsKey(DETECTED_BUILDPACK_KEY)) {
				detectedBuildpack = (String) metaValue.get(DETECTED_BUILDPACK_KEY);
			}
			
			setStaging(new Staging(command, buildpackUrl, detectedBuildpack));
		}
	}

	public CloudSpace getSpace() {
		return space;
	}

	public void setSpace(CloudSpace space) {
		this.space = space;
	}

	public enum AppState {
		UPDATING, STARTED, STOPPED
	}

	public enum DebugMode {
		run,
		suspend
	}

	public Staging getStaging() {
		return staging;
	}

	public void setStaging(Staging staging) {
		this.staging = staging;
	}

	// for backward compatibility
	public Map getResources() {
		Map resources = new HashMap();
		resources.put(MEMORY_KEY, memory);
		resources.put(DISK_KEY, diskQuota);
		return resources;
	}

	public int getInstances() {
		return instances;
	}

	public void setInstances(int instances) {
		this.instances = instances;
	}

	public int getDiskQuota() {
		return diskQuota;
	}

	public void setDiskQuota(int diskQuota) {
		this.diskQuota = diskQuota;
	}

	public int getMemory() {
		return memory;
	}

	public void setMemory(int memory) {
		this.memory = memory;
	}

	public List getUris() {
		return uris;
	}

	public void setUris(List uris) {
		this.uris = uris;
	}

	public AppState getState() {
		return state;
	}

	public void setState(AppState state) {
		this.state = state;
	}

	public DebugMode getDebug() {
		return debug;
	}

	public void setDebug(DebugMode debug) {
		this.debug = debug;
	}

	public List getServices() {
		return services;
	}

	public void setServices(List services) {
		this.services = services;
	}

	public int getRunningInstances() {
		return runningInstances;
	}

	public void setRunningInstances(int runningInstances) {
		this.runningInstances = runningInstances;
	}

	public Map getEnvAsMap() {
		Map envMap = new HashMap();
		for (String nameAndValue : env) {
			String[] parts = nameAndValue.split("=", 2);
			envMap.put(parts[0], parts.length == 2 && parts[1].length() > 0 ? parts[1] : null);
		}
		return envMap;
	}

	public List getEnv() {
		return env;
	}

	public void setEnv(Map env) {
		List joined = new ArrayList();
		for (Map.Entry entry : env.entrySet()) {
			// skip this environment variable if the key is null
			if (null == entry.getKey()) {
				continue;
			}

			String value;
			// check that there is a value. If it is null, the value should be an empty string
			if(null == entry.getValue()) {
				value = "";
			} else {
				value = entry.getValue().toString();
			}

			joined.add(entry.getKey().toString() + '=' + value);
		}

		this.env = joined;
	}

	@Override
	public String toString() {
		return "CloudApplication [staging=" + staging + ", instances="
				+ instances + ", name=" + getName() 
				+ ", memory=" + memory + ", diskQuota=" + diskQuota
				+ ", state=" + state + ", debug=" + debug + ", uris=" + uris + ", services=" + services
    }
				+ ", env=" + env + ", space=" + space.getName() + "]";
	}
=======
    private static final String BUILDPACK_URL_KEY = "buildpack";

    private static final String COMMAND_KEY = "command";

    private static final String DISK_KEY = "disk_quota";

    private static final String MEMORY_KEY = "memory";

    private DebugMode debug;

    private int diskQuota;

    private List env = new ArrayList();

    private int instances;

    private int memory;

    private int runningInstances;

    private List services;

    private Staging staging;

    private AppState state;

    private List uris;

    public CloudApplication(Meta meta, String name) {
        super(meta, name);
    }

    public CloudApplication(String name, String command, String buildpackUrl, int memory, int instances,
                            List uris, List serviceNames,
                            AppState state) {
        super(CloudEntity.Meta.defaultMeta(), name);
        this.staging = new Staging(command, buildpackUrl);
        this.memory = memory;
        this.instances = instances;
        this.uris = uris;
        this.services = serviceNames;
        this.state = state;
    }

    @SuppressWarnings("unchecked")
    public CloudApplication(Map attributes) {
        super(CloudEntity.Meta.defaultMeta(), parse(attributes.get("name")));
        instances = (Integer) attributes.get("instances");
        Integer runningInstancesAttribute = (Integer) attributes.get("runningInstances");
        if (runningInstancesAttribute != null) {
            runningInstances = runningInstancesAttribute;
        }
        uris = (List) attributes.get("uris");
        services = (List) attributes.get("services");
        state = AppState.valueOf((String) attributes.get("state"));
        if (attributes.containsKey("memory")) {
            memory = (Integer) attributes.get("memory");
        }
        if (attributes.containsKey("disk_quota")) {
            diskQuota = (Integer) attributes.get("disk_quota");
        }
        env = (List) attributes.get("env");

        Map metaValue = parse(Map.class,
                attributes.get("meta"));
        if (metaValue != null) {
            String debugAttribute = (String) metaValue.get("debug");
            if (debugAttribute != null) {
                debug = DebugMode.valueOf(debugAttribute);
            }
            long created = parse(Long.class, metaValue.get("created"));
            Date createdDate = created != 0 ? new Date(created * 1000) : null;
            setMeta(new Meta(null, createdDate, null));

            String command = null;
            if (metaValue.containsKey(COMMAND_KEY)) {
                command = (String) metaValue.get(COMMAND_KEY);
            }
            String buildpackUrl = null;
            if (metaValue.containsKey(BUILDPACK_URL_KEY)) {
                buildpackUrl = (String) metaValue.get(BUILDPACK_URL_KEY);
            }

            setStaging(new Staging(command, buildpackUrl));
        }
    }

    public DebugMode getDebug() {
        return debug;
    }

    public void setDebug(DebugMode debug) {
        this.debug = debug;
    }

    public int getDiskQuota() {
        return diskQuota;

    public void setDiskQuota(int diskQuota) {
        this.diskQuota = diskQuota;
    }

    public List getEnv() {
        return env;
    }

    public void setEnv(List env) {
        for (String s : env) {
            if (!s.contains("=")) {
                throw new IllegalArgumentException("Environment setting without '=' is invalid: " + s);
            }
        }
        this.env = env;
    }

    public Map getEnvAsMap() {
        Map envMap = new HashMap();
        for (String nameAndValue : env) {
            String[] parts = nameAndValue.split("=");
            envMap.put(parts[0], parts.length == 2 ? parts[1] : null);
        }
        return envMap;
    }

    public int getInstances() {
        return instances;
    }

    public void setInstances(int instances) {
        this.instances = instances;
    }

    public int getMemory() {
        return memory;
    }

    public void setMemory(int memory) {
        this.memory = memory;
    }

    // for backward compatibility
    public Map getResources() {
        Map resources = new HashMap();
        resources.put(MEMORY_KEY, memory);
        resources.put(DISK_KEY, diskQuota);
        return resources;
    }

    public int getRunningInstances() {
        return runningInstances;
    }

    public void setRunningInstances(int runningInstances) {
        this.runningInstances = runningInstances;
    }

    public List getServices() {
        return services;
    }

    public void setServices(List services) {
        this.services = services;
    }

    public Staging getStaging() {
        return staging;
    }

    public void setStaging(Staging staging) {
        this.staging = staging;
    }

    public AppState getState() {
        return state;
    }

    public void setState(AppState state) {
        this.state = state;
    }

    public List getUris() {
        return uris;
    }

    public void setUris(List uris) {
        this.uris = uris;
    }

    public void setEnv(Map env) {
        List joined = new ArrayList();
        for (Map.Entry entry : env.entrySet()) {
            joined.add(entry.getKey() + '=' + entry.getValue());
        }
        this.env = joined;
    }

    @Override
    public String toString() {
        return "CloudApplication [staging=" + staging + ", instances="
                + instances + ", name=" + getName()
                + ", memory=" + memory + ", diskQuota=" + diskQuota
                + ", state=" + state + ", debug=" + debug + ", uris=" + uris + ",services=" + services
                + ", env=" + env + "]";
    }

    public enum AppState {
        UPDATING, STARTED, STOPPED
    }

    public enum DebugMode {
        run,
        suspend
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
        .NONE)
public class CloudApplication extends CloudEntity {

    private static final String BUILDPACK_URL_KEY = "buildpack";

    private static final String COMMAND_KEY = "command";

    private static final String DETECTED_BUILDPACK_KEY = "detected_buildpack";

    private static final String DISK_KEY = "disk_quota";

    private static final String MEMORY_KEY = "memory";

    private DebugMode debug;

    private int diskQuota;

    private List env = new ArrayList();

    private int instances;

    private int memory;

    private int runningInstances;

    private List services;

    private CloudSpace space;

    private Staging staging;

    private AppState state;

    private List uris;

    public CloudApplication(Meta meta, String name) {
        super(meta, name);
    }

    public CloudApplication(String name, String command, String buildpackUrl, int memory, int instances,
                            List uris, List serviceNames,
                            AppState state) {
        super(CloudEntity.Meta.defaultMeta(), name);
        this.staging = new Staging(command, buildpackUrl);
        this.memory = memory;

        this.instances = instances;
        this.uris = uris;
        this.services = serviceNames;
        this.state = state;
    }

    @SuppressWarnings("unchecked")
    public CloudApplication(Map attributes) {
        super(CloudEntity.Meta.defaultMeta(), parse(attributes.get("name")));
        instances = (Integer) attributes.get("instances");
        Integer runningInstancesAttribute = (Integer) attributes.get("runningInstances");
        if (runningInstancesAttribute != null) {
            runningInstances = runningInstancesAttribute;
        }
        uris = (List) attributes.get("uris");
        services = (List) attributes.get("services");
        state = AppState.valueOf((String) attributes.get("state"));
        if (attributes.containsKey("memory")) {
            memory = (Integer) attributes.get("memory");
        }
        if (attributes.containsKey("disk_quota")) {
            diskQuota = (Integer) attributes.get("disk_quota");
        }
        env = (List) attributes.get("env");

        Map metaValue = parse(Map.class,
                attributes.get("meta"));
        if (metaValue != null) {
            String debugAttribute = (String) metaValue.get("debug");
            if (debugAttribute != null) {
                debug = DebugMode.valueOf(debugAttribute);
            }
            long created = parse(Long.class, metaValue.get("created"));
            Date createdDate = created != 0 ? new Date(created * 1000) : null;
            setMeta(new Meta(null, createdDate, null));

            String command = null;
            if (metaValue.containsKey(COMMAND_KEY)) {
                command = (String) metaValue.get(COMMAND_KEY);
            }
            String buildpackUrl = null;
            if (metaValue.containsKey(BUILDPACK_URL_KEY)) {
                buildpackUrl = (String) metaValue.get(BUILDPACK_URL_KEY);
            }
            String detectedBuildpack = null;
            if (metaValue.containsKey(DETECTED_BUILDPACK_KEY)) {
                detectedBuildpack = (String) metaValue.get(DETECTED_BUILDPACK_KEY);
            }

            setStaging(new Staging(command, buildpackUrl, detectedBuildpack));
        }
    }

    public DebugMode getDebug() {
        return debug;
    }

    public void setDebug(DebugMode debug) {
        this.debug = debug;
    }

    public int getDiskQuota() {
        return diskQuota;
    }

    public void setDiskQuota(int diskQuota) {
        this.diskQuota = diskQuota;
    }

    public List getEnv() {
        return env;
    }

    public void setEnv(Map env) {
        List joined = new ArrayList();
        for (Map.Entry entry : env.entrySet()) {
            // skip this environment variable if the key is null
            if (null == entry.getKey()) {
                continue;
            }

            String value;
            // check that there is a value. If it is null, the value should be an empty string
            if (null == entry.getValue()) {
                value = "";
            } else {
                value = entry.getValue().toString();
            }

            joined.add(entry.getKey().toString() + '=' + value);
        }

        this.env = joined;
    }

    public Map getEnvAsMap() {
        Map envMap = new HashMap();
        for (String nameAndValue : env) {
            String[] parts = nameAndValue.split("=", 2);
            envMap.put(parts[0], parts.length == 2 && parts[1].length() > 0 ? parts[1] : null);
        }
        return envMap;
    }

    public int getInstances() {
        return instances;
    }

    public void setInstances(int instances) {
        this.instances = instances;
    }

    public int getMemory() {
        return memory;
    }

    public void setMemory(int memory) {
        this.memory = memory;
    }

    // for backward compatibility
    public Map getResources() {
        Map resources = new HashMap();
        resources.put(MEMORY_KEY, memory);
        resources.put(DISK_KEY, diskQuota);
        return resources;
    }

    public int getRunningInstances() {
        return runningInstances;
    }
    public void setRunningInstances(int runningInstances) {
        this.runningInstances = runningInstances;
    }

    public List getServices() {
        return services;
    }

    public void setServices(List services) {
        this.services = services;
    }

    public CloudSpace getSpace() {
        return space;
    }

    public void setSpace(CloudSpace space) {
        this.space = space;
    }

    public Staging getStaging() {
        return staging;
    }

    public void setStaging(Staging staging) {
        this.staging = staging;
    }

    public AppState getState() {
        return state;
    }

    public void setState(AppState state) {
        this.state = state;
    }

    public List getUris() {
        return uris;
    }

    public void setUris(List uris) {
        this.uris = uris;
    }

    @Override
    public String toString() {
        return "CloudApplication [staging=" + staging + ", instances="
                + instances + ", name=" + getName()
                + ", memory=" + memory + ", diskQuota=" + diskQuota
                + ", state=" + state + ", debug=" + debug + ", uris=" + uris + ", services=" + services
                + ", env=" + env + ", space=" + space.getName() + "]";
    }

    public enum AppState {
        UPDATING, STARTED, STOPPED
    }

    public enum DebugMode {
        run,
        suspend
    }
}
File
CloudApplication.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Comment
Enum declaration
Method declaration
Method invocation
Chunk
Conflicting content
    public void setName(String name) {

 */
public class CloudEntity {

<<<<<<< HEAD
	@JsonIgnore
	private Meta meta;

	private String name;

	public CloudEntity() {
	}

	public CloudEntity(Meta meta) {
		this(meta, null);
	}

	public CloudEntity(Meta meta, String name) {
		if (meta != null) {
			this.meta = meta;
		}
		else {
			this.meta = Meta.defaultMeta();
		}
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Meta getMeta() {
		return meta;
	}

	public void setMeta(Meta meta) {
		this.meta = meta;
	}

	@Override
	public String toString() {
		return this.getClass().getSimpleName() + ": (" +
				(meta == null || meta.getGuid() == null ? "-" : meta.getGuid()) + ") " +
				getName();
	}

	public static class Meta {

		private UUID guid;
		private Date created;
		private Date updated;
		private String url;

		public Meta(UUID guid, Date created, Date updated) {
			this.guid = guid;
			this.created = created;
			this.updated = updated;
		}
		public Meta(UUID guid, Date created, Date updated, String url) {
			this.guid = guid;
			this.created = created;
			this.updated = updated;
			this.url = url;
		}

		public UUID getGuid() {
			return guid;
		}

		public Date getCreated() {
			return created;
		}

		public Date getUpdated() {
			return updated;
		}

		public String getUrl() {
			return url;
		}

		public static Meta defaultMeta() {
			return new Meta(null, null, null);
		}
	}
=======
    @JsonIgnore
    private Meta meta;

    private String name;

    public CloudEntity() {
    }

    public CloudEntity(Meta meta, String name) {
        if (meta != null) {
            this.meta = meta;
        } else {
            this.meta = Meta.defaultMeta();
        }
        this.name = name;
    }

    public Meta getMeta() {
        return meta;
    }

    public void setMeta(Meta meta) {
        this.meta = meta;
    }

    public String getName() {
        return name;
    }

        this.name = name;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + ": (" +
                (meta == null || meta.getGuid() == null ? "-" : meta.getGuid()) + ") " +
                getName();
    }

    public static class Meta {

        private Date created;

        private UUID guid;

        private Date updated;

        public Meta(UUID guid, Date created, Date updated) {
            this.guid = guid;
            this.created = created;
            this.updated = updated;
        }

        public static Meta defaultMeta() {
            return new Meta(null, null, null);
        }

        public Date getCreated() {
            return created;
        }

        public UUID getGuid() {
            return guid;
        }

        public Date getUpdated() {
            return updated;
        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
 */
public class CloudEntity {

    @JsonIgnore
    private Meta meta;

    private String name;

    public CloudEntity() {
    }

    public CloudEntity(Meta meta) {
        this(meta, null);
    }

    public CloudEntity(Meta meta, String name) {
        if (meta != null) {
            this.meta = meta;
        } else {
            this.meta = Meta.defaultMeta();
        }
        this.name = name;
    }

    public Meta getMeta() {
        return meta;
    }

    public void setMeta(Meta meta) {
        this.meta = meta;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + ": (" +
                (meta == null || meta.getGuid() == null ? "-" : meta.getGuid()) + ") " +
                getName();
    }

    public static class Meta {

        private Date created;

        private UUID guid;

        private Date updated;

        private String url;

        public Meta(UUID guid, Date created, Date updated) {
            this.guid = guid;
            this.created = created;
            this.updated = updated;
        }

        public Meta(UUID guid, Date created, Date updated, String url) {
            this.guid = guid;
            this.created = created;
            this.updated = updated;
            this.url = url;
        }

        public static Meta defaultMeta() {
            return new Meta(null, null, null);
        }

        public Date getCreated() {
            return created;
        }

        public UUID getGuid() {
            return guid;
        }

        public Date getUpdated() {
            return updated;
        }

        public String getUrl() {
            return url;
        }
    }
}
File
CloudEntity.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Class declaration
Method declaration
Chunk
Conflicting content
public class CloudServicePlan extends CloudEntity {

<<<<<<< HEAD
	private boolean free;
	private boolean _public;
	private String description;
	private String extra;
	private String uniqueId;
	
	private CloudServiceOffering serviceOffering;

	public CloudServicePlan() {
	}

	public CloudServicePlan(Meta meta, String name) {
		super(meta, name);
	}

	public CloudServicePlan(Meta meta, String name, String description, boolean free,
							boolean _public, String extra, String uniqueId) {
		super(meta, name);
		this.description = description;
		this.free = free;
		this._public = _public;
		this.extra = extra;
		this.uniqueId = uniqueId;
	}

	public boolean isFree() {
		return this.free;
	}
	
	public boolean isPublic() {
		return this._public;
	}
	
	public String getDescription() {
		return description;
	}
	
	public String getExtra() {
		return extra;
	}
	
	public String getUniqueId() {
		return uniqueId;
	}
	
	public CloudServiceOffering getServiceOffering() {
		return serviceOffering;
	}

	public void setServiceOffering(CloudServiceOffering serviceOffering) {
		this.serviceOffering = serviceOffering;
	}
=======
    private boolean _public;

    private String description;

    private String extra;

    private boolean free;

    private CloudServiceOffering serviceOffering;

    private String uniqueId;

    public CloudServicePlan() {
    }

    public CloudServicePlan(Meta meta, String name, String description, boolean free,
                            boolean _public, String extra, String uniqueId,
                            CloudServiceOffering serviceOffering) {
        super(meta, name);
        this.description = description;
        this.free = free;
        this._public = _public;
        this.extra = extra;
        this.uniqueId = uniqueId;
        this.serviceOffering = serviceOffering;
    }

    public String getDescription() {
        return description;
    }

    public String getExtra() {
        return extra;
    }

    public CloudServiceOffering getServiceOffering() {
        return serviceOffering;
    }

    public void setServiceOffering(CloudServiceOffering serviceOffering) {
        this.serviceOffering = serviceOffering;
    }

    public String getUniqueId() {
        return uniqueId;
    }

    public boolean isFree() {
        return this.free;
    }

    public boolean isPublic() {
        return this._public;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
public class CloudServicePlan extends CloudEntity {

    private boolean _public;

    private String description;

    private String extra;

    private boolean free;

    private CloudServiceOffering serviceOffering;

    private String uniqueId;

    public CloudServicePlan() {
    }

    public CloudServicePlan(Meta meta, String name) {
        super(meta, name);
    }

    public CloudServicePlan(Meta meta, String name, String description, boolean free,
                            boolean _public, String extra, String uniqueId) {
        super(meta, name);
        this.description = description;
        this.free = free;
        this._public = _public;
        this.extra = extra;
        this.uniqueId = uniqueId;
    }

    public String getDescription() {
        return description;
    }

    public String getExtra() {
        return extra;
    }

    public CloudServiceOffering getServiceOffering() {
        return serviceOffering;
    }

    public void setServiceOffering(CloudServiceOffering serviceOffering) {
        this.serviceOffering = serviceOffering;
    }

    public String getUniqueId() {
        return uniqueId;
    }

    public boolean isFree() {
        return this.free;
    }

    public boolean isPublic() {
        return this._public;
    }
}
File
CloudServicePlan.java
Developer's decision
Combination
Kind of conflict
Attribute
Method declaration
Chunk
Conflicting content
package org.cloudfoundry.client.lib.domain;

<<<<<<< HEAD
public class CloudStack  extends CloudEntity {
	private String description;

	public CloudStack(Meta meta, String name, String description) {
		super(meta, name);
		this.description = description;
	}

	public String getDescription() {
		return description;
	}
=======
public class CloudStack extends CloudEntity {

    private String description;

    public CloudStack(Meta meta, String name, String description) {
        setMeta(meta);
        setName(name);
        this.description = description;
    }

    public String getDescription() {
        return description;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
package org.cloudfoundry.client.lib.domain;

public class CloudStack extends CloudEntity {

    private String description;

    public CloudStack(Meta meta, String name, String description) {
        super(meta, name);
        this.description = description;
    }

    public String getDescription() {
        return description;
    }
}
File
CloudStack.java
Developer's decision
Version 1
Kind of conflict
Attribute
Class signature
Method declaration
Chunk
Conflicting content
	}

public class InstanceStats {

<<<<<<< HEAD
	public static class Usage {

		private double cpu;
		private long disk;
		private long mem;
		private Date time;

		public Usage(Map attributes) {
			this.time = parseDate(parse(String.class, attributes.get("time")));
			this.cpu = parse(Double.class, attributes.get("cpu"));
			this.disk = parse(Long.class, attributes.get("disk"));
			this.mem = parse(Long.class, attributes.get("mem"));
		}

		public double getCpu() {
			return cpu;
		}

		public long getDisk() {
			return disk;
		}

		public long getMem() {
			return mem;
		}

		public Date getTime() {
			return time;
		}
	}

	private int cores;
	private long diskQuota;
	private int fdsQuota;
	private String host;
	private String id;
	private long memQuota;
	private String name;
	private int port;
	private InstanceState state;
	private double uptime;
	private List uris;
	private Usage usage;

	@SuppressWarnings("unchecked")
	public InstanceStats(String id, Map attributes) {
		this.id = id;
		String instanceState = parse(String.class, attributes.get("state"));
		this.state = InstanceState.valueOfWithDefault(instanceState);
		Map stats = parse(Map.class, attributes.get("stats"));
		if (stats != null) {
			this.cores = parse(Integer.class, stats.get("cores"));
			this.name = parse(String.class, stats.get("name"));
			Map usageValue = parse(Map.class,
					stats.get("usage"));
			if (usageValue != null) {
				this.usage = new Usage(usageValue);
			}
			this.diskQuota = parse(Long.class, stats.get("disk_quota"));
			this.port = parse(Integer.class, stats.get("port"));
			this.memQuota = parse(Long.class, stats.get("mem_quota"));
			List statsValue = parse(List.class, stats.get("uris"));
			if (statsValue != null) {
				this.uris = Collections.unmodifiableList(statsValue);
			}
			this.fdsQuota = parse(Integer.class, stats.get("fds_quota"));
			this.host = parse(String.class, stats.get("host"));
			this.uptime = parse(Double.class, stats.get("uptime"));
		}
	}

	private static Date parseDate(String date) {
		// dates will be of the form 2011-04-07 09:11:50 +0000
		try {
			return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss ZZZZZ").parse(date);
		}
		catch (ParseException e) {
			// TODO - not sure how best to handle this error
			return null;
		}
	}

	public int getCores() {
		return cores;
	}

	public long getDiskQuota() {
		return diskQuota;
	}

	public int getFdsQuota() {
		return fdsQuota;
	}

	public String getHost() {
		return host;
	}

	public String getId() {
		return id;

	public long getMemQuota() {
		return memQuota;
	}

	public String getName() {
		return name;
	}

	public int getPort() {
		return port;
	}

	public InstanceState getState() {
		return state;
	}

	public double getUptime() {
		return uptime;
	}

	public List getUris() {
		return uris;
	}

	public Usage getUsage() {
		return usage;
	}
=======
    private int cores;

    private long diskQuota;

    private int fdsQuota;

    private String host;

    private String id;

    private long memQuota;

    private String name;

    private int port;

    private InstanceState state;

    private double uptime;

    private List uris;

    private Usage usage;

    @SuppressWarnings("unchecked")
    public InstanceStats(String id, Map attributes) {
        this.id = id;
        String instanceState = parse(String.class, attributes.get("state"));
        public Date getTime() {
        this.state = InstanceState.valueOfWithDefault(instanceState);
        Map stats = parse(Map.class, attributes.get("stats"));
        if (stats != null) {
            this.cores = parse(Integer.class, stats.get("cores"));
            this.name = parse(String.class, stats.get("name"));
            Map usageValue = parse(Map.class,
                    stats.get("usage"));
            if (usageValue != null) {
                this.usage = new Usage(usageValue);
            }
            this.diskQuota = parse(Long.class, stats.get("disk_quota"));
            this.port = parse(Integer.class, stats.get("port"));
            this.memQuota = parse(Long.class, stats.get("mem_quota"));
            List statsValue = parse(List.class, stats.get("uris"));
            if (statsValue != null) {
                this.uris = Collections.unmodifiableList(statsValue);
            }
            this.fdsQuota = parse(Integer.class, stats.get("fds_quota"));
            this.host = parse(String.class, stats.get("host"));
            this.uptime = parse(Double.class, stats.get("uptime"));
        }
    }

    private static Date parseDate(String date) {
        // dates will be of the form 2011-04-07 09:11:50 +0000
        try {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss ZZZZZ").parse(date);
        } catch (ParseException e) {
            // TODO - not sure how best to handle this error
            return null;
        }
    }

    public int getCores() {
        return cores;
    }

    public long getDiskQuota() {
        return diskQuota;
    }

    public int getFdsQuota() {
        return fdsQuota;
    }

    public String getHost() {
        return host;
    }

    public String getId() {
        return id;
    }

    public long getMemQuota() {
        return memQuota;
    }

    public String getName() {
        return name;
    }

    public int getPort() {
        return port;
    }

    public InstanceState getState() {
        return state;
    }

    public double getUptime() {
        return uptime;
    }

    public List getUris() {
        return uris;
    }

    public Usage getUsage() {
        return usage;
    }

    public static class Usage {

        private double cpu;

        private int disk;

        private int mem;

        private Date time;

        public Usage(Map attributes) {
            this.time = parseDate(parse(String.class, attributes.get("time")));
            this.cpu = parse(Double.class, attributes.get("cpu"));
            this.disk = parse(Integer.class, attributes.get("disk"));
            this.mem = parse(Integer.class, attributes.get("mem"));
        }

        public double getCpu() {
            return cpu;
        }

        public int getDisk() {
            return disk;
        }

        public int getMem() {
            return mem;
        }
            return time;
        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
public class InstanceStats {

    private int cores;

    private long diskQuota;

    private int fdsQuota;

    private String host;

    private String id;

    private long memQuota;

    private String name;

    private int port;

    private InstanceState state;

    private double uptime;

    private List uris;

    private Usage usage;

    @SuppressWarnings("unchecked")
    public InstanceStats(String id, Map attributes) {
        this.id = id;
        String instanceState = parse(String.class, attributes.get("state"));
        this.state = InstanceState.valueOfWithDefault(instanceState);
        Map stats = parse(Map.class, attributes.get("stats"));
        if (stats != null) {
            this.cores = parse(Integer.class, stats.get("cores"));
            this.name = parse(String.class, stats.get("name"));
            Map usageValue = parse(Map.class,
                    stats.get("usage"));
            if (usageValue != null) {
                this.usage = new Usage(usageValue);
            }
            this.diskQuota = parse(Long.class, stats.get("disk_quota"));
            this.port = parse(Integer.class, stats.get("port"));
            this.memQuota = parse(Long.class, stats.get("mem_quota"));
            List statsValue = parse(List.class, stats.get("uris"));
            if (statsValue != null) {
                this.uris = Collections.unmodifiableList(statsValue);
            }
            this.fdsQuota = parse(Integer.class, stats.get("fds_quota"));
            this.host = parse(String.class, stats.get("host"));
            this.uptime = parse(Double.class, stats.get("uptime"));
        }
    }

    private static Date parseDate(String date) {
        // dates will be of the form 2011-04-07 09:11:50 +0000
        try {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss ZZZZZ").parse(date);
        } catch (ParseException e) {
            // TODO - not sure how best to handle this error
            return null;
        }
    }

    public int getCores() {
        return cores;
    }

    public long getDiskQuota() {
        return diskQuota;
    }

    public int getFdsQuota() {
        return fdsQuota;
    }

    public String getHost() {

        return host;
    }

    public String getId() {
        return id;
    }

    public long getMemQuota() {
        return memQuota;
    }

    public String getName() {
        return name;
    }

    public int getPort() {
        return port;
    }

    public InstanceState getState() {
        return state;
    }

    public double getUptime() {
        return uptime;
    }

    public List getUris() {
        return uris;
    }

    public Usage getUsage() {
        return usage;
    }

    public static class Usage {

        private double cpu;

        private long disk;
        private long mem;

        private Date time;

        public Usage(Map attributes) {
            this.time = parseDate(parse(String.class, attributes.get("time")));
            this.cpu = parse(Double.class, attributes.get("cpu"));
            this.disk = parse(Long.class, attributes.get("disk"));
            this.mem = parse(Long.class, attributes.get("mem"));
        }

        public double getCpu() {
            return cpu;
        }

        public long getDisk() {
            return disk;
        }

        public long getMem() {
            return mem;
        }

        public Date getTime() {
            return time;
        }
    }
}
File
InstanceStats.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Class declaration
Method declaration
Chunk
Conflicting content
 * @author Scott Frederick
 */
public class Staging {
<<<<<<< HEAD
	private String command;
	private String buildpackUrl;
	private String detectedBuildpack;
	private String stack;
	private Integer healthCheckTimeout;

	/**
	 * Default staging: No command, default buildpack
	 */
	public Staging() {
		
	}
	
	/**
	 *
	 * @param command the application command; may be null
	 * @param buildpackUrl a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may be null
	 */
	public Staging(String command, String buildpackUrl) {
		this.command = command;
		this.buildpackUrl = buildpackUrl;
	}
	
	/**
	 *
	 * @param command the application command; may be null
	 * @param buildpackUrl a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may be null
	 * @param detectedBuildpack raw, free-form information regarding a detected buildpack. It is a read-only property, and should not be set except when parsing a response. May be null.
	 */
	public Staging(String command, String buildpackUrl, String detectedBuildpack) {
		this(command, buildpackUrl);
		this.detectedBuildpack = detectedBuildpack;
	}

	/**
	 *
	 * @param command the application command; may be null
	 * @param buildpackUrl a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may be null
	 * @param stack the stack to use when staging the application; may be null
	 * @param healthCheckTimeout the amount of time the platform should wait when verifying that an app started; may be null
	 */
	public Staging(String command, String buildpackUrl, String stack, Integer healthCheckTimeout) {
		this(command, buildpackUrl);
		this.stack = stack;
		this.healthCheckTimeout = healthCheckTimeout;
	}
	
	/**
	 *
	 * @param command the application command; may be null
	 * @param buildpackUrl a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may be null
	 * @param stack the stack to use when staging the application; may be null
	 * @param healthCheckTimeout the amount of time the platform should wait when verifying that an app started; may be null
	 * @param detectedBuildpack raw, free-form information regarding a detected buildpack. It is a read-only property, and should not be set except when parsing a response. May be null.
	 */
	public Staging(String command, String buildpackUrl, String stack, Integer healthCheckTimeout, String detectedBuildpack) {
		this(command, buildpackUrl, stack, healthCheckTimeout);
		this.detectedBuildpack = detectedBuildpack;
	}
=======

    private String buildpackUrl;

    private String command;

    private Integer healthCheckTimeout;

    private String stack;

    /**
     * Default staging: No command, default buildpack
     */
    public Staging() {

    }

    /**
     * @param command      the application command; may be null
     * @param buildpackUrl a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may be
     *                     null
     */
    public Staging(String command, String buildpackUrl) {
        this.command = command;
        this.buildpackUrl = buildpackUrl;
    }

    /**
     * @param command            the application command; may be null
     * @param buildpackUrl       a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may
     *                           be null
     * @param stack              the stack to use when staging the application; may be null
     * @param healthCheckTimeout the amount of time the platform should wait when verifying that an app started; may be
     *                           null
     */
    public Staging(String command, String buildpackUrl, String stack, Integer healthCheckTimeout) {
        this(command, buildpackUrl);
        this.stack = stack;
        this.healthCheckTimeout = healthCheckTimeout;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    /**
     * @return The buildpack url, or null to use the default buildpack detected based on application content
Solution content
 * @author Scott Frederick
 */
public class Staging {

    private String buildpackUrl;

    private String command;

    private String detectedBuildpack;

    private Integer healthCheckTimeout;

    private String stack;

    /**
     * Default staging: No command, default buildpack
     */
    public Staging() {

    }

    /**
     * @param command      the application command; may be null
     * @param buildpackUrl a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may be
     *                     null
     */
    public Staging(String command, String buildpackUrl) {
        this.command = command;
        this.buildpackUrl = buildpackUrl;
    }

    /**
     * @param command           the application command; may be null
     * @param buildpackUrl      a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may be
     *                          null
     * @param detectedBuildpack raw, free-form information regarding a detected buildpack. It is a read-only property,
     *                          and should not be set except when parsing a response. May be null.
     */
    public Staging(String command, String buildpackUrl, String detectedBuildpack) {
        this(command, buildpackUrl);
        this.detectedBuildpack = detectedBuildpack;
    }

    /**
     * @param command            the application command; may be null
     * @param buildpackUrl       a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may
     *                           be null
     * @param stack              the stack to use when staging the application; may be null
     * @param healthCheckTimeout the amount of time the platform should wait when verifying that an app started; may be
     *                           null
     */
    public Staging(String command, String buildpackUrl, String stack, Integer healthCheckTimeout) {
        this(command, buildpackUrl);
        this.stack = stack;
        this.healthCheckTimeout = healthCheckTimeout;
    }

    /**
     * @param command            the application command; may be null
     * @param buildpackUrl       a custom buildpack url (e.g. https://github.com/cloudfoundry/java-buildpack.git); may
     *                           be null
     * @param stack              the stack to use when staging the application; may be null
     * @param healthCheckTimeout the amount of time the platform should wait when verifying that an app started; may be
     *                           null
     * @param detectedBuildpack  raw, free-form information regarding a detected buildpack. It is a read-only property,
     *                           and should not be set except when parsing a response. May be null.
     */
    public Staging(String command, String buildpackUrl, String stack, Integer healthCheckTimeout, String
            detectedBuildpack) {
        this(command, buildpackUrl, stack, healthCheckTimeout);
        this.detectedBuildpack = detectedBuildpack;
    }

    /**
     * @return The buildpack url, or null to use the default buildpack detected based on application content
File
Staging.java
Developer's decision
Manual
Kind of conflict
Attribute
Comment
Method declaration
Chunk
Conflicting content
        return command;
    }

<<<<<<< HEAD
	/**
	 *
	 * @return Raw, free-form information regarding a detected buildpack, or
	 *         null if no detected buildpack was resolved. For example, if the
	 *         application is stopped, the detected buildpack may be null.
	 */
	public String getDetectedBuildpack() {
		return detectedBuildpack;
	}
	
	/**
	 *
	 * @return the stack to use when staging the application, or null to use the default stack
	 */
	public String getStack() {
		return stack;
	}
=======
    /**
     * @return the health check timeout value
     */
    public Integer getHealthCheckTimeout() {
        return healthCheckTimeout;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    /**
     * @return the stack to use when staging the application, or null to use the default stack
Solution content
        return command;
    }

    /**
     * @return Raw, free-form information regarding a detected buildpack, or null if no detected buildpack was resolved.
     * For example, if the application is stopped, the detected buildpack may be null.
     */
    public String getDetectedBuildpack() {
        return detectedBuildpack;
    }

    /**
     * @return the health check timeout value
     */
    public Integer getHealthCheckTimeout() {
        return healthCheckTimeout;
    }

    /**
     * @return the stack to use when staging the application, or null to use the default stack
File
Staging.java
Developer's decision
Manual
Kind of conflict
Comment
Method declaration
Chunk
Conflicting content
package org.cloudfoundry.client.lib.oauth2;

<<<<<<< HEAD
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

=======
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
import org.cloudfoundry.client.lib.CloudCredentials;
import org.cloudfoundry.client.lib.CloudFoundryException;
import org.cloudfoundry.client.lib.util.JsonUtil;
Solution content
package org.cloudfoundry.client.lib.oauth2;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.cloudfoundry.client.lib.CloudCredentials;
import org.cloudfoundry.client.lib.CloudFoundryException;
import org.cloudfoundry.client.lib.util.JsonUtil;
File
OauthClient.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content
 */
public class OauthClient {

<<<<<<< HEAD
	private static final String AUTHORIZATION_HEADER_KEY = "Authorization";

	private URL authorizationUrl;

	private RestTemplate restTemplate;

	private OAuth2AccessToken token;
	private CloudCredentials credentials;

	public OauthClient(URL authorizationUrl, RestTemplate restTemplate) {
		this.authorizationUrl = authorizationUrl;
		this.restTemplate = restTemplate;
	}

	public void init(CloudCredentials credentials) {
		if (credentials != null) {
			this.credentials = credentials;

			if (credentials.getToken() != null) {
				this.token = credentials.getToken();
			} else {
				this.token = createToken(credentials.getEmail(), credentials.getPassword(),
						credentials.getClientId(), credentials.getClientSecret());
			}
		}
	}

	public void clear() {
		this.token = null;
		this.credentials = null;
	}

	public OAuth2AccessToken getToken() {
		if (token == null) {
			return null;
		}

		if(this.credentials.isRefreshable()) {
			if (token.getExpiresIn() < 50) { // 50 seconds before expiration? Then refresh it.
				token = refreshToken(token, credentials.getEmail(), credentials.getPassword(),
						credentials.getClientId(), credentials.getClientSecret());
			}
		}

		return token;
	}

	public String getAuthorizationHeader() {
		OAuth2AccessToken accessToken = getToken();
		if (accessToken != null) {
			return accessToken.getTokenType() + " " + accessToken.getValue();
		}
		return null;
	}

	private OAuth2AccessToken createToken(String username, String password, String clientId, String clientSecret) {
		OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
		AccessTokenRequest request = createAccessTokenRequest(username, password);

		ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
		try {
			return provider.obtainAccessToken(resource, request);
		}
		catch (OAuth2AccessDeniedException oauthEx) {
			HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
			CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage());
			cfEx.setDescription(oauthEx.getSummary());
			throw cfEx;
		}
	}

	private OAuth2AccessToken refreshToken(OAuth2AccessToken currentToken, String username, String password, String clientId, String clientSecret) {
		OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
		AccessTokenRequest request = createAccessTokenRequest(username, password);

		ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();

		return provider.refreshAccessToken(resource, currentToken.getRefreshToken(), request);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void changePassword(String oldPassword, String newPassword) {
		HttpHeaders headers = new HttpHeaders();
		headers.add(AUTHORIZATION_HEADER_KEY, token.getTokenType() + " " + token.getValue());
		HttpEntity info = new HttpEntity(headers);
		ResponseEntity response = restTemplate.exchange(authorizationUrl + "/userinfo", HttpMethod.GET, info, String.class);
		Map responseMap = JsonUtil.convertJsonToMap(response.getBody());
		String userId = (String) responseMap.get("user_id");
		Map body = new HashMap();
		body.put("schemas", new String[] {"urn:scim:schemas:core:1.0"});
		body.put("password", newPassword);
		body.put("oldPassword", oldPassword);
		HttpEntity httpEntity = new HttpEntity(body, headers);
		restTemplate.put(authorizationUrl + "/User/{id}/password", httpEntity, userId);
	}

	protected ResourceOwnerPasswordAccessTokenProvider createResourceOwnerPasswordAccessTokenProvider() {
		ResourceOwnerPasswordAccessTokenProvider resourceOwnerPasswordAccessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
		resourceOwnerPasswordAccessTokenProvider.setRequestFactory(restTemplate.getRequestFactory()); //copy the http proxy along
		return resourceOwnerPasswordAccessTokenProvider;
	}

	private AccessTokenRequest createAccessTokenRequest(String username, String password) {
		AccessTokenRequest request = new DefaultAccessTokenRequest();
		return request;
	}

	private OAuth2ProtectedResourceDetails getResourceDetails(String username, String password, String clientId, String clientSecret) {
		ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
		resource.setUsername(username);
		resource.setPassword(password);

		resource.setClientId(clientId);
		resource.setClientSecret(clientSecret);
		resource.setId(clientId);
		resource.setClientAuthenticationScheme(AuthenticationScheme.header);
		resource.setAccessTokenUri(authorizationUrl + "/oauth/token");

		return resource;
	}
=======
    private static final String AUTHORIZATION_HEADER_KEY = "Authorization";

    private URL authorizationUrl;

    private CloudCredentials credentials;

    private RestTemplate restTemplate;

    private OAuth2AccessToken token;


    public OauthClient(URL authorizationUrl, RestTemplate restTemplate) {
        this.authorizationUrl = authorizationUrl;
        this.restTemplate = restTemplate;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public void changePassword(String oldPassword, String newPassword) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(AUTHORIZATION_HEADER_KEY, token.getTokenType() + " " + token.getValue());
        HttpEntity info = new HttpEntity(headers);
        ResponseEntity response = restTemplate.exchange(authorizationUrl + "/userinfo", HttpMethod.GET, info,
                String.class);
        Map responseMap = JsonUtil.convertJsonToMap(response.getBody());
        String userId = (String) responseMap.get("user_id");
        Map body = new HashMap();
        body.put("schemas", new String[]{"urn:scim:schemas:core:1.0"});
        body.put("password", newPassword);
        body.put("oldPassword", oldPassword);
        HttpEntity httpEntity = new HttpEntity(body, headers);
        restTemplate.put(authorizationUrl + "/User/{id}/password", httpEntity, userId);
    }

    public void clear() {
        this.token = null;
        this.credentials = null;
    }

    public String getAuthorizationHeader() {
        OAuth2AccessToken accessToken = getToken();
        if (accessToken != null) {
            return accessToken.getTokenType() + " " + accessToken.getValue();
        }
        return null;
    }

    public OAuth2AccessToken getToken() {
        if (token == null) {
            return null;
        }

        if (token.getExpiresIn() < 50) { // 50 seconds before expiration? Then refresh it.
            token = refreshToken(token, credentials.getEmail(), credentials.getPassword(),
                    credentials.getClientId(), credentials.getClientSecret());
        }

        return token;
    }

    public void init(CloudCredentials credentials) {
        if (credentials != null) {
            this.credentials = credentials;

            if (credentials.getToken() != null) {
                this.token = credentials.getToken();
            } else {
                this.token = createToken(credentials.getEmail(), credentials.getPassword(),
                        credentials.getClientId(), credentials.getClientSecret());
            }
        }
    }

    protected ResourceOwnerPasswordAccessTokenProvider createResourceOwnerPasswordAccessTokenProvider() {
        ResourceOwnerPasswordAccessTokenProvider resourceOwnerPasswordAccessTokenProvider = new
                ResourceOwnerPasswordAccessTokenProvider();
        resourceOwnerPasswordAccessTokenProvider.setRequestFactory(restTemplate.getRequestFactory()); //copy the http
        // proxy along
        return resourceOwnerPasswordAccessTokenProvider;
    }

    private AccessTokenRequest createAccessTokenRequest(String username, String password) {
        AccessTokenRequest request = new DefaultAccessTokenRequest();
        return request;
    }

    private OAuth2AccessToken createToken(String username, String password, String clientId, String clientSecret) {
        OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
        AccessTokenRequest request = createAccessTokenRequest(username, password);

        ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
        try {
            return provider.obtainAccessToken(resource, request);
        } catch (OAuth2AccessDeniedException oauthEx) {
            HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
            CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage());
            cfEx.setDescription(oauthEx.getSummary());
            throw cfEx;
        }
    }
    private OAuth2ProtectedResourceDetails getResourceDetails(String username, String password, String clientId, String clientSecret) {
        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setUsername(username);
        resource.setPassword(password);

        resource.setClientId(clientId);
        resource.setClientSecret(clientSecret);
        resource.setId(clientId);
        resource.setClientAuthenticationScheme(AuthenticationScheme.header);
        resource.setAccessTokenUri(authorizationUrl + "/oauth/token");

        return resource;
    }

    private OAuth2AccessToken refreshToken(OAuth2AccessToken currentToken, String username, String password, String
            clientId, String clientSecret) {
        OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
        AccessTokenRequest request = createAccessTokenRequest(username, password);

        ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();

        return provider.refreshAccessToken(resource, currentToken.getRefreshToken(), request);
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
 */
public class OauthClient {

	private static final String AUTHORIZATION_HEADER_KEY = "Authorization";

	private URL authorizationUrl;

	private RestTemplate restTemplate;

	private OAuth2AccessToken token;
	private CloudCredentials credentials;

	public OauthClient(URL authorizationUrl, RestTemplate restTemplate) {
		this.authorizationUrl = authorizationUrl;
		this.restTemplate = restTemplate;
	}

	public void init(CloudCredentials credentials) {
		if (credentials != null) {
			this.credentials = credentials;

			if (credentials.getToken() != null) {
				this.token = credentials.getToken();
			} else {
				this.token = createToken(credentials.getEmail(), credentials.getPassword(),
						credentials.getClientId(), credentials.getClientSecret());
			}
		}
	}

	public void clear() {
		this.token = null;
		this.credentials = null;
	}

	public OAuth2AccessToken getToken() {
		if (token == null) {
			return null;
		}

		if(this.credentials.isRefreshable()) {
			if (token.getExpiresIn() < 50) { // 50 seconds before expiration? Then refresh it.
				token = refreshToken(token, credentials.getEmail(), credentials.getPassword(),
						credentials.getClientId(), credentials.getClientSecret());
			}
		}

		return token;
	}

	public String getAuthorizationHeader() {
		OAuth2AccessToken accessToken = getToken();
		if (accessToken != null) {
			return accessToken.getTokenType() + " " + accessToken.getValue();
		}
		return null;
	}

	private OAuth2AccessToken createToken(String username, String password, String clientId, String clientSecret) {
		OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
		AccessTokenRequest request = createAccessTokenRequest(username, password);

		ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
		try {
			return provider.obtainAccessToken(resource, request);
		}
		catch (OAuth2AccessDeniedException oauthEx) {
			HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
			CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage());
			cfEx.setDescription(oauthEx.getSummary());
			throw cfEx;
		}
	}

	private OAuth2AccessToken refreshToken(OAuth2AccessToken currentToken, String username, String password, String clientId, String clientSecret) {
		OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
		AccessTokenRequest request = createAccessTokenRequest(username, password);

		ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();

		return provider.refreshAccessToken(resource, currentToken.getRefreshToken(), request);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void changePassword(String oldPassword, String newPassword) {
		HttpHeaders headers = new HttpHeaders();
		headers.add(AUTHORIZATION_HEADER_KEY, token.getTokenType() + " " + token.getValue());
		HttpEntity info = new HttpEntity(headers);
		ResponseEntity response = restTemplate.exchange(authorizationUrl + "/userinfo", HttpMethod.GET, info, String.class);
		Map responseMap = JsonUtil.convertJsonToMap(response.getBody());
		String userId = (String) responseMap.get("user_id");
		Map body = new HashMap();
		body.put("schemas", new String[] {"urn:scim:schemas:core:1.0"});
		body.put("password", newPassword);
		body.put("oldPassword", oldPassword);
		HttpEntity httpEntity = new HttpEntity(body, headers);
		restTemplate.put(authorizationUrl + "/User/{id}/password", httpEntity, userId);
	}

	protected ResourceOwnerPasswordAccessTokenProvider createResourceOwnerPasswordAccessTokenProvider() {
		ResourceOwnerPasswordAccessTokenProvider resourceOwnerPasswordAccessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
		resourceOwnerPasswordAccessTokenProvider.setRequestFactory(restTemplate.getRequestFactory()); //copy the http proxy along
		return resourceOwnerPasswordAccessTokenProvider;
	}

	private AccessTokenRequest createAccessTokenRequest(String username, String password) {
		AccessTokenRequest request = new DefaultAccessTokenRequest();
		return request;
	}

	private OAuth2ProtectedResourceDetails getResourceDetails(String username, String password, String clientId, String clientSecret) {
		ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
		resource.setUsername(username);
		resource.setPassword(password);

		resource.setClientId(clientId);
		resource.setClientSecret(clientSecret);
		resource.setId(clientId);
		resource.setClientAuthenticationScheme(AuthenticationScheme.header);
		resource.setAccessTokenUri(authorizationUrl + "/oauth/token");

		return resource;
	}
}
File
OauthClient.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Method declaration
Chunk
Conflicting content
    void deleteDomain(String domainName);

<<<<<<< HEAD
	CloudServiceInstance getServiceInstance(String serviceName);

	void deleteService(String service);
=======
    List deleteOrphanedRoutes();
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    void deleteQuota(String quotaName);
Solution content
    void deleteDomain(String domainName);

    List deleteOrphanedRoutes();

    void deleteQuota(String quotaName);
File
CloudControllerClient.java
Developer's decision
Version 2
Kind of conflict
Method interface
Chunk
Conflicting content
    InstancesInfo getApplicationInstances(CloudApplication app);

<<<<<<< HEAD
	CloudApplication getApplication(String appName);

	CloudApplication getApplication(UUID appGuid);
=======
    ApplicationStats getApplicationStats(String appName);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    List getApplications();
Solution content
    List getApplicationEvents(String appName);

    InstancesInfo getApplicationInstances(String appName);

    InstancesInfo getApplicationInstances(CloudApplication app);

    ApplicationStats getApplicationStats(String appName);

    List getApplications();
File
CloudControllerClient.java
Developer's decision
Manual
Kind of conflict
Method interface
Chunk
Conflicting content
    List getApplications();

<<<<<<< HEAD
	Map getApplicationEnvironment(UUID appGuid);

	Map getApplicationEnvironment(String appName);

    void createApplication(String appName, Staging staging, Integer memory, List uris,
	                       List serviceNames);
=======
    URL getCloudControllerUrl();
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    Map getCrashLogs(String appName);
Solution content
    List getApplications();

    URL getCloudControllerUrl();

    Map getCrashLogs(String appName);
File
CloudControllerClient.java
Developer's decision
Version 2
Kind of conflict
Method interface
Chunk
Conflicting content
    List getSharedDomains();

<<<<<<< HEAD
	List getEvents();

	List getApplicationEvents(String appName);

	Map getLogs(String appName);
=======
    CloudSpace getSpace(String spaceName);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    List getSpaces();
Solution content
    List getSharedDomains();

    // Space management

    CloudSpace getSpace(String spaceName);

    List getSpaceAuditors(String orgName, String spaceName);

    List getSpaceDevelopers(String orgName, String spaceName);

    // Domains and routes management

    List getSpaceManagers(String orgName, String spaceName);

    List getSpaces();
File
CloudControllerClient.java
Developer's decision
Manual
Kind of conflict
Method interface
Chunk
Conflicting content
    void setQuotaToOrg(String orgName, String quotaName);

<<<<<<< HEAD
	// Space management

	void createSpace(String spaceName);

	CloudSpace getSpace(String spaceName);

	void deleteSpace(String spaceName);

	// Domains and routes management
=======
    void setResponseErrorHandler(ResponseErrorHandler errorHandler);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    StartingInfo startApplication(String appName);
Solution content
    void setQuotaToOrg(String orgName, String quotaName);

    void setResponseErrorHandler(ResponseErrorHandler errorHandler);

    StartingInfo startApplication(String appName);
File
CloudControllerClient.java
Developer's decision
Version 2
Kind of conflict
Comment
Method interface
Chunk
Conflicting content
=======
    void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback callback)
            throws IOException;

<<<<<<< HEAD
	void setQuotaToOrg(String orgName, String quotaName);

	List getSpaceManagers(String orgName, String spaceName);

	List getSpaceDevelopers(String orgName, String spaceName);

	List getSpaceAuditors(String orgName, String spaceName);

	void associateManagerWithSpace(String orgName, String spaceName, String userGuid);

	void associateDeveloperWithSpace(String orgName, String spaceName, String userGuid);

	void associateAuditorWithSpace(String orgName, String spaceName, String userGuid);

	// Security Group Operations

	List getSecurityGroups();

	CloudSecurityGroup getSecurityGroup(String securityGroupName);

	void createSecurityGroup(CloudSecurityGroup securityGroup);

	void createSecurityGroup(String name, InputStream jsonRulesFile);

	void updateSecurityGroup(CloudSecurityGroup securityGroup);

	void updateSecurityGroup(String name, InputStream jsonRulesFile);

	void deleteSecurityGroup(String securityGroupName);

	List getStagingSecurityGroups();

	void bindStagingSecurityGroup(String securityGroupName);

	void unbindStagingSecurityGroup(String securityGroupName);

	List getRunningSecurityGroups();

	void bindRunningSecurityGroup(String securityGroupName);

	void unbindRunningSecurityGroup(String securityGroupName);

	List getSpacesBoundToSecurityGroup(String securityGroupName);

	void bindSecurityGroup(String orgName, String spaceName, String securityGroupName);

	void unbindSecurityGroup(String orgName, String spaceName, String securityGroupName);

	Map getOrganizationUsers(String orgName);
    void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws
            IOException;
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
    void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback callback)
            throws IOException;

    void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback) throws
            IOException;
}
File
CloudControllerClient.java
Developer's decision
Version 2
Kind of conflict
Comment
Method interface
Chunk
Conflicting content
 */
public class CloudControllerClientImpl implements CloudControllerClient {

<<<<<<< HEAD
	private static final String AUTHORIZATION_HEADER_KEY = "Authorization";
	private static final String PROXY_USER_HEADER_KEY = "Proxy-User";

	private static final String LOGS_LOCATION = "logs";
	private static final long JOB_POLLING_PERIOD = TimeUnit.SECONDS.toMillis(5);
	private static final long JOB_TIMEOUT = TimeUnit.MINUTES.toMillis(3);

	private OauthClient oauthClient;

	private CloudSpace sessionSpace;

	private CloudEntityResourceMapper resourceMapper = new CloudEntityResourceMapper();

	private RestTemplate restTemplate;

	private URL cloudControllerUrl;

	private LoggregatorClient loggregatorClient;

	protected CloudCredentials cloudCredentials;

	private final Log logger;

	/**
	 * Only for unit tests. This works around the fact that the initialize method is called within the constructor and
	 * hence can not be overloaded, making it impossible to write unit tests that don't trigger network calls.
	 */
	protected CloudControllerClientImpl() {
		logger = LogFactory.getLog(getClass().getName());
	}

	public CloudControllerClientImpl(URL cloudControllerUrl, RestTemplate restTemplate,
	                                 OauthClient oauthClient, LoggregatorClient loggregatorClient,
	                                 CloudCredentials cloudCredentials, CloudSpace sessionSpace) {
		logger = LogFactory.getLog(getClass().getName());
		initialize(cloudControllerUrl, restTemplate, oauthClient, loggregatorClient, cloudCredentials);

		this.sessionSpace = sessionSpace;
	}

	public CloudControllerClientImpl(URL cloudControllerUrl, RestTemplate restTemplate,
	                                 OauthClient oauthClient, LoggregatorClient loggregatorClient,
	                                 CloudCredentials cloudCredentials, String orgName, String spaceName) {
		logger = LogFactory.getLog(getClass().getName());
		CloudControllerClientImpl tempClient =
				new CloudControllerClientImpl(cloudControllerUrl, restTemplate,
						oauthClient, loggregatorClient, cloudCredentials, null);

		initialize(cloudControllerUrl, restTemplate, oauthClient, loggregatorClient, cloudCredentials);

		this.sessionSpace = validateSpaceAndOrg(spaceName, orgName, tempClient);
	}

	private void initialize(URL cloudControllerUrl, RestTemplate restTemplate, OauthClient oauthClient,
	                        LoggregatorClient loggregatorClient, CloudCredentials cloudCredentials) {
		Assert.notNull(cloudControllerUrl, "CloudControllerUrl cannot be null");
		Assert.notNull(restTemplate, "RestTemplate cannot be null");
		Assert.notNull(oauthClient, "OauthClient cannot be null");

		oauthClient.init(cloudCredentials);
=======
    private static final String AUTHORIZATION_HEADER_KEY = "Authorization";
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    private static final int JOB_POLLING_PERIOD = 5000; // matches that of gcf
Solution content
 */
public class CloudControllerClientImpl implements CloudControllerClient {

    private static final String AUTHORIZATION_HEADER_KEY = "Authorization";

    private static final long JOB_POLLING_PERIOD = TimeUnit.SECONDS.toMillis(5);

    private static final long JOB_TIMEOUT = TimeUnit.MINUTES.toMillis(3);
File
CloudControllerClientImpl.java
Developer's decision
Combination
Kind of conflict
Attribute
Comment
Method declaration
Method invocation
Method signature
Chunk
Conflicting content
    private URL cloudControllerUrl;

<<<<<<< HEAD
		for (CloudSpace space : spaces) {
			if (space.getName().equals(spaceName)) {
				CloudOrganization org = space.getOrganization();
				if (orgName == null || org.getName().equals(orgName)) {
					return space;
				}
			}
		}

		throw new IllegalArgumentException("No matching organization and space found for org: " + orgName + " space: " + spaceName);
	}

	@Override
	public void setResponseErrorHandler(ResponseErrorHandler errorHandler) {
		this.restTemplate.setErrorHandler(errorHandler);
	}

	@Override
	public URL getCloudControllerUrl() {
		return this.cloudControllerUrl;
	}

	@Override
	public void updatePassword(String newPassword) {
		updatePassword(cloudCredentials, newPassword);
	}

	@Override
	public Map getLogs(String appName) {
		String urlPath = getFileUrlPath();
		String instance = String.valueOf(0);
		return doGetLogs(urlPath, appName, instance);
	}

	@Override
	public List getRecentLogs(String appName) {
		UUID appId = getAppId(appName);

		String endpoint = getInfo().getLoggregatorEndpoint();
		String uri = loggregatorClient.getRecentHttpEndpoint(endpoint);

		ApplicationLogs logs = getRestTemplate().getForObject(uri + "?app={guid}", ApplicationLogs.class, appId);

		Collections.sort(logs);

		return logs;
	}

	@Override
	public StreamingLogToken streamLogs(String appName, ApplicationLogListener listener) {
		return streamLoggregatorLogs(appName, listener, false);
	}

	@Override
	public Map getCrashLogs(String appName) {
		String urlPath = getFileUrlPath();
		CrashesInfo crashes = getCrashes(appName);
		if (crashes.getCrashes().isEmpty()) {
			return Collections.emptyMap();
		}
		TreeMap crashInstances = new TreeMap();
		for (CrashInfo crash : crashes.getCrashes()) {
			crashInstances.put(crash.getSince(), crash.getInstance());
		}
		String instance = crashInstances.get(crashInstances.lastKey());
		return doGetLogs(urlPath, appName, instance);
	}

	@Override
	public String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition) {
		String urlPath = getFileUrlPath();
		Object appId = getFileAppId(appName);
		return doGetFile(urlPath, appId, instanceIndex, filePath, startPosition, endPosition);
	}


	@Override
	public void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback callback) {
		String urlPath = getFileUrlPath();
		Object appId = getFileAppId(appName);
		doOpenFile(urlPath, appId, instanceIndex, filePath, callback);
	}

	@Override
	public void registerRestLogListener(RestLogCallback callBack) {
		if (getRestTemplate() instanceof LoggingRestTemplate) {
			((LoggingRestTemplate)getRestTemplate()).registerRestLogListener(callBack);
		}
	}

	@Override
	public void unRegisterRestLogListener(RestLogCallback callBack) {
		if (getRestTemplate() instanceof LoggingRestTemplate) {
			((LoggingRestTemplate)getRestTemplate()).unRegisterRestLogListener(callBack);
		}
	}

	/**
	 * Returns null if no further content is available. Two errors that will
	 * lead to a null value are 404 Bad Request errors, which are handled in the
	 * implementation, meaning that no further log file contents are available,
	 * or ResourceAccessException, also handled in the implementation,
	 * indicating a possible timeout in the server serving the content. Note
	 * that any other CloudFoundryException or RestClientException exception not
	 * related to the two errors mentioned above may still be thrown (e.g. 500
	 * level errors, Unauthorized or Forbidden exceptions, etc..)
	 *
	 * @return content if available, which may contain multiple lines, or null
	 *         if no further content is available.
	 *
	 */
	@Override
	public String getStagingLogs(StartingInfo info, int offset) {
		String stagingFile = info.getStagingFile();
		if (stagingFile != null) {
			CloudFoundryClientHttpRequestFactory cfRequestFactory = null;
			try {
				HashMap logsRequest = new HashMap();
				logsRequest.put("offset", offset);

				cfRequestFactory = getRestTemplate().getRequestFactory() instanceof CloudFoundryClientHttpRequestFactory ? (CloudFoundryClientHttpRequestFactory) getRestTemplate()
						.getRequestFactory() : null;
				if (cfRequestFactory != null) {
					cfRequestFactory
							.increaseReadTimeoutForStreamedTailedLogs(5 * 60 * 1000);
				}
				return getRestTemplate().getForObject(
						stagingFile + "&tail&tail_offset={offset}",
						String.class, logsRequest);
			} catch (CloudFoundryException e) {
				if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
					// Content is no longer available
					return null;
				} else {
					throw e;
				}
			} catch (ResourceAccessException e) {
				// Likely read timeout, the directory server won't serve
				// the content again
				logger.debug("Caught exception while fetching staging logs. Aborting. Caught:" + e,
						e);
			} finally {
				if (cfRequestFactory != null) {
					cfRequestFactory
							.increaseReadTimeoutForStreamedTailedLogs(-1);
				}
			}
		}
		return null;
	}

	protected RestTemplate getRestTemplate() {
		return this.restTemplate;
	}

	protected String getUrl(String path) {
		return cloudControllerUrl + (path.startsWith("/") ? path : "/" + path);
	}

	protected void configureCloudFoundryRequestFactory(RestTemplate restTemplate) {
		ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory();
		if (!(requestFactory instanceof CloudFoundryClientHttpRequestFactory)) {
			restTemplate.setRequestFactory(
					new CloudFoundryClientHttpRequestFactory(requestFactory));
		}
	}

	private class CloudFoundryClientHttpRequestFactory implements ClientHttpRequestFactory {

		private ClientHttpRequestFactory delegate;
		private Integer defaultSocketTimeout = 0;

		public CloudFoundryClientHttpRequestFactory(ClientHttpRequestFactory delegate) {
			this.delegate = delegate;
			captureDefaultReadTimeout();
		}

		@Override
		public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
			ClientHttpRequest request = delegate.createRequest(uri, httpMethod);

			String authorizationHeader = oauthClient.getAuthorizationHeader();
			if (authorizationHeader != null) {
				request.getHeaders().add(AUTHORIZATION_HEADER_KEY, authorizationHeader);
			}

			if (cloudCredentials != null && cloudCredentials.getProxyUser() != null) {
				request.getHeaders().add(PROXY_USER_HEADER_KEY, cloudCredentials.getProxyUser());
			}

			return request;
		}

        private void captureDefaultReadTimeout() {
            // As of HttpClient 4.3.x, obtaining the default parameters is deprecated and removed,
            // so we fallback to java.net.Socket.

            if (defaultSocketTimeout == null) {
                try {
                    defaultSocketTimeout = new Socket().getSoTimeout();
                } catch (SocketException e) {
                    defaultSocketTimeout = 0;
                }
            }
        }

		public void increaseReadTimeoutForStreamedTailedLogs(int timeout) {
			// May temporary increase read timeout on other unrelated concurrent
			// threads, but per-request read timeout don't seem easily
			// accessible
			if (delegate instanceof HttpComponentsClientHttpRequestFactory) {
				HttpComponentsClientHttpRequestFactory httpRequestFactory =
						(HttpComponentsClientHttpRequestFactory) delegate;

				if (timeout > 0) {
					httpRequestFactory.setReadTimeout(timeout);
				} else {
					httpRequestFactory
							.setReadTimeout(defaultSocketTimeout);
				}
			}
		}
	}

	protected Map doGetLogs(String urlPath, String appName, String instance) {
		Object appId = getFileAppId(appName);
		String logFiles = doGetFile(urlPath, appId, instance, LOGS_LOCATION, -1, -1);
		String[] lines = logFiles.split("\n");
		List fileNames = new ArrayList();
		for (String line : lines) {
			String[] parts = line.split("\\s");
			if (parts.length > 0 && parts[0] != null) {
				fileNames.add(parts[0]);
			}
		}
		Map logs = new HashMap(fileNames.size());
		for(String fileName : fileNames) {
			String logFile = LOGS_LOCATION + "/" + fileName;
			logs.put(logFile, doGetFile(urlPath, appId, instance, logFile, -1, -1));
		}
		return logs;
	}

	@SuppressWarnings("unchecked")
	protected void doOpenFile(String urlPath, Object app, int instanceIndex, String filePath,
			ClientHttpResponseCallback callback) {
		getRestTemplate().execute(getUrl(urlPath), HttpMethod.GET, null, new ResponseExtractorWrapper(callback), app,
				String.valueOf(instanceIndex), filePath);
	}

	protected String doGetFile(String urlPath, Object app, int instanceIndex, String filePath, int startPosition, int endPosition) {
		return doGetFile(urlPath, app, String.valueOf(instanceIndex), filePath, startPosition, endPosition);
	}

	protected String doGetFile(String urlPath, Object app, String instance, String filePath, int startPosition, int endPosition) {
		Assert.isTrue(startPosition >= -1, "Invalid start position value: " + startPosition);
		Assert.isTrue(endPosition >= -1, "Invalid end position value: " + endPosition);
		Assert.isTrue(startPosition < 0 || endPosition < 0 || endPosition >= startPosition,
				"The end position (" + endPosition + ") can't be less than the start position (" + startPosition + ")");

		int start, end;
		if (startPosition == -1 && endPosition == -1) {
			start = 0;
			end = -1;
		} else {
			start = startPosition;
			end = endPosition;
		}

		final String range =
				"bytes=" + (start == -1 ? "" : start) + "-" + (end == -1 ? "" : end);

		return doGetFileByRange(urlPath, app, instance, filePath, start, end, range);
	}

	private String doGetFileByRange(String urlPath, Object app, String instance, String filePath, int start, int end,
									String range) {

		boolean supportsRanges;
		try {
			supportsRanges = getRestTemplate().execute(getUrl(urlPath),
					HttpMethod.HEAD,
					new RequestCallback() {
						public void doWithRequest(ClientHttpRequest request) throws IOException {
							request.getHeaders().set("Range", "bytes=0-");
						}
					},
					new ResponseExtractor() {
						public Boolean extractData(ClientHttpResponse response) throws IOException {
							return response.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT);
						}
					},
					app, instance, filePath);
		} catch (CloudFoundryException e) {
			if (e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)) {
				// must be a 0 byte file
				return "";
			} else {
				throw e;
			}
		}
		HttpHeaders headers = new HttpHeaders();
		if (supportsRanges) {
			headers.set("Range", range);
		}
		HttpEntity requestEntity = new HttpEntity(headers);
		ResponseEntity responseEntity = getRestTemplate().exchange(getUrl(urlPath),
				HttpMethod.GET, requestEntity, String.class, app, instance, filePath);
		String response = responseEntity.getBody();
		boolean partialFile = false;
		if (responseEntity.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT)) {
			partialFile = true;
		}
		if (!partialFile && response != null) {
			if (start == -1) {
				return response.substring(response.length() - end);
			} else {
				if (start >= response.length()) {
					if (response.length() == 0) {
						return "";
					}
					throw new CloudFoundryException(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
							"The starting position " + start + " is past the end of the file content.");
				}
				if (end != -1) {
					if (end >= response.length()) {
						end = response.length() - 1;
					}
					return response.substring(start, end + 1);
				} else {
					return response.substring(start);
				}
			}
		}
		return response;
	}

	@SuppressWarnings("unchecked")
	@Override
	public CloudInfo getInfo() {
		// info comes from two end points: /info and /v2/info

		String infoV2Json = getRestTemplate().getForObject(getUrl("/v2/info"), String.class);
		Map infoV2Map = JsonUtil.convertJsonToMap(infoV2Json);

		Map userMap = getUserInfo((String) infoV2Map.get("user"));

		String infoJson = getRestTemplate().getForObject(getUrl("/info"), String.class);
		Map infoMap = JsonUtil.convertJsonToMap(infoJson);
		Map limitMap = (Map) infoMap.get("limits");
		Map usageMap = (Map) infoMap.get("usage");

		String name = CloudUtil.parse(String.class, infoV2Map.get("name"));
		String support = CloudUtil.parse(String.class, infoV2Map.get("support"));
		String authorizationEndpoint = CloudUtil.parse(String.class, infoV2Map.get("authorization_endpoint"));
		String build = CloudUtil.parse(String.class, infoV2Map.get("build"));
		String version = "" + CloudUtil.parse(Number.class, infoV2Map.get("version"));
		String description = CloudUtil.parse(String.class, infoV2Map.get("description"));

		CloudInfo.Limits limits = null;
		CloudInfo.Usage usage = null;
		boolean debug = false;
		if (oauthClient.getToken() != null) {
			limits = new CloudInfo.Limits(limitMap);
			usage = new CloudInfo.Usage(usageMap);
			debug = CloudUtil.parse(Boolean.class, infoMap.get("allow_debug"));
		}

		String loggregatorEndpoint = CloudUtil.parse(String.class, infoV2Map.get("logging_endpoint"));

		return new CloudInfo(name, support, authorizationEndpoint, build, version, (String)userMap.get("user_name"),
				description, limits, usage, debug, loggregatorEndpoint);
	}

	@Override
	public void createSpace(String spaceName) {
		assertSpaceProvided("create a new space");
		UUID orgGuid = sessionSpace.getOrganization().getMeta().getGuid();
		UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
		if (spaceGuid == null) {
			doCreateSpace(spaceName, orgGuid);
		}
	}

	@Override
	public CloudSpace getSpace(String spaceName) {
		String urlPath = "/v2/spaces?inline-relations-depth=1&q=name:{name}";
		HashMap spaceRequest = new HashMap();
		spaceRequest.put("name", spaceName);
		List> resourceList = getAllResources(urlPath, spaceRequest);
		CloudSpace space = null;
		if (resourceList.size() > 0) {
			Map resource = resourceList.get(0);
			space = resourceMapper.mapResource(resource, CloudSpace.class);
		}
		return space;
	}

	@Override
	public void deleteSpace(String spaceName) {
		assertSpaceProvided("delete a space");
		UUID orgGuid = sessionSpace.getOrganization().getMeta().getGuid();
		UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
		if (spaceGuid != null) {
			doDeleteSpace(spaceGuid);
		}
	}

	private UUID doCreateSpace(String spaceName, UUID orgGuid) {
		String urlPath = "/v2/spaces";
		HashMap spaceRequest = new HashMap();
		spaceRequest.put("organization_guid", orgGuid);
		spaceRequest.put("name", spaceName);
		String resp = getRestTemplate().postForObject(getUrl(urlPath), spaceRequest, String.class);
		Map respMap = JsonUtil.convertJsonToMap(resp);
		return resourceMapper.getGuidOfResource(respMap);
	}

	private UUID getSpaceGuid(String spaceName, UUID orgGuid) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/organizations/{orgGuid}/spaces?inline-relations-depth=1&q=name:{name}";
		urlVars.put("orgGuid", orgGuid);
		urlVars.put("name", spaceName);
		List> resourceList = getAllResources(urlPath, urlVars);
		if (resourceList.size() > 0) {
			Map resource = resourceList.get(0);
			return resourceMapper.getGuidOfResource(resource);
		}
		return null;
	}

	private UUID getSpaceGuid(String orgName, String spaceName) {
		CloudOrganization org = getOrgByName(orgName, true);
		return getSpaceGuid(spaceName, org.getMeta().getGuid());
	}

	private void doDeleteSpace(UUID spaceGuid) {
		getRestTemplate().delete(getUrl("/v2/spaces/{guid}?async=false"), spaceGuid);
	}

	@Override
	public List getSpaces() {
		String urlPath = "/v2/spaces?inline-relations-depth=1";
		List> resourceList = getAllResources(urlPath, null);
		List spaces = new ArrayList();
		for (Map resource : resourceList) {
			spaces.add(resourceMapper.mapResource(resource, CloudSpace.class));
		}
		return spaces;
	}

	@Override
	public List getSpaceManagers(String orgName, String spaceName) {
		String urlPath = "/v2/spaces/{guid}/managers";
		return getSpaceUserGuids(orgName, spaceName, urlPath);
	}

	@Override
	public List getSpaceDevelopers(String orgName, String spaceName) {
		String urlPath = "/v2/spaces/{guid}/developers";
		return getSpaceUserGuids(orgName, spaceName, urlPath);
	}

	@Override
	public List getSpaceAuditors(String orgName, String spaceName) {
		String urlPath = "/v2/spaces/{guid}/auditors";
		return getSpaceUserGuids(orgName, spaceName, urlPath);
	}

	private List getSpaceUserGuids(String orgName, String spaceName, String urlPath) {
		if (orgName == null || spaceName == null) {
			assertSpaceProvided("get space users");
		}

		UUID spaceGuid;
		if (spaceName == null) {
			spaceGuid = sessionSpace.getMeta().getGuid();
		} else {
			CloudOrganization organization = (orgName == null ? sessionSpace.getOrganization() : getOrgByName(orgName, true));
			spaceGuid = getSpaceGuid(spaceName, organization.getMeta().getGuid());
		}

		Map urlVars = new HashMap();
		urlVars.put("guid", spaceGuid);

		List managersGuid = new ArrayList();
		List> resourceList = getAllResources(urlPath, urlVars);
		for (Map resource : resourceList) {
			UUID userGuid = resourceMapper.getGuidOfResource(resource);
			managersGuid.add(userGuid);
		}
		return managersGuid;
	}

	@Override
	public void associateManagerWithSpace(String orgName, String spaceName, String userGuid) {
		String urlPath = "/v2/spaces/{guid}/managers/{userGuid}";
		associateRoleWithSpace(orgName, spaceName, userGuid, urlPath);
	}

	@Override
	public void associateDeveloperWithSpace(String orgName, String spaceName, String userGuid) {
		String urlPath = "/v2/spaces/{guid}/developers/{userGuid}";
		associateRoleWithSpace(orgName, spaceName, userGuid, urlPath);
	}

	@Override
	public void associateAuditorWithSpace(String orgName, String spaceName, String userGuid) {
		String urlPath = "/v2/spaces/{guid}/auditors/{userGuid}";
		associateRoleWithSpace(orgName, spaceName, userGuid, urlPath);
	}

	private void associateRoleWithSpace(String orgName, String spaceName, String userGuid, String urlPath) {
		assertSpaceProvided("associate roles");

		CloudOrganization organization = (orgName == null ? sessionSpace.getOrganization() : getOrgByName(orgName, true));
		UUID orgGuid = organization.getMeta().getGuid();

		UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
		HashMap spaceRequest = new HashMap();
		spaceRequest.put("guid", spaceGuid);

		String userId = (userGuid==null?getCurrentUserId():userGuid);

		getRestTemplate().put(getUrl(urlPath), spaceRequest, spaceGuid, userId);
	}

	private String getCurrentUserId() {
		String username = getInfo().getUser();
		Map userMap = getUserInfo(username);
		String userId= (String) userMap.get("user_id");
		return userId;
	}

	@Override
	public Map getOrganizationUsers(String orgName) {
		String urlPath = "/v2/organizations/{guid}/users";
		CloudOrganization organization = getOrgByName(orgName, true);

		UUID orgGuid=organization.getMeta().getGuid();
		Map urlVars = new HashMap();
		urlVars.put("guid", orgGuid);

		List> resourceList = getAllResources(urlPath, urlVars);
		Map orgUsers = new HashMap();
		for (Map resource : resourceList) {
			CloudUser user = resourceMapper.mapResource(resource, CloudUser.class);
			orgUsers.put(user.getUsername(),user);
		}
		return orgUsers;
	}

	@Override
	public List getOrganizations() {
		String urlPath = "/v2/organizations?inline-relations-depth=0";
		List> resourceList = getAllResources(urlPath, null);
		List orgs = new ArrayList();
		for (Map resource : resourceList) {
			orgs.add(resourceMapper.mapResource(resource, CloudOrganization.class));
		}
		return orgs;
	}

	@Override
	public OAuth2AccessToken login() {
		oauthClient.init(cloudCredentials);
		return oauthClient.getToken();
	}

	@Override
	public void logout() {
		oauthClient.clear();
	}

	@Override
	public void register(String email, String password) {
		throw new UnsupportedOperationException("Feature is not yet implemented.");
	}

	@Override
	public void updatePassword(CloudCredentials credentials, String newPassword) {
		oauthClient.changePassword(credentials.getPassword(), newPassword);
		CloudCredentials newCloudCredentials = new CloudCredentials(credentials.getEmail(), newPassword);
		if (cloudCredentials.getProxyUser() != null) {
			cloudCredentials = newCloudCredentials.proxyForUser(cloudCredentials.getProxyUser());
		} else {
			cloudCredentials = newCloudCredentials;
		}
	}

	@Override
	public void unregister() {
		throw new UnsupportedOperationException("Feature is not yet implemented.");
	}

	@Override
	public List getServices() {
		Map urlVars = new HashMap();
		String urlPath = "/v2";
		if (sessionSpace != null) {
			urlVars.put("space", sessionSpace.getMeta().getGuid());
			urlPath = urlPath + "/spaces/{space}";
		}
		urlPath = urlPath + "/service_instances?inline-relations-depth=1&return_user_provided_service_instances=true";
		List> resourceList = getAllResources(urlPath, urlVars);
		List services = new ArrayList();
		for (Map resource : resourceList) {
			if (hasEmbeddedResource(resource, "service_plan")) {
				fillInEmbeddedResource(resource, "service_plan", "service");
			}
			services.add(resourceMapper.mapResource(resource, CloudService.class));
		}
		return services;
	}

	@Override
	public void createService(CloudService service) {
		assertSpaceProvided("create service");
		Assert.notNull(service, "Service must not be null");
		Assert.notNull(service.getName(), "Service name must not be null");
		Assert.notNull(service.getLabel(), "Service label must not be null");
		Assert.notNull(service.getPlan(), "Service plan must not be null");

		CloudServicePlan cloudServicePlan = findPlanForService(service);

		HashMap serviceRequest = new HashMap();
		serviceRequest.put("space_guid", sessionSpace.getMeta().getGuid());
		serviceRequest.put("name", service.getName());
		serviceRequest.put("service_plan_guid", cloudServicePlan.getMeta().getGuid());
		getRestTemplate().postForObject(getUrl("/v2/service_instances"), serviceRequest, String.class);
	}

	private CloudServicePlan findPlanForService(CloudService service) {
		List offerings = getServiceOfferings(service.getLabel());
		for (CloudServiceOffering offering : offerings) {
			if (service.getVersion() == null || service.getVersion().equals(offering.getVersion())) {
				for (CloudServicePlan plan : offering.getCloudServicePlans()) {
					if (service.getPlan() != null && service.getPlan().equals(plan.getName())) {
						return plan;
					}
				}
			}
		}
		throw new IllegalArgumentException("Service plan " + service.getPlan() + " not found");
	}

	@Override
	public void createUserProvidedService(CloudService service, Map credentials) {
		createUserProvidedServiceDelegate(service, credentials, "");
	}

	@Override
	public void createUserProvidedService(CloudService service, Map credentials, String syslogDrainUrl) {
		createUserProvidedServiceDelegate(service, credentials, syslogDrainUrl);
	}

	private void createUserProvidedServiceDelegate(CloudService service, Map credentials, String syslogDrainUrl) {
		assertSpaceProvided("create service");
		Assert.notNull(credentials, "Service credentials must not be null");
		Assert.notNull(service, "Service must not be null");
		Assert.notNull(service.getName(), "Service name must not be null");
		Assert.isNull(service.getLabel(), "Service label is not valid for user-provided services");
		Assert.isNull(service.getProvider(), "Service provider is not valid for user-provided services");
		Assert.isNull(service.getVersion(), "Service version is not valid for user-provided services");
		Assert.isNull(service.getPlan(), "Service plan is not valid for user-provided services");

		HashMap serviceRequest = new HashMap<>();
		serviceRequest.put("space_guid", sessionSpace.getMeta().getGuid());
		serviceRequest.put("name", service.getName());
		serviceRequest.put("credentials", credentials);
		if (syslogDrainUrl != null && !syslogDrainUrl.equals("")) {
			serviceRequest.put("syslog_drain_url", syslogDrainUrl);
		}

		getRestTemplate().postForObject(getUrl("/v2/user_provided_service_instances"), serviceRequest, String.class);
	}

	@Override
	public CloudService getService(String serviceName) {
		Map resource = doGetServiceInstance(serviceName, 0);

		if (resource == null) {
			return null;
		}

		return resourceMapper.mapResource(resource, CloudService.class);
	}

	@Override
	public CloudServiceInstance getServiceInstance(String serviceName) {
		Map resource = doGetServiceInstance(serviceName, 1);

		if (resource == null) {
			return null;
		}

		return resourceMapper.mapResource(resource, CloudServiceInstance.class);
	}

	private Map doGetServiceInstance(String serviceName, int inlineDepth) {
		String urlPath = "/v2";
		Map urlVars = new HashMap();
		if (sessionSpace != null) {
			urlVars.put("space", sessionSpace.getMeta().getGuid());
			urlPath = urlPath + "/spaces/{space}";
		}
		urlVars.put("q", "name:" + serviceName);
		urlPath = urlPath + "/service_instances?q={q}&return_user_provided_service_instances=true";
		if (inlineDepth > 0) {
			urlPath = urlPath + "&inline-relations-depth=" + inlineDepth;
		}

		List> resources = getAllResources(urlPath, urlVars);

		if (resources.size() > 0) {
			Map serviceResource = resources.get(0);
			if (hasEmbeddedResource(serviceResource, "service_plan")) {
				fillInEmbeddedResource(serviceResource, "service_plan", "service");
			}
			return serviceResource;
		}
		return null;
	}

	@Override
	public void deleteService(String serviceName) {
		CloudService cloudService = getService(serviceName);
		doDeleteService(cloudService);
	}

	@Override
	public void deleteAllServices() {
		List cloudServices = getServices();
		for (CloudService cloudService : cloudServices) {
			doDeleteService(cloudService);
		}
	}

	@Override
	public List getServiceOfferings() {
		String urlPath = "/v2/services?inline-relations-depth=1";
		List> resourceList = getAllResources(urlPath, null);
		List serviceOfferings = new ArrayList();
		for (Map resource : resourceList) {
			CloudServiceOffering serviceOffering = resourceMapper.mapResource(resource, CloudServiceOffering.class);
			serviceOfferings.add(serviceOffering);
		}
		return serviceOfferings;
	}

	@Override
	public List getServiceBrokers() {
		String urlPath = "/v2/service_brokers?inline-relations-depth=1";
		List> resourceList = getAllResources(urlPath, null);
		List serviceBrokers = new ArrayList();
		for (Map resource : resourceList) {
			CloudServiceBroker broker = resourceMapper.mapResource(resource, CloudServiceBroker.class);
			serviceBrokers.add(broker);
		}
		return serviceBrokers;
	}

	@Override
	public CloudServiceBroker getServiceBroker(String name) {
		String urlPath = "/v2/service_brokers?q={q}";
		Map urlVars = new HashMap<>();
		urlVars.put("q", "name:" + name);
		List> resourceList = getAllResources(urlPath, urlVars);
		CloudServiceBroker serviceBroker = null;
		if (resourceList.size() > 0) {
			final Map resource = resourceList.get(0);
			serviceBroker = resourceMapper.mapResource(resource, CloudServiceBroker.class);
		}
		return serviceBroker;
	}

	@Override
	public void createServiceBroker(CloudServiceBroker serviceBroker) {
		Assert.notNull(serviceBroker, "Service Broker must not be null");
		Assert.notNull(serviceBroker.getName(), "Service Broker name must not be null");
		Assert.notNull(serviceBroker.getUrl(), "Service Broker URL must not be null");
		Assert.notNull(serviceBroker.getUsername(), "Service Broker username must not be null");
		Assert.notNull(serviceBroker.getPassword(), "Service Broker password must not be null");

		HashMap serviceRequest = new HashMap<>();
		serviceRequest.put("name", serviceBroker.getName());
		serviceRequest.put("broker_url", serviceBroker.getUrl());
		serviceRequest.put("auth_username", serviceBroker.getUsername());
		serviceRequest.put("auth_password", serviceBroker.getPassword());
		getRestTemplate().postForObject(getUrl("/v2/service_brokers"), serviceRequest, String.class);
	}

	@Override
	public void updateServiceBroker(CloudServiceBroker serviceBroker) {
		Assert.notNull(serviceBroker, "Service Broker must not be null");
		Assert.notNull(serviceBroker.getName(), "Service Broker name must not be null");
		Assert.notNull(serviceBroker.getUrl(), "Service Broker URL must not be null");
		Assert.notNull(serviceBroker.getUsername(), "Service Broker username must not be null");
		Assert.notNull(serviceBroker.getPassword(), "Service Broker password must not be null");

		CloudServiceBroker existingBroker = getServiceBroker(serviceBroker.getName());
		Assert.notNull(existingBroker, "Cannot update broker if it does not first exist");

		HashMap serviceRequest = new HashMap<>();
		serviceRequest.put("name", serviceBroker.getName());
		serviceRequest.put("broker_url", serviceBroker.getUrl());
		serviceRequest.put("auth_username", serviceBroker.getUsername());
		serviceRequest.put("auth_password", serviceBroker.getPassword());
		getRestTemplate().put(getUrl("/v2/service_brokers/{guid}"), serviceRequest, existingBroker.getMeta().getGuid());
	}

	@Override
	public void deleteServiceBroker(String name) {
		CloudServiceBroker existingBroker = getServiceBroker(name);
	@SuppressWarnings("unchecked")
		Assert.notNull(existingBroker, "Cannot update broker if it does not first exist");

		getRestTemplate().delete(getUrl("/v2/service_brokers/{guid}"), existingBroker.getMeta().getGuid());
	}

	@Override
	public void updateServicePlanVisibilityForBroker(String name, boolean visibility) {
		CloudServiceBroker broker = getServiceBroker(name);

		String urlPath = "/v2/services?q={q}";
		Map urlVars = new HashMap<>();
		urlVars.put("q", "service_broker_guid:" + broker.getMeta().getGuid());
		List> serviceResourceList = getAllResources(urlPath, urlVars);

		for (Map serviceResource : serviceResourceList) {
			Map metadata = (Map) serviceResource.get("metadata");
			String serviceGuid = (String) metadata.get("guid");

			urlPath = "/v2/service_plans?q={q}";
			urlVars = new HashMap<>();
			urlVars.put("q", "service_guid:" + serviceGuid);
			List> planResourceList = getAllResources(urlPath, urlVars);
			for (Map planResource : planResourceList) {
				metadata = (Map) planResource.get("metadata");
				String planGuid = (String) metadata.get("guid");

				HashMap planUpdateRequest = new HashMap<>();
				planUpdateRequest.put("public", visibility);
				getRestTemplate().put(getUrl("/v2/service_plans/{guid}"), planUpdateRequest, planGuid);
			}
		}
	}

	@Override
	public List getApplications() {
		Map urlVars = new HashMap();
		String urlPath = "/v2";
		if (sessionSpace != null) {
			urlVars.put("space", sessionSpace.getMeta().getGuid());
			urlPath = urlPath + "/spaces/{space}";
		}
		urlPath = urlPath + "/apps?inline-relations-depth=1";
		List> resourceList = getAllResources(urlPath, urlVars);
		List apps = new ArrayList();
		for (Map resource : resourceList) {
			processApplicationResource(resource, true);
			apps.add(mapCloudApplication(resource));
		}
		return apps;
	}

	@Override
	public CloudApplication getApplication(String appName) {
		Map resource = findApplicationResource(appName, true);
		if (resource == null) {
			throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Not Found", "Application not found");
		}
		return mapCloudApplication(resource);
	}

	@Override
	public CloudApplication getApplication(UUID appGuid) {
		Map resource = findApplicationResource(appGuid, true);
		if (resource == null) {
			throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Not Found", "Application not found");
		}
		return mapCloudApplication(resource);
	}

	@Override
	public Map getApplicationEnvironment(UUID appGuid) {
    	String url = getUrl("/v2/apps/{guid}/env");
		Map urlVars = new HashMap();
		urlVars.put("guid", appGuid);
		String resp = restTemplate.getForObject(url, String.class, urlVars);
		return JsonUtil.convertJsonToMap(resp);
	}

	@Override
	public Map getApplicationEnvironment(String appName) {
		UUID appId = getAppId(appName);
		return getApplicationEnvironment(appId);
	}

	@SuppressWarnings("unchecked")
	private CloudApplication mapCloudApplication(Map resource) {
		UUID appId = resourceMapper.getGuidOfResource(resource);
		CloudApplication cloudApp = null;
		if (resource != null) {
			int running = getRunningInstances(appId,
				CloudApplication.AppState.valueOf(
					CloudEntityResourceMapper.getEntityAttribute(resource, "state", String.class)));
			((Map)resource.get("entity")).put("running_instances", running);
			cloudApp = resourceMapper.mapResource(resource, CloudApplication.class);
			cloudApp.setUris(findApplicationUris(cloudApp.getMeta().getGuid()));
		}
		return cloudApp;
	}

	private int getRunningInstances(UUID appId, CloudApplication.AppState appState) {
		int running = 0;
		ApplicationStats appStats = doGetApplicationStats(appId, appState);
		if (appStats != null && appStats.getRecords() != null) {
			for (InstanceStats inst : appStats.getRecords()) {
				if (InstanceState.RUNNING == inst.getState()){
					running++;
				}
			}
		}
		return running;
	}

	@Override
	public ApplicationStats getApplicationStats(String appName) {
		CloudApplication app = getApplication(appName);
		return doGetApplicationStats(app.getMeta().getGuid(), app.getState());
	}

	@SuppressWarnings("unchecked")
	private ApplicationStats doGetApplicationStats(UUID appId, CloudApplication.AppState appState) {
		List instanceList = new ArrayList();
		if (appState.equals(CloudApplication.AppState.STARTED)) {
			Map respMap = getInstanceInfoForApp(appId, "stats");
			for (String instanceId : respMap.keySet()) {
				InstanceStats instanceStats =
						new InstanceStats(instanceId, (Map) respMap.get(instanceId));
				instanceList.add(instanceStats);
			}
		}
		return new ApplicationStats(instanceList);
	}

	private Map getInstanceInfoForApp(UUID appId, String path) {
		String url = getUrl("/v2/apps/{guid}/" + path);
		Map urlVars = new HashMap();
		urlVars.put("guid", appId);
		String resp = getRestTemplate().getForObject(url, String.class, urlVars);
		return JsonUtil.convertJsonToMap(resp);
	}

	@Override
	public void createApplication(String appName, Staging staging, Integer memory, List uris,
	                              List serviceNames) {
		createApplication(appName, staging, null, memory, uris, serviceNames);
	}

	@Override
	public void createApplication(String appName, Staging staging, Integer disk, Integer memory,
	                              List uris, List serviceNames) {
		HashMap appRequest = new HashMap();
		appRequest.put("space_guid", sessionSpace.getMeta().getGuid());
		appRequest.put("name", appName);
		appRequest.put("memory", memory);
		if (disk != null) {
			appRequest.put("disk_quota", disk);
		}
		appRequest.put("instances", 1);
		addStagingToRequest(staging, appRequest);
		appRequest.put("state", CloudApplication.AppState.STOPPED);


		String appResp = getRestTemplate().postForObject(getUrl("/v2/apps"), appRequest, String.class);
		Map appEntity = JsonUtil.convertJsonToMap(appResp);
		UUID newAppGuid = CloudEntityResourceMapper.getMeta(appEntity).getGuid();

		if (serviceNames != null && serviceNames.size() > 0) {
			updateApplicationServices(appName, serviceNames);
		}

		if (uris != null && uris.size() > 0) {
			addUris(uris, newAppGuid);
		}
	}

	private void addStagingToRequest(Staging staging, HashMap appRequest) {
		if (staging.getBuildpackUrl() != null) {
			appRequest.put("buildpack", staging.getBuildpackUrl());
		}
		if (staging.getCommand() != null) {
			appRequest.put("command", staging.getCommand());
		}
		if (staging.getStack() != null) {
			appRequest.put("stack_guid", getStack(staging.getStack()).getMeta().getGuid());
		}
		if (staging.getHealthCheckTimeout() != null) {
			appRequest.put("health_check_timeout", staging.getHealthCheckTimeout());
		}
	}

	private List> getAllResources(String urlPath, Map urlVars) {
		List> allResources = new ArrayList>();
		String resp;
		if (urlVars != null) {
			resp = getRestTemplate().getForObject(getUrl(urlPath), String.class, urlVars);
		} else {
			resp = getRestTemplate().getForObject(getUrl(urlPath), String.class);
		}
		Map respMap = JsonUtil.convertJsonToMap(resp);
		List> newResources = (List>) respMap.get("resources");
		if (newResources != null && newResources.size() > 0) {
			allResources.addAll(newResources);
		}
		String nextUrl = (String) respMap.get("next_url");
		while (nextUrl != null && nextUrl.length() > 0) {
			nextUrl = addPageOfResources(nextUrl, allResources);
		}
		return allResources;
	}

	@SuppressWarnings("unchecked")
	private String addPageOfResources(String nextUrl, List> allResources) {
		String resp = getRestTemplate().getForObject(getUrl(nextUrl), String.class);
		Map respMap = JsonUtil.convertJsonToMap(resp);
		List> newResources = (List>) respMap.get("resources");
		if (newResources != null && newResources.size() > 0) {
			allResources.addAll(newResources);
		}
		return (String) respMap.get("next_url");
	}

	private void addUris(List uris, UUID appGuid) {
		Map domains = getDomainGuids();
		for (String uri : uris) {
			Map uriInfo = new HashMap(2);
			extractUriInfo(domains, uri, uriInfo);
			UUID domainGuid = domains.get(uriInfo.get("domainName"));
			bindRoute(uriInfo.get("host"), domainGuid, appGuid);
		}
	}

	private void removeUris(List uris, UUID appGuid) {
		Map domains = getDomainGuids();
		for (String uri : uris) {
			Map uriInfo = new HashMap(2);
			extractUriInfo(domains, uri, uriInfo);
			UUID domainGuid = domains.get(uriInfo.get("domainName"));
			unbindRoute(uriInfo.get("host"), domainGuid, appGuid);
		}
	}

	protected void extractUriInfo(Map domains, String uri, Map uriInfo) {
		URI newUri = URI.create(uri);
		String host = newUri.getScheme() != null ? newUri.getHost(): newUri.getPath();
		for (String domain : domains.keySet()) {
			if (host != null && host.endsWith(domain)) {
				String previousDomain = uriInfo.get("domainName");
				if (previousDomain == null || domain.length() > previousDomain.length()) {
					//Favor most specific subdomains
					uriInfo.put("domainName", domain);
					if (domain.length() < host.length()) {
						uriInfo.put("host", host.substring(0, host.indexOf(domain) - 1));
					} else if (domain.length() == host.length()) {
						uriInfo.put("host", "");
					}
				}
			}
		}
		if (uriInfo.get("domainName") == null) {
			throw new IllegalArgumentException("Domain not found for URI " + uri);
		}
		if (uriInfo.get("host") == null) {
			throw new IllegalArgumentException("Invalid URI " + uri +
					" -- host not specified for domain " + uriInfo.get("domainName"));
		}
	}

	private Map getDomainGuids() {
		Map urlVars = new HashMap();
		String urlPath = "/v2";
		if (sessionSpace != null) {
			urlVars.put("space", sessionSpace.getMeta().getGuid());
			urlPath = urlPath + "/spaces/{space}";
		}
		String domainPath = urlPath + "/domains?inline-relations-depth=1";
		List> resourceList = getAllResources(domainPath, urlVars);
		Map domains = new HashMap(resourceList.size());
		for (Map d : resourceList) {
			domains.put(
					CloudEntityResourceMapper.getEntityAttribute(d, "name", String.class),
		return file;
					CloudEntityResourceMapper.getMeta(d).getGuid());
		}
		return domains;
	}

	private UUID getDomainGuid(String domainName, boolean required) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/domains?inline-relations-depth=1&q=name:{name}";
		urlVars.put("name", domainName);
		List> resourceList = getAllResources(urlPath, urlVars);
		UUID domainGuid = null;
		if (resourceList.size() > 0) {
			Map resource = resourceList.get(0);
			domainGuid = resourceMapper.getGuidOfResource(resource);
		}
		if (domainGuid == null && required) {
			throw new IllegalArgumentException("Domain '" + domainName + "' not found.");
		}
		return domainGuid;
	}

	private void bindRoute(String host, UUID domainGuid, UUID appGuid) {
		UUID routeGuid = getRouteGuid(host, domainGuid);
		if (routeGuid == null) {
			routeGuid = doAddRoute(host, domainGuid);
		}
		String bindPath = "/v2/apps/{app}/routes/{route}";
		Map bindVars = new HashMap();
		bindVars.put("app", appGuid);
		bindVars.put("route", routeGuid);
		HashMap bindRequest = new HashMap();
		getRestTemplate().put(getUrl(bindPath), bindRequest, bindVars);
	}

	private void unbindRoute(String host, UUID domainGuid, UUID appGuid) {
		UUID routeGuid = getRouteGuid(host, domainGuid);
		if (routeGuid != null) {
			String bindPath = "/v2/apps/{app}/routes/{route}";
			Map bindVars = new HashMap();
			bindVars.put("app", appGuid);
			bindVars.put("route", routeGuid);
			getRestTemplate().delete(getUrl(bindPath), bindVars);
		}
	}

	private UUID getRouteGuid(String host, UUID domainGuid) {
		Map urlVars = new HashMap();
		String urlPath = "/v2";
		urlPath = urlPath + "/routes?inline-relations-depth=0&q=host:{host}";
		urlVars.put("host", host);
		List> allRoutes = getAllResources(urlPath, urlVars);
		UUID routeGuid = null;
		for (Map route : allRoutes) {
			UUID routeSpace = CloudEntityResourceMapper.getEntityAttribute(route, "space_guid", UUID.class);
			UUID routeDomain = CloudEntityResourceMapper.getEntityAttribute(route, "domain_guid", UUID.class);
			if (sessionSpace.getMeta().getGuid().equals(routeSpace) &&
					domainGuid.equals(routeDomain)) {
				routeGuid = CloudEntityResourceMapper.getMeta(route).getGuid();
			}
		}
		return routeGuid;
	}

	private UUID doAddRoute(String host, UUID domainGuid) {
		assertSpaceProvided("add route");

		HashMap routeRequest = new HashMap();
		routeRequest.put("host", host);
		routeRequest.put("domain_guid", domainGuid);
		routeRequest.put("space_guid", sessionSpace.getMeta().getGuid());
		String routeResp = getRestTemplate().postForObject(getUrl("/v2/routes"), routeRequest, String.class);
		Map routeEntity = JsonUtil.convertJsonToMap(routeResp);
		return CloudEntityResourceMapper.getMeta(routeEntity).getGuid();
	}

	@Override
	public void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException {
		Assert.notNull(file, "File must not be null");
		if (file.isDirectory()) {
			ApplicationArchive archive = new DirectoryApplicationArchive(file);
			uploadApplication(appName, archive, callback);
		} else {
			try (ZipFile zipFile = new ZipFile(file)) {
				ApplicationArchive archive = new ZipApplicationArchive(zipFile);
				uploadApplication(appName, archive, callback);
			}
		}
	}

	@Override
	public void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback callback) throws IOException {
		Assert.notNull(fileName, "FileName must not be null");
		Assert.notNull(inputStream, "InputStream must not be null");

		File file = createTemporaryUploadFile(inputStream);

		try (ZipFile zipFile = new ZipFile(file)) {
			ApplicationArchive archive = new ZipApplicationArchive(zipFile);
			uploadApplication(appName, archive, callback);
		}

		file.delete();
	}

	@Override
	public void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback)
			throws IOException {
		Assert.notNull(appName, "AppName must not be null");
		Assert.notNull(archive, "Archive must not be null");
		UUID appId = getAppId(appName);

		if (callback == null) {
			callback = UploadStatusCallback.NONE;
		}
		CloudResources knownRemoteResources = getKnownRemoteResources(archive);
		callback.onCheckResources();
		callback.onMatchedFileNames(knownRemoteResources.getFilenames());
		UploadApplicationPayload payload = new UploadApplicationPayload(archive, knownRemoteResources);
		callback.onProcessMatchedResources(payload.getTotalUncompressedSize());
		HttpEntity entity = generatePartialResourceRequest(payload, knownRemoteResources);
		ResponseEntity> responseEntity =
			getRestTemplate().exchange(getUrl("/v2/apps/{guid}/bits?async=true"),
				HttpMethod.PUT, entity,
				new ParameterizedTypeReference>() {}, appId);
		processAsyncJob(responseEntity.getBody(), callback);
	}

	private void processAsyncJob(Map jobResource, UploadStatusCallback callback) {
		CloudJob job = resourceMapper.mapResource(jobResource, CloudJob.class);
		do {
			boolean unsubscribe = callback.onProgress(job.getStatus().toString());
			if (unsubscribe) {
				return;
			}
			if (job.getStatus() == CloudJob.Status.FAILED) {
				return;
			}

			try {
				Thread.sleep(JOB_POLLING_PERIOD);
			} catch (InterruptedException ex) {
				return;
			}

			ResponseEntity> jobProgressEntity =
					getRestTemplate().exchange(getUrl(job.getMeta().getUrl()),
						HttpMethod.GET, HttpEntity.EMPTY,
						new ParameterizedTypeReference>() {});
			job = resourceMapper.mapResource(jobProgressEntity.getBody(), CloudJob.class);
		} while (job.getStatus() != CloudJob.Status.FINISHED);
	}

	private CloudResources getKnownRemoteResources(ApplicationArchive archive) throws IOException {
		CloudResources archiveResources = new CloudResources(archive);
		String json = JsonUtil.convertToJson(archiveResources);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(JsonUtil.JSON_MEDIA_TYPE);
		HttpEntity requestEntity = new HttpEntity(json, headers);
		ResponseEntity responseEntity =
			getRestTemplate().exchange(getUrl("/v2/resource_match"), HttpMethod.PUT, requestEntity, String.class);
		List cloudResources = JsonUtil.convertJsonToCloudResourceList(responseEntity.getBody());
		return new CloudResources(cloudResources);
	}

	private HttpEntity> generatePartialResourceRequest(UploadApplicationPayload application,
			CloudResources knownRemoteResources) throws IOException {
		MultiValueMap body = new LinkedMultiValueMap(2);
		body.add("application", application);
		ObjectMapper mapper = new ObjectMapper();
		String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
		body.add("resources", knownRemoteResourcesPayload);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.MULTIPART_FORM_DATA);
		return new HttpEntity>(body, headers);
	}

	private File createTemporaryUploadFile(InputStream inputStream) throws IOException {
		File file = File.createTempFile("cfjava", null);
		FileOutputStream outputStream = new FileOutputStream(file);
		FileCopyUtils.copy(inputStream, outputStream);
		outputStream.close();
	}

	@Override
	public StartingInfo startApplication(String appName) {
		CloudApplication app = getApplication(appName);
		if (app.getState() != CloudApplication.AppState.STARTED) {
			HashMap appRequest = new HashMap();
			appRequest.put("state", CloudApplication.AppState.STARTED);

			HttpEntity requestEntity = new HttpEntity(
					appRequest);
			ResponseEntity entity = getRestTemplate().exchange(
					getUrl("/v2/apps/{guid}?stage_async=true"), HttpMethod.PUT, requestEntity,
					String.class, app.getMeta().getGuid());

			HttpHeaders headers = entity.getHeaders();

			// Return a starting info, even with a null staging log value, as a non-null starting info
			// indicates that the response entity did have headers. The API contract is to return starting info
			// if there are headers in the response, null otherwise.
			if (headers != null && !headers.isEmpty()) {
				String stagingFile = headers.getFirst("x-app-staging-log");

				if (stagingFile != null) {
					try {
						stagingFile = URLDecoder.decode(stagingFile, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						logger.error("unexpected inability to UTF-8 decode", e);
					}
				}
				// Return the starting info even if decoding failed or staging file is null
				return new StartingInfo(stagingFile);
			}
		}
		return null;
	}

	@Override
	public void debugApplication(String appName, CloudApplication.DebugMode mode) {
		throw new UnsupportedOperationException("Feature is not yet implemented.");
	}

	@Override
	public void stopApplication(String appName) {
		CloudApplication app = getApplication(appName);
		if (app.getState() != CloudApplication.AppState.STOPPED) {
			HashMap appRequest = new HashMap();
			appRequest.put("state", CloudApplication.AppState.STOPPED);
			getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, app.getMeta().getGuid());
		}
	}

	@Override
	public StartingInfo restartApplication(String appName) {
		stopApplication(appName);
		return startApplication(appName);
	}

	@Override
	public void deleteApplication(String appName) {
		UUID appId = getAppId(appName);
		doDeleteApplication(appId);
	}

	@Override
	public void deleteAllApplications() {
		List cloudApps = getApplications();
		for (CloudApplication cloudApp : cloudApps) {
			deleteApplication(cloudApp.getName());
		}
	}
	@Override
	public void updateApplicationDiskQuota(String appName, int disk) {
		UUID appId = getAppId(appName);
		HashMap appRequest = new HashMap();
		appRequest.put("disk_quota", disk);
		getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
	}

	@Override
	public void updateApplicationMemory(String appName, int memory) {
		UUID appId = getAppId(appName);
		HashMap appRequest = new HashMap();
		appRequest.put("memory", memory);
		getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
	}

	@Override
	public void updateApplicationInstances(String appName, int instances) {
		UUID appId = getAppId(appName);
		HashMap appRequest = new HashMap();
		appRequest.put("instances", instances);
		getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
	}

	@Override
	public void updateApplicationServices(String appName, List services) {
		CloudApplication app = getApplication(appName);
		List addServices = new ArrayList();
		List deleteServices = new ArrayList();
		// services to add
		for (String serviceName : services) {
			if (!app.getServices().contains(serviceName)) {
				CloudService cloudService = getService(serviceName);
				if (cloudService != null) {
					addServices.add(cloudService.getMeta().getGuid());
				}
				else {
					throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Service with name " + serviceName +
							" not found in current space " + sessionSpace.getName());
				}
			}
		}
		// services to delete
		for (String serviceName : app.getServices()) {
			if (!services.contains(serviceName)) {
				CloudService cloudService = getService(serviceName);
				if (cloudService != null) {
					deleteServices.add(cloudService.getMeta().getGuid());
				}
			}
		}
		for (UUID serviceId : addServices) {
			doBindService(app.getMeta().getGuid(), serviceId);
		}
		for (UUID serviceId : deleteServices) {
			doUnbindService(app.getMeta().getGuid(), serviceId);
		}
	}

	public List getQuotas() {
		String urlPath = "/v2/quota_definitions";
		List> resourceList = getAllResources(urlPath, null);
		List quotas = new ArrayList();
		for (Map resource : resourceList) {
			quotas.add(resourceMapper.mapResource(resource, CloudQuota.class));
		}
		return quotas;
	}

	/**
	 * Create quota from a CloudQuota instance (Quota Plan)
	 *
	 * @param quota
	 */
	public void createQuota(CloudQuota quota) {
		String setPath = "/v2/quota_definitions";
		HashMap setRequest = new HashMap();
		setRequest.put("name", quota.getName());
		setRequest.put("memory_limit", quota.getMemoryLimit());
		setRequest.put("total_routes", quota.getTotalRoutes());
		setRequest.put("total_services", quota.getTotalServices());
		setRequest.put("non_basic_services_allowed", quota.isNonBasicServicesAllowed());
		getRestTemplate().postForObject(getUrl(setPath), setRequest, String.class);
	}

	public void updateQuota(CloudQuota quota, String name) {
		CloudQuota oldQuota = this.getQuotaByName(name, true);

		String setPath = "/v2/quota_definitions/{quotaGuid}";

		Map setVars = new HashMap();
		setVars.put("quotaGuid", oldQuota.getMeta().getGuid());

		HashMap setRequest = new HashMap();
		setRequest.put("name", quota.getName());
		setRequest.put("memory_limit", quota.getMemoryLimit());
		setRequest.put("total_routes", quota.getTotalRoutes());
		setRequest.put("total_services", quota.getTotalServices());
		setRequest.put("non_basic_services_allowed", quota.isNonBasicServicesAllowed());

		getRestTemplate().put(getUrl(setPath), setRequest, setVars);
	}

	public void deleteQuota(String quotaName) {
		CloudQuota quota = this.getQuotaByName(quotaName, true);
		String setPath = "/v2/quota_definitions/{quotaGuid}";
		Map setVars = new HashMap();
		setVars.put("quotaGuid", quota.getMeta().getGuid());
		getRestTemplate().delete(getUrl(setPath), setVars);
	}

	/**
	 * Set quota to organization
	 *
	 * @param orgName
	 * @param quotaName
	 */
	public void setQuotaToOrg(String orgName, String quotaName) {
		CloudQuota quota = this.getQuotaByName(quotaName, true);
		CloudOrganization org = this.getOrgByName(orgName, true);

		doSetQuotaToOrg(org.getMeta().getGuid(), quota.getMeta().getGuid());
	}

	/**
	 * Get organization by given name.
	 *
	 * @param orgName
	 * @param required
	 * @return CloudOrganization instance
	 */
	public CloudOrganization getOrgByName(String orgName, boolean required) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/organizations?inline-relations-depth=1&q=name:{name}";
		urlVars.put("name", orgName);
		CloudOrganization org = null;
		List> resourceList = getAllResources(urlPath,
				urlVars);
		if (resourceList.size() > 0) {
			Map resource = resourceList.get(0);
			org = resourceMapper.mapResource(resource, CloudOrganization.class);
		}

		if (org == null && required) {
			throw new IllegalArgumentException("Organization '" + orgName
					+ "' not found.");
		}

		return org;
	}

	/**
	 * Get quota by given name.
	 *
	 * @param quotaName
	 * @param required
	 * @return CloudQuota instance
	 */
	public CloudQuota getQuotaByName(String quotaName, boolean required) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/quota_definitions?q=name:{name}";
		urlVars.put("name", quotaName);
		CloudQuota quota = null;
		List> resourceList = getAllResources(urlPath, urlVars);
		if (resourceList.size() > 0) {
			Map resource = resourceList.get(0);
			quota = resourceMapper.mapResource(resource, CloudQuota.class);
		}

		if (quota == null && required) {
			throw new IllegalArgumentException("Quota '" + quotaName
					+ "' not found.");
		}

		return quota;
	}

	private void doSetQuotaToOrg(UUID orgGuid, UUID quotaGuid) {
		String setPath = "/v2/organizations/{org}";
		Map setVars = new HashMap();
		setVars.put("org", orgGuid);
		HashMap setRequest = new HashMap();
		setRequest.put("quota_definition_guid", quotaGuid);

		getRestTemplate().put(getUrl(setPath), setRequest, setVars);
	}

	private void doBindService(UUID appId, UUID serviceId) {
		HashMap serviceRequest = new HashMap();
		serviceRequest.put("service_instance_guid", serviceId);
		serviceRequest.put("app_guid", appId);
		getRestTemplate().postForObject(getUrl("/v2/service_bindings"), serviceRequest, String.class);
	}

	private void doUnbindService(UUID appId, UUID serviceId) {
		UUID serviceBindingId = getServiceBindingId(appId, serviceId);
		getRestTemplate().delete(getUrl("/v2/service_bindings/{guid}"), serviceBindingId);
	}

	@Override
	public void updateApplicationStaging(String appName, Staging staging) {
		UUID appId = getAppId(appName);
		HashMap appRequest = new HashMap();
		addStagingToRequest(staging, appRequest);
		getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
	}

	@Override
	public void updateApplicationUris(String appName, List uris) {
		CloudApplication app = getApplication(appName);
		List newUris = new ArrayList(uris);
		newUris.removeAll(app.getUris());
		List removeUris = app.getUris();
		removeUris.removeAll(uris);
		removeUris(removeUris, app.getMeta().getGuid());
		addUris(newUris, app.getMeta().getGuid());
	}

	@Override
	public void updateApplicationEnv(String appName, Map env) {
		UUID appId = getAppId(appName);
		HashMap appRequest = new HashMap();
		appRequest.put("environment_json", env);
		getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
	}

	@Override
	public void updateApplicationEnv(String appName, List env) {
		Map envHash = new HashMap();
		for (String s : env) {
			if (!s.contains("=")) {
				throw new IllegalArgumentException("Environment setting without '=' is invalid: " + s);
			}
			String key = s.substring(0, s.indexOf('=')).trim();
			String value = s.substring(s.indexOf('=') + 1).trim();
			envHash.put(key, value);
		}
		updateApplicationEnv(appName, envHash);
	}

	@Override
	public List getEvents() {
		String urlPath = "/v2/events";
		return doGetEvents(urlPath, null);
	}

	@Override
	public List getApplicationEvents(String appName) {
		UUID appId = getAppId(appName);
		Map urlVars = new HashMap();
		urlVars.put("appId", appId);
		String urlPath = "/v2/events?q=actee:{appId}";
		return doGetEvents(urlPath, urlVars);
	}

	private List doGetEvents(String urlPath, Map urlVars) {
		List> resourceList = getAllResources(urlPath, urlVars);
		List events = new ArrayList();
		for (Map resource : resourceList) {
			if (resource != null) {
				events.add(resourceMapper.mapResource(resource, CloudEvent.class));
			}
		}
		return events;
	}

	@Override
	public void bindService(String appName, String serviceName) {
		CloudService cloudService = getService(serviceName);
		UUID appId = getAppId(appName);
		doBindService(appId, cloudService.getMeta().getGuid());
	}

	@Override
	public void unbindService(String appName, String serviceName) {
		CloudService cloudService = getService(serviceName);
		UUID appId = getAppId(appName);
		doUnbindService(appId, cloudService.getMeta().getGuid());
	}

	@Override
	public InstancesInfo getApplicationInstances(String appName) {
		CloudApplication app = getApplication(appName);
		return getApplicationInstances(app);
	}

	@Override
	public InstancesInfo getApplicationInstances(CloudApplication app) {
		if (app.getState().equals(CloudApplication.AppState.STARTED)) {
			return doGetApplicationInstances(app.getMeta().getGuid());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
			return sharedDomains.get(0);
	private InstancesInfo doGetApplicationInstances(UUID appId) {
		try {
			List> instanceList = new ArrayList>();
			Map respMap = getInstanceInfoForApp(appId, "instances");
			List keys = new ArrayList(respMap.keySet());
			Collections.sort(keys);
			for (String instanceId : keys) {
				Integer index;
				try {
					index = Integer.valueOf(instanceId);
				} catch (NumberFormatException e) {
					index = -1;
				}
				Map instanceMap = (Map) respMap.get(instanceId);
				instanceMap.put("index", index);
				instanceList.add(instanceMap);
			}
			return new InstancesInfo(instanceList);
		} catch (CloudFoundryException e) {
			if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
				return null;
			} else {
				throw e;
			}

		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public CrashesInfo getCrashes(String appName) {
		UUID appId = getAppId(appName);
		if (appId == null) {
			throw new IllegalArgumentException("Application '" + appName + "' not found.");
		}
		Map urlVars = new HashMap();
		urlVars.put("guid", appId);
		String resp = getRestTemplate().getForObject(getUrl("/v2/apps/{guid}/crashes"), String.class, urlVars);
		Map respMap = JsonUtil.convertJsonToMap("{ \"crashes\" : " + resp + " }");
		List> attributes = (List>) respMap.get("crashes");
		return new CrashesInfo(attributes);
	}

	@Override
	public void rename(String appName, String newName) {
		UUID appId = getAppId(appName);
		HashMap appRequest = new HashMap();
		appRequest.put("name", newName);
		getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
	}

	@Override
	public List getStacks() {
		String urlPath = "/v2/stacks";
		List> resources = getAllResources(urlPath, null);
		List stacks = new ArrayList();
		for (Map resource : resources) {
			stacks.add(resourceMapper.mapResource(resource, CloudStack.class));
		}
		return stacks;
	}

	@Override
	public CloudStack getStack(String name) {
		String urlPath = "/v2/stacks?q={q}";
		Map urlVars = new HashMap();
		urlVars.put("q", "name:" + name);
		List> resources = getAllResources(urlPath, urlVars);
		if (resources.size() > 0) {
			Map resource = resources.get(0);
			return resourceMapper.mapResource(resource, CloudStack.class);
		}
		return null;
	}

	@Override
	public List getDomainsForOrg() {
		assertSpaceProvided("access organization domains");
		return doGetDomains(sessionSpace.getOrganization());
	}

	@Override
	public List getDomains() {
		return doGetDomains((CloudOrganization) null);
	}

	@Override
	public List getPrivateDomains() {
		return doGetDomains("/v2/private_domains");
	}

	@Override
	public List getSharedDomains() {
		return doGetDomains("/v2/shared_domains");
	}

	@Override
	public CloudDomain getDefaultDomain() {
		List sharedDomains = getSharedDomains();
		if (sharedDomains.isEmpty()) {
			return null;
		} else {
		}
	}

	@Override
	public void addDomain(String domainName) {
		assertSpaceProvided("add domain");
		UUID domainGuid = getDomainGuid(domainName, false);
		if (domainGuid == null) {
			doCreateDomain(domainName);
		}
	}

	@Override
	public void deleteDomain(String domainName) {
		assertSpaceProvided("delete domain");
		UUID domainGuid = getDomainGuid(domainName, true);
		List routes = getRoutes(domainName);
		if (routes.size() > 0) {
			throw new IllegalStateException("Unable to remove domain that is in use --" +
					" it has " + routes.size() + " routes.");
		}
		doDeleteDomain(domainGuid);
	}

	@Override
	public void removeDomain(String domainName) {
		deleteDomain(domainName);
	}

	@Override
	public List getRoutes(String domainName) {
		assertSpaceProvided("get routes for domain");
		UUID domainGuid = getDomainGuid(domainName, true);
		return doGetRoutes(domainGuid);
	}

	@Override
	public void addRoute(String host, String domainName) {
		assertSpaceProvided("add route for domain");
		UUID domainGuid = getDomainGuid(domainName, true);
		doAddRoute(host, domainGuid);
	}

	@Override
	public void deleteRoute(String host, String domainName) {
		assertSpaceProvided("delete route for domain");
		UUID domainGuid = getDomainGuid(domainName, true);
		UUID routeGuid = getRouteGuid(host, domainGuid);
		if (routeGuid == null) {
			throw new IllegalArgumentException("Host '" + host + "' not found for domain '" + domainName + "'.");
		}
		doDeleteRoute(routeGuid);
	}

	protected String getFileUrlPath() {
		return "/v2/apps/{appId}/instances/{instance}/files/{filePath}";
	}

	protected Object getFileAppId(String appName) {
		return getAppId(appName);
	}

	private void assertSpaceProvided(String operation) {
		Assert.notNull(sessionSpace, "Unable to " + operation + " without specifying organization and space to use.");
	}

	private void doDeleteRoute(UUID routeGuid) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/routes/{route}";
		urlVars.put("route", routeGuid);
		getRestTemplate().delete(getUrl(urlPath), urlVars);
	}

	/**
	 * Delete routes that do not have any application which is assigned to them.
	 *
	 * @return deleted routes or an empty list if no routes have been found
	 */
	@Override
	public List deleteOrphanedRoutes() {
		List orphanRoutes = new ArrayList<>();
		for (CloudDomain cloudDomain : getDomainsForOrg()) {
			orphanRoutes.addAll(fetchOrphanRoutes(cloudDomain.getName()));
		}

		List deletedCloudRoutes = new ArrayList<>();
		for (CloudRoute orphanRoute : orphanRoutes) {
			deleteRoute(orphanRoute.getHost(), orphanRoute.getDomain().getName());
			deletedCloudRoutes.add(orphanRoute);
		}

		return deletedCloudRoutes;
	}

	private List fetchOrphanRoutes(String domainName) {
		List orphanRoutes = new ArrayList<>();
		for (CloudRoute cloudRoute : getRoutes(domainName)) {
			if (isOrphanRoute(cloudRoute)) {
				orphanRoutes.add(cloudRoute);
			}
		}

		return orphanRoutes;
	}

	private boolean isOrphanRoute(CloudRoute cloudRoute) {
		return cloudRoute.getAppsUsingRoute() == 0;
	}

	private List doGetDomains(CloudOrganization org) {
		Map urlVars = new HashMap();
		String urlPath = "/v2";
		if (org != null) {
			urlVars.put("org", org.getMeta().getGuid());
			urlPath = urlPath + "/organizations/{org}";
		}
		urlPath = urlPath + "/domains";
		return doGetDomains(urlPath, urlVars);
	}

	private List doGetDomains(String urlPath) {
		return doGetDomains(urlPath, null);
	}

	private List doGetDomains(String urlPath, Map urlVars) {
		List> domainResources = getAllResources(urlPath, urlVars);
		List domains = new ArrayList();
		for (Map resource : domainResources) {
			domains.add(resourceMapper.mapResource(resource, CloudDomain.class));
		}
		return domains;
	}

	private UUID doCreateDomain(String domainName) {
		String urlPath = "/v2/private_domains";
		HashMap domainRequest = new HashMap();
		domainRequest.put("owning_organization_guid", sessionSpace.getOrganization().getMeta().getGuid());
		domainRequest.put("name", domainName);
		domainRequest.put("wildcard", true);
		String resp = getRestTemplate().postForObject(getUrl(urlPath), domainRequest, String.class);
		Map respMap = JsonUtil.convertJsonToMap(resp);
		return resourceMapper.getGuidOfResource(respMap);
	}

	private void doDeleteDomain(UUID domainGuid) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/private_domains/{domain}";
		urlVars.put("domain", domainGuid);
		getRestTemplate().delete(getUrl(urlPath), urlVars);
	}

	private List doGetRoutes(UUID domainGuid) {
		Map urlVars = new HashMap();
		String urlPath = "/v2";
=======
    private LoggregatorClient loggregatorClient;

    private OauthClient oauthClient;

    private CloudEntityResourceMapper resourceMapper = new CloudEntityResourceMapper();

    private RestTemplate restTemplate;

    private CloudSpace sessionSpace;

    public CloudControllerClientImpl(URL cloudControllerUrl, RestTemplate restTemplate,
                                     OauthClient oauthClient, LoggregatorClient loggregatorClient,
                                     CloudCredentials cloudCredentials, CloudSpace sessionSpace) {
        logger = LogFactory.getLog(getClass().getName());

        initialize(cloudControllerUrl, restTemplate, oauthClient, loggregatorClient, cloudCredentials);

        this.sessionSpace = sessionSpace;
    }

    public CloudControllerClientImpl(URL cloudControllerUrl, RestTemplate restTemplate,
                                     OauthClient oauthClient, LoggregatorClient loggregatorClient,
                                     CloudCredentials cloudCredentials, String orgName, String spaceName) {
        logger = LogFactory.getLog(getClass().getName());
        CloudControllerClientImpl tempClient =
                new CloudControllerClientImpl(cloudControllerUrl, restTemplate,
                        oauthClient, loggregatorClient, cloudCredentials, null);

        initialize(cloudControllerUrl, restTemplate, oauthClient, loggregatorClient, cloudCredentials);

        this.sessionSpace = validateSpaceAndOrg(spaceName, orgName, tempClient);
    }

    /**
     * Only for unit tests. This works around the fact that the initialize method is called within the constructor and
     * hence can not be overloaded, making it impossible to write unit tests that don't trigger network calls.
     */
    protected CloudControllerClientImpl() {
        logger = LogFactory.getLog(getClass().getName());
    }

    @Override
    public void addDomain(String domainName) {
        assertSpaceProvided("add domain");
        UUID domainGuid = getDomainGuid(domainName, false);
        if (domainGuid == null) {
            doCreateDomain(domainName);
        }
    }

    @Override
    public void addRoute(String host, String domainName) {
        assertSpaceProvided("add route for domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        doAddRoute(host, domainGuid);
    }

    @Override
    public void bindService(String appName, String serviceName) {
        CloudService cloudService = getService(serviceName);
        UUID appId = getAppId(appName);
        doBindService(appId, cloudService.getMeta().getGuid());
    }

    @Override
    public void createApplication(String appName, Staging staging, Integer memory, List uris,
                                  List serviceNames) {
        createApplication(appName, staging, null, memory, uris, serviceNames);
    }

    @Override
    public void createApplication(String appName, Staging staging, Integer disk, Integer memory,
                                  List uris, List serviceNames) {
        HashMap appRequest = new HashMap();
        appRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        appRequest.put("name", appName);
        appRequest.put("memory", memory);
        if (disk != null) {
            appRequest.put("disk_quota", disk);
        }
        appRequest.put("instances", 1);
        addStagingToRequest(staging, appRequest);
        appRequest.put("state", CloudApplication.AppState.STOPPED);

        String appResp = getRestTemplate().postForObject(getUrl("/v2/apps"), appRequest, String.class);
        Map appEntity = JsonUtil.convertJsonToMap(appResp);
        UUID newAppGuid = CloudEntityResourceMapper.getMeta(appEntity).getGuid();

        if (serviceNames != null && serviceNames.size() > 0) {
            updateApplicationServices(appName, serviceNames);
        }

        if (uris != null && uris.size() > 0) {
            addUris(uris, newAppGuid);
        }
    }

    /**
     * Create quota from a CloudQuota instance (Quota Plan)
     *
     * @param quota
     */
    public void createQuota(CloudQuota quota) {
        String setPath = "/v2/quota_definitions";
        HashMap setRequest = new HashMap();
        setRequest.put("name", quota.getName());
        setRequest.put("memory_limit", quota.getMemoryLimit());
        setRequest.put("total_routes", quota.getTotalRoutes());
        setRequest.put("total_services", quota.getTotalServices());
        setRequest.put("non_basic_services_allowed", quota.isNonBasicServicesAllowed());
        getRestTemplate().postForObject(getUrl(setPath), setRequest, String.class);
    }

    @Override
    public void createService(CloudService service) {
        assertSpaceProvided("create service");
        Assert.notNull(service, "Service must not be null");
        Assert.notNull(service.getName(), "Service name must not be null");
        Assert.notNull(service.getLabel(), "Service label must not be null");
        Assert.notNull(service.getPlan(), "Service plan must not be null");

        CloudServicePlan cloudServicePlan = findPlanForService(service);

        HashMap serviceRequest = new HashMap();
        serviceRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        serviceRequest.put("name", service.getName());
        serviceRequest.put("service_plan_guid", cloudServicePlan.getMeta().getGuid());
        getRestTemplate().postForObject(getUrl("/v2/service_instances"), serviceRequest, String.class);
    }

    @Override
            try {
    public void createServiceBroker(CloudServiceBroker serviceBroker) {
        Assert.notNull(serviceBroker, "Service Broker must not be null");
        Assert.notNull(serviceBroker.getName(), "Service Broker name must not be null");
        Assert.notNull(serviceBroker.getUrl(), "Service Broker URL must not be null");
        Assert.notNull(serviceBroker.getUsername(), "Service Broker username must not be null");
        Assert.notNull(serviceBroker.getPassword(), "Service Broker password must not be null");

        HashMap serviceRequest = new HashMap<>();
        serviceRequest.put("name", serviceBroker.getName());
        serviceRequest.put("broker_url", serviceBroker.getUrl());
        serviceRequest.put("auth_username", serviceBroker.getUsername());
        serviceRequest.put("auth_password", serviceBroker.getPassword());
        getRestTemplate().postForObject(getUrl("/v2/service_brokers"), serviceRequest, String.class);
    }

    @Override
    public void createSpace(String spaceName) {
        UUID orgGuid = sessionSpace.getOrganization().getMeta().getGuid();
        UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
        if (spaceGuid == null) {
            doCreateSpace(spaceName, orgGuid);
        }
    }

    @Override
    public void createUserProvidedService(CloudService service, Map credentials) {
        createUserProvidedServiceDelegate(service, credentials, "");
    }

    @Override
    public void createUserProvidedService(CloudService service, Map credentials, String
            syslogDrainUrl) {
        createUserProvidedServiceDelegate(service, credentials, syslogDrainUrl);
    }

    @Override
    public void debugApplication(String appName, CloudApplication.DebugMode mode) {
        throw new UnsupportedOperationException("Feature is not yet implemented.");
    }

    @Override
    public void deleteAllApplications() {
        List cloudApps = getApplications();
        for (CloudApplication cloudApp : cloudApps) {
            deleteApplication(cloudApp.getName());
        }
    }

    @Override
    public void deleteAllServices() {
        List cloudServices = getServices();
        for (CloudService cloudService : cloudServices) {
            doDeleteService(cloudService);
        }
    }

    @Override
    public void deleteApplication(String appName) {
        UUID appId = getAppId(appName);
        doDeleteApplication(appId);
    }

    @Override
    public void deleteDomain(String domainName) {
        assertSpaceProvided("delete domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        List routes = getRoutes(domainName);
        if (routes.size() > 0) {
            throw new IllegalStateException("Unable to remove domain that is in use --" +
                    " it has " + routes.size() + " routes.");
        }
        doDeleteDomain(domainGuid);
    }

    /**
     * Delete routes that do not have any application which is assigned to them.
     *
     * @return deleted routes or an empty list if no routes have been found
     */
    @Override
    public List deleteOrphanedRoutes() {
        List orphanRoutes = new ArrayList<>();
        for (CloudDomain cloudDomain : getDomainsForOrg()) {
            orphanRoutes.addAll(fetchOrphanRoutes(cloudDomain.getName()));
        }

        List deletedCloudRoutes = new ArrayList<>();
        for (CloudRoute orphanRoute : orphanRoutes) {
            deleteRoute(orphanRoute.getHost(), orphanRoute.getDomain().getName());
            deletedCloudRoutes.add(orphanRoute);
        }

        return deletedCloudRoutes;
    }

    public void deleteQuota(String quotaName) {
        CloudQuota quota = this.getQuotaByName(quotaName, true);
        String setPath = "/v2/quota_definitions/{quotaGuid}";
        Map setVars = new HashMap();
        setVars.put("quotaGuid", quota.getMeta().getGuid());
        getRestTemplate().delete(getUrl(setPath), setVars);
    }

    @Override
    public void deleteRoute(String host, String domainName) {
        assertSpaceProvided("delete route for domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        UUID routeGuid = getRouteGuid(host, domainGuid);
        if (routeGuid == null) {
            throw new IllegalArgumentException("Host '" + host + "' not found for domain '" + domainName + "'.");
        }
        doDeleteRoute(routeGuid);
    }

    @Override
    public void deleteService(String serviceName) {
        CloudService cloudService = getService(serviceName);
        doDeleteService(cloudService);
    }

    @Override
    public void deleteServiceBroker(String name) {
        CloudServiceBroker existingBroker = getServiceBroker(name);
        Assert.notNull(existingBroker, "Cannot update broker if it does not first exist");

        getRestTemplate().delete(getUrl("/v2/service_brokers/{guid}"), existingBroker.getMeta().getGuid());
    }

    @Override
    public void deleteSpace(String spaceName) {
        UUID orgGuid = sessionSpace.getOrganization().getMeta().getGuid();
        UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
        if (spaceGuid != null) {
            doDeleteSpace(spaceGuid);
        }
    }

    @Override
    public CloudApplication getApplication(String appName) {
        Map resource = findApplicationResource(appName, true);
        if (resource == null) {
            throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Not Found", "Application not found");
        }
        return mapCloudApplication(resource);
    }

    @Override
    public CloudApplication getApplication(UUID appGuid) {
        Map resource = findApplicationResource(appGuid, true);
        if (resource == null) {
            throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Not Found", "Application not found");
        }
        return mapCloudApplication(resource);
    }

    @Override
    public InstancesInfo getApplicationInstances(String appName) {
        CloudApplication app = getApplication(appName);
        return getApplicationInstances(app);
    }

    @Override
    public InstancesInfo getApplicationInstances(CloudApplication app) {
        if (app.getState().equals(CloudApplication.AppState.STARTED)) {
            return doGetApplicationInstances(app.getMeta().getGuid());
        }
        return null;
    }

    @Override
    public ApplicationStats getApplicationStats(String appName) {
        CloudApplication app = getApplication(appName);
        return doGetApplicationStats(app.getMeta().getGuid(), app.getState());
    }

    @Override
    public List getApplications() {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlPath = urlPath + "/apps?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, urlVars);
        List apps = new ArrayList();
        for (Map resource : resourceList) {
            processApplicationResource(resource, true);
            apps.add(mapCloudApplication(resource));
        }
        return apps;
    }

    @Override
    public URL getCloudControllerUrl() {
        return this.cloudControllerUrl;
    }

    @Override
    public Map getCrashLogs(String appName) {
        String urlPath = getFileUrlPath();
        CrashesInfo crashes = getCrashes(appName);
        if (crashes.getCrashes().isEmpty()) {
            return Collections.emptyMap();
        }
        TreeMap crashInstances = new TreeMap();
        for (CrashInfo crash : crashes.getCrashes()) {
            crashInstances.put(crash.getSince(), crash.getInstance());
        }
        String instance = crashInstances.get(crashInstances.lastKey());
        return doGetLogs(urlPath, appName, instance);
    }

    @SuppressWarnings("unchecked")
    @Override
    public CrashesInfo getCrashes(String appName) {
        UUID appId = getAppId(appName);
        if (appId == null) {
            throw new IllegalArgumentException("Application '" + appName + "' not found.");
        }
        Map urlVars = new HashMap();
        urlVars.put("guid", appId);
        String resp = getRestTemplate().getForObject(getUrl("/v2/apps/{guid}/crashes"), String.class, urlVars);
        Map respMap = JsonUtil.convertJsonToMap("{ \"crashes\" : " + resp + " }");
        List> attributes = (List>) respMap.get("crashes");
        return new CrashesInfo(attributes);
    }

    @Override
    public CloudDomain getDefaultDomain() {
        List sharedDomains = getSharedDomains();
        if (sharedDomains.isEmpty()) {
            return null;
        } else {
            return sharedDomains.get(0);
        }
    }

    @Override
    public List getDomains() {
        return doGetDomains((CloudOrganization) null);
    }

    @Override
    public List getDomainsForOrg() {
        assertSpaceProvided("access organization domains");
        return doGetDomains(sessionSpace.getOrganization());
    }

    @Override
    public String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition) {
        String urlPath = getFileUrlPath();
        Object appId = getFileAppId(appName);
        return doGetFile(urlPath, appId, instanceIndex, filePath, startPosition, endPosition);
    }

    @SuppressWarnings("unchecked")
    @Override
    public CloudInfo getInfo() {
        // info comes from two end points: /info and /v2/info

        String infoV2Json = getRestTemplate().getForObject(getUrl("/v2/info"), String.class);
        Map infoV2Map = JsonUtil.convertJsonToMap(infoV2Json);

        Map userMap = getUserInfo((String) infoV2Map.get("user"));

        String infoJson = getRestTemplate().getForObject(getUrl("/info"), String.class);
        Map infoMap = JsonUtil.convertJsonToMap(infoJson);
        Map limitMap = (Map) infoMap.get("limits");
        Map usageMap = (Map) infoMap.get("usage");

        String name = CloudUtil.parse(String.class, infoV2Map.get("name"));
        String support = CloudUtil.parse(String.class, infoV2Map.get("support"));
        String authorizationEndpoint = CloudUtil.parse(String.class, infoV2Map.get("authorization_endpoint"));
        String build = CloudUtil.parse(String.class, infoV2Map.get("build"));
        String version = "" + CloudUtil.parse(Number.class, infoV2Map.get("version"));
        String description = CloudUtil.parse(String.class, infoV2Map.get("description"));

        CloudInfo.Limits limits = null;
        CloudInfo.Usage usage = null;
        boolean debug = false;
        if (oauthClient.getToken() != null) {
            limits = new CloudInfo.Limits(limitMap);
            usage = new CloudInfo.Usage(usageMap);
            debug = CloudUtil.parse(Boolean.class, infoMap.get("allow_debug"));
        }

        String loggregatorEndpoint = CloudUtil.parse(String.class, infoV2Map.get("logging_endpoint"));

        return new CloudInfo(name, support, authorizationEndpoint, build, version, (String) userMap.get("user_name"),
                description, limits, usage, debug, loggregatorEndpoint);
    }

    @Override
    public Map getLogs(String appName) {
        String urlPath = getFileUrlPath();
        String instance = String.valueOf(0);
        return doGetLogs(urlPath, appName, instance);
    }

    /**
     * Get organization by given name.
     *
     * @param orgName
     * @param required
     * @return CloudOrganization instance
     */
    public CloudOrganization getOrgByName(String orgName, boolean required) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/organizations?inline-relations-depth=1&q=name:{name}";
        urlVars.put("name", orgName);
        CloudOrganization org = null;
        List> resourceList = getAllResources(urlPath,
                urlVars);
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            org = resourceMapper.mapResource(resource, CloudOrganization.class);
        }

        if (org == null && required) {
            throw new IllegalArgumentException("Organization '" + orgName
                    + "' not found.");
        }

        return org;
    }

    @Override
    public List getOrganizations() {
        String urlPath = "/v2/organizations?inline-relations-depth=0";
        List> resourceList = getAllResources(urlPath, null);
        List orgs = new ArrayList();
        for (Map resource : resourceList) {
            orgs.add(resourceMapper.mapResource(resource, CloudOrganization.class));
        }
        return orgs;
    }

    @Override
    public List getPrivateDomains() {
        return doGetDomains("/v2/private_domains");
    }

    /**
     * Get quota by given name.
     *
     * @param quotaName
     * @param required
     * @return CloudQuota instance
     */
    public CloudQuota getQuotaByName(String quotaName, boolean required) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/quota_definitions?q=name:{name}";
        urlVars.put("name", quotaName);
        CloudQuota quota = null;
        List> resourceList = getAllResources(urlPath, urlVars);
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            quota = resourceMapper.mapResource(resource, CloudQuota.class);
        }

        if (quota == null && required) {
            throw new IllegalArgumentException("Quota '" + quotaName
                    + "' not found.");
        }

        return quota;
    }

    public List getQuotas() {
        String urlPath = "/v2/quota_definitions";
        List> resourceList = getAllResources(urlPath, null);
        List quotas = new ArrayList();
        for (Map resource : resourceList) {
            quotas.add(resourceMapper.mapResource(resource, CloudQuota.class));
        }
        return quotas;
    }

    @Override
    public List getRecentLogs(String appName) {
        UUID appId = getAppId(appName);

        String endpoint = getInfo().getLoggregatorEndpoint();
        String uri = loggregatorClient.getRecentHttpEndpoint(endpoint);

        ApplicationLogs logs = getRestTemplate().getForObject(uri + "?app={guid}", ApplicationLogs.class, appId);

        Collections.sort(logs);

        return logs;
    }

    @Override
    public List getRoutes(String domainName) {
        assertSpaceProvided("get routes for domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        return doGetRoutes(domainGuid);
    }

    @Override
    public CloudService getService(String serviceName) {
        String urlPath = "/v2";
        Map urlVars = new HashMap();
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlVars.put("q", "name:" + serviceName);
        urlPath = urlPath + "/service_instances?q={q}&return_user_provided_service_instances=true";
        List> resourceList = getAllResources(urlPath, urlVars);
        CloudService cloudService = null;
        if (resourceList.size() > 0) {
            final Map resource = resourceList.get(0);
            if (hasEmbeddedResource(resource, "service_plan")) {
                fillInEmbeddedResource(resource, "service_plan", "service");
            }
            cloudService = resourceMapper.mapResource(resource, CloudService.class);
        }
        return cloudService;
    }

    @Override
    public CloudServiceBroker getServiceBroker(String name) {
        String urlPath = "/v2/service_brokers?q={q}";
        Map urlVars = new HashMap<>();
        urlVars.put("q", "name:" + name);
        List> resourceList = getAllResources(urlPath, urlVars);
        CloudServiceBroker serviceBroker = null;
        if (resourceList.size() > 0) {
            final Map resource = resourceList.get(0);
            serviceBroker = resourceMapper.mapResource(resource, CloudServiceBroker.class);
        }
        return serviceBroker;
    }

    @Override
    public List getServiceBrokers() {
        String urlPath = "/v2/service_brokers?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, null);
        List serviceBrokers = new ArrayList();
        for (Map resource : resourceList) {
            CloudServiceBroker broker = resourceMapper.mapResource(resource, CloudServiceBroker.class);
            serviceBrokers.add(broker);
        }
        return serviceBrokers;
    }

    @Override
    public List getServiceOfferings() {
        String urlPath = "/v2/services?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, null);
        List serviceOfferings = new ArrayList();
        for (Map resource : resourceList) {
            CloudServiceOffering serviceOffering = resourceMapper.mapResource(resource, CloudServiceOffering.class);
            serviceOfferings.add(serviceOffering);
        }
        return serviceOfferings;
    }

    @Override
    public List getServices() {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlPath = urlPath + "/service_instances?inline-relations-depth=1&return_user_provided_service_instances=true";
        List> resourceList = getAllResources(urlPath, urlVars);
        List services = new ArrayList();
        for (Map resource : resourceList) {
            if (hasEmbeddedResource(resource, "service_plan")) {
                fillInEmbeddedResource(resource, "service_plan", "service");
            }
            services.add(resourceMapper.mapResource(resource, CloudService.class));
        }
        return services;
    }

    @Override
    public List getSharedDomains() {
        return doGetDomains("/v2/shared_domains");
    }

    @Override
    public CloudSpace getSpace(String spaceName) {
        String urlPath = "/v2/spaces?inline-relations-depth=1&q=name:{name}";
        HashMap spaceRequest = new HashMap();
        spaceRequest.put("name", spaceName);
        List> resourceList = getAllResources(urlPath, spaceRequest);
        CloudSpace space = null;
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            space = resourceMapper.mapResource(resource, CloudSpace.class);
        }
        return space;
    }

    @Override
    public List getSpaces() {
        String urlPath = "/v2/spaces?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, null);
        List spaces = new ArrayList();
        for (Map resource : resourceList) {
            spaces.add(resourceMapper.mapResource(resource, CloudSpace.class));
        }
        return spaces;
    }

    @Override
    public CloudStack getStack(String name) {
        String urlPath = "/v2/stacks?q={q}";
        Map urlVars = new HashMap();
        urlVars.put("q", "name:" + name);
        List> resources = getAllResources(urlPath, urlVars);
        if (resources.size() > 0) {
            Map resource = resources.get(0);
            return resourceMapper.mapResource(resource, CloudStack.class);
        }
        return null;
    }

    @Override
    public List getStacks() {
        String urlPath = "/v2/stacks";
        List> resources = getAllResources(urlPath, null);
        List stacks = new ArrayList();
        for (Map resource : resources) {
            stacks.add(resourceMapper.mapResource(resource, CloudStack.class));
        }
        return stacks;
    }

    /**
     * Returns null if no further content is available. Two errors that will lead to a null value are 404 Bad Request
     * errors, which are handled in the implementation, meaning that no further log file contents are available, or
     * ResourceAccessException, also handled in the implementation, indicating a possible timeout in the server serving
     * the content. Note that any other CloudFoundryException or RestClientException exception not related to the two
     * errors mentioned above may still be thrown (e.g. 500 level errors, Unauthorized or Forbidden exceptions, etc..)
     *
     * @return content if available, which may contain multiple lines, or null if no further content is available.
     */
    @Override
    public String getStagingLogs(StartingInfo info, int offset) {
        String stagingFile = info.getStagingFile();
        if (stagingFile != null) {
            CloudFoundryClientHttpRequestFactory cfRequestFactory = null;
                HashMap logsRequest = new HashMap();
                logsRequest.put("offset", offset);

                cfRequestFactory = getRestTemplate().getRequestFactory() instanceof
                        CloudFoundryClientHttpRequestFactory ? (CloudFoundryClientHttpRequestFactory) getRestTemplate()
                        .getRequestFactory() : null;
                if (cfRequestFactory != null) {
                    cfRequestFactory
                            .increaseReadTimeoutForStreamedTailedLogs(5 * 60 * 1000);
                }
                return getRestTemplate().getForObject(
                        stagingFile + "&tail&tail_offset={offset}",
                        String.class, logsRequest);
            } catch (CloudFoundryException e) {
                if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                    // Content is no longer available
                    return null;
                } else {
                    throw e;
                }
            } catch (ResourceAccessException e) {
                // Likely read timeout, the directory server won't serve
                // the content again
                logger.debug("Caught exception while fetching staging logs. Aborting. Caught:" + e,
                        e);
            } finally {
                if (cfRequestFactory != null) {
                        stagingFile = URLDecoder.decode(stagingFile, "UTF-8");
                    cfRequestFactory
                            .increaseReadTimeoutForStreamedTailedLogs(-1);
                }
            }
        }
        return null;
    }

    @Override
    public OAuth2AccessToken login() {
        oauthClient.init(cloudCredentials);
        return oauthClient.getToken();
    }

    @Override
    public void logout() {
        oauthClient.clear();
    }

    @Override
    public void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback callback) {
        String urlPath = getFileUrlPath();
        Object appId = getFileAppId(appName);
        doOpenFile(urlPath, appId, instanceIndex, filePath, callback);
    }

    @Override
    public void register(String email, String password) {
        throw new UnsupportedOperationException("Feature is not yet implemented.");
    }

    @Override
    public void registerRestLogListener(RestLogCallback callBack) {
        if (getRestTemplate() instanceof LoggingRestTemplate) {
            ((LoggingRestTemplate) getRestTemplate()).registerRestLogListener(callBack);
        }
    }

    @Override
    public void removeDomain(String domainName) {
        deleteDomain(domainName);
    }

    @Override
    public void rename(String appName, String newName) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("name", newName);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public StartingInfo restartApplication(String appName) {
        stopApplication(appName);
        return startApplication(appName);
    }

    /**
     * Set quota to organization
     *
     * @param orgName
     * @param quotaName
     */
    public void setQuotaToOrg(String orgName, String quotaName) {
        CloudQuota quota = this.getQuotaByName(quotaName, true);
        CloudOrganization org = this.getOrgByName(orgName, true);

        doSetQuotaToOrg(org.getMeta().getGuid(), quota.getMeta().getGuid());
    }

    @Override
    public void setResponseErrorHandler(ResponseErrorHandler errorHandler) {
        this.restTemplate.setErrorHandler(errorHandler);
    }

    @Override
    public StartingInfo startApplication(String appName) {
        CloudApplication app = getApplication(appName);
        if (app.getState() != CloudApplication.AppState.STARTED) {
            HashMap appRequest = new HashMap();
            appRequest.put("state", CloudApplication.AppState.STARTED);

            HttpEntity requestEntity = new HttpEntity(
                    appRequest);
            ResponseEntity entity = getRestTemplate().exchange(
                    getUrl("/v2/apps/{guid}?stage_async=true"), HttpMethod.PUT, requestEntity,
                    String.class, app.getMeta().getGuid());

            HttpHeaders headers = entity.getHeaders();

            // Return a starting info, even with a null staging log value, as a non-null starting info
            // indicates that the response entity did have headers. The API contract is to return starting info
            // if there are headers in the response, null otherwise.
            if (headers != null && !headers.isEmpty()) {
                String stagingFile = headers.getFirst("x-app-staging-log");

                if (stagingFile != null) {
                    try {
                    } catch (UnsupportedEncodingException e) {
                        logger.error("unexpected inability to UTF-8 decode", e);
                    }
                }
                // Return the starting info even if decoding failed or staging file is null
                return new StartingInfo(stagingFile);
            }
        }
        return null;
    }

    @Override
    public void stopApplication(String appName) {
        CloudApplication app = getApplication(appName);
        if (app.getState() != CloudApplication.AppState.STOPPED) {
            HashMap appRequest = new HashMap();
            appRequest.put("state", CloudApplication.AppState.STOPPED);
            getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, app.getMeta().getGuid());
        }
    }

    @Override
    public StreamingLogToken streamLogs(String appName, ApplicationLogListener listener) {
        return streamLoggregatorLogs(appName, listener, false);
    }

    @Override
    public void unRegisterRestLogListener(RestLogCallback callBack) {
        if (getRestTemplate() instanceof LoggingRestTemplate) {
            ((LoggingRestTemplate) getRestTemplate()).unRegisterRestLogListener(callBack);
        }
    }

    @Override
    public void unbindService(String appName, String serviceName) {
        CloudService cloudService = getService(serviceName);
        UUID appId = getAppId(appName);
        doUnbindService(appId, cloudService.getMeta().getGuid());
    }

    @Override
    public void unregister() {
        throw new UnsupportedOperationException("Feature is not yet implemented.");
    }

    @Override
    public void updateApplicationDiskQuota(String appName, int disk) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("disk_quota", disk);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationEnv(String appName, Map env) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("environment_json", env);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationEnv(String appName, List env) {
        Map envHash = new HashMap();
        for (String s : env) {
            if (!s.contains("=")) {
                throw new IllegalArgumentException("Environment setting without '=' is invalid: " + s);
            }
            String key = s.substring(0, s.indexOf('=')).trim();
            String value = s.substring(s.indexOf('=') + 1).trim();
            envHash.put(key, value);
        }
        updateApplicationEnv(appName, envHash);
    }

    @Override
    public void updateApplicationInstances(String appName, int instances) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("instances", instances);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationMemory(String appName, int memory) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("memory", memory);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationServices(String appName, List services) {
        CloudApplication app = getApplication(appName);
        List addServices = new ArrayList();
        List deleteServices = new ArrayList();
        // services to add
        for (String serviceName : services) {
            if (!app.getServices().contains(serviceName)) {
                CloudService cloudService = getService(serviceName);
                if (cloudService != null) {
                    addServices.add(cloudService.getMeta().getGuid());
                } else {
                    throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Service with name " + serviceName +
                            " not found in current space " + sessionSpace.getName());
                }
            }
        }
        // services to delete
        for (String serviceName : app.getServices()) {
            if (!services.contains(serviceName)) {
                CloudService cloudService = getService(serviceName);
                if (cloudService != null) {
                    deleteServices.add(cloudService.getMeta().getGuid());
                }
            }
        }
        for (UUID serviceId : addServices) {
            doBindService(app.getMeta().getGuid(), serviceId);
        }
        for (UUID serviceId : deleteServices) {
            doUnbindService(app.getMeta().getGuid(), serviceId);
        }
    }

    @Override
    public void updateApplicationStaging(String appName, Staging staging) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        addStagingToRequest(staging, appRequest);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationUris(String appName, List uris) {
        CloudApplication app = getApplication(appName);
        List newUris = new ArrayList(uris);
        newUris.removeAll(app.getUris());
        List removeUris = app.getUris();
        removeUris.removeAll(uris);
        removeUris(removeUris, app.getMeta().getGuid());
        addUris(newUris, app.getMeta().getGuid());
    }

    @Override
    public void updatePassword(String newPassword) {
        updatePassword(cloudCredentials, newPassword);
    }

    @Override
    public void updatePassword(CloudCredentials credentials, String newPassword) {
        oauthClient.changePassword(credentials.getPassword(), newPassword);
        CloudCredentials newCloudCredentials = new CloudCredentials(credentials.getEmail(), newPassword);
        if (cloudCredentials.getProxyUser() != null) {
            cloudCredentials = newCloudCredentials.proxyForUser(cloudCredentials.getProxyUser());
        } else {
            cloudCredentials = newCloudCredentials;
        }
    }

    public void updateQuota(CloudQuota quota, String name) {
        CloudQuota oldQuota = this.getQuotaByName(name, true);

        String setPath = "/v2/quota_definitions/{quotaGuid}";

        Map setVars = new HashMap();
        setVars.put("quotaGuid", oldQuota.getMeta().getGuid());

        HashMap setRequest = new HashMap();
        setRequest.put("name", quota.getName());
        setRequest.put("memory_limit", quota.getMemoryLimit());
        setRequest.put("total_routes", quota.getTotalRoutes());
        setRequest.put("total_services", quota.getTotalServices());
        setRequest.put("non_basic_services_allowed", quota.isNonBasicServicesAllowed());

        getRestTemplate().put(getUrl(setPath), setRequest, setVars);
    }

    @Override
    public void updateServiceBroker(CloudServiceBroker serviceBroker) {
        Assert.notNull(serviceBroker, "Service Broker must not be null");
        Assert.notNull(serviceBroker.getName(), "Service Broker name must not be null");
        Assert.notNull(serviceBroker.getUrl(), "Service Broker URL must not be null");
        Assert.notNull(serviceBroker.getUsername(), "Service Broker username must not be null");
        Assert.notNull(serviceBroker.getPassword(), "Service Broker password must not be null");

        CloudServiceBroker existingBroker = getServiceBroker(serviceBroker.getName());
        Assert.notNull(existingBroker, "Cannot update broker if it does not first exist");

        HashMap serviceRequest = new HashMap<>();
        serviceRequest.put("name", serviceBroker.getName());
        serviceRequest.put("broker_url", serviceBroker.getUrl());
        serviceRequest.put("auth_username", serviceBroker.getUsername());
        serviceRequest.put("auth_password", serviceBroker.getPassword());
        getRestTemplate().put(getUrl("/v2/service_brokers/{guid}"), serviceRequest, existingBroker.getMeta().getGuid());
    }

    @Override
    public void updateServicePlanVisibilityForBroker(String name, boolean visibility) {
        CloudServiceBroker broker = getServiceBroker(name);

        String urlPath = "/v2/services?q={q}";
        Map urlVars = new HashMap<>();
        urlVars.put("q", "service_broker_guid:" + broker.getMeta().getGuid());
        List> serviceResourceList = getAllResources(urlPath, urlVars);

        for (Map serviceResource : serviceResourceList) {
            Map metadata = (Map) serviceResource.get("metadata");
            String serviceGuid = (String) metadata.get("guid");

            urlPath = "/v2/service_plans?q={q}";
            urlVars = new HashMap<>();
            urlVars.put("q", "service_guid:" + serviceGuid);
            List> planResourceList = getAllResources(urlPath, urlVars);
            for (Map planResource : planResourceList) {
                metadata = (Map) planResource.get("metadata");
                String planGuid = (String) metadata.get("guid");

                HashMap planUpdateRequest = new HashMap<>();
                planUpdateRequest.put("public", visibility);
                getRestTemplate().put(getUrl("/v2/service_plans/{guid}"), planUpdateRequest, planGuid);
            }
        }
    }

    @Override
    public void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException {
        Assert.notNull(file, "File must not be null");
        if (file.isDirectory()) {
            ApplicationArchive archive = new DirectoryApplicationArchive(file);
            uploadApplication(appName, archive, callback);
        } else {
            try (ZipFile zipFile = new ZipFile(file)) {
                ApplicationArchive archive = new ZipApplicationArchive(zipFile);
                uploadApplication(appName, archive, callback);
            }
        }
    }

    @Override
        }
    public void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback
            callback) throws IOException {
        Assert.notNull(fileName, "FileName must not be null");
        Assert.notNull(inputStream, "InputStream must not be null");

        File file = createTemporaryUploadFile(inputStream);

        try (ZipFile zipFile = new ZipFile(file)) {
            ApplicationArchive archive = new ZipApplicationArchive(zipFile);
            uploadApplication(appName, archive, callback);
        }
    }

    @Override
    public void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback)
            throws IOException {
        Assert.notNull(appName, "AppName must not be null");
        Assert.notNull(archive, "Archive must not be null");
        UUID appId = getAppId(appName);

        if (callback == null) {
            callback = UploadStatusCallback.NONE;
        }
        CloudResources knownRemoteResources = getKnownRemoteResources(archive);
        callback.onCheckResources();
        callback.onMatchedFileNames(knownRemoteResources.getFilenames());
        UploadApplicationPayload payload = new UploadApplicationPayload(archive, knownRemoteResources);
        callback.onProcessMatchedResources(payload.getTotalUncompressedSize());
        HttpEntity entity = generatePartialResourceRequest(payload, knownRemoteResources);
        ResponseEntity>> responseEntity =
                getRestTemplate().exchange(getUrl("/v2/apps/{guid}/bits?async=true"), HttpMethod.PUT, entity,
                        new ParameterizedTypeReference>>() {
                        }, appId);
        processAsyncJob(responseEntity, callback);
    }

    protected void configureCloudFoundryRequestFactory(RestTemplate restTemplate) {
        ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory();
        if (!(requestFactory instanceof CloudFoundryClientHttpRequestFactory)) {
            restTemplate.setRequestFactory(
                    new CloudFoundryClientHttpRequestFactory(requestFactory));
        }
    }

    protected String doGetFile(String urlPath, Object app, int instanceIndex, String filePath, int startPosition, int
            endPosition) {
        return doGetFile(urlPath, app, String.valueOf(instanceIndex), filePath, startPosition, endPosition);
    }

    protected String doGetFile(String urlPath, Object app, String instance, String filePath, int startPosition, int
            endPosition) {
        Assert.isTrue(startPosition >= -1, "Invalid start position value: " + startPosition);
        Assert.isTrue(endPosition >= -1, "Invalid end position value: " + endPosition);
        Assert.isTrue(startPosition < 0 || endPosition < 0 || endPosition >= startPosition,
                "The end position (" + endPosition + ") can't be less than the start position (" + startPosition + ")");

        int start, end;
        if (startPosition == -1 && endPosition == -1) {
            start = 0;
            end = -1;
        } else {
            start = startPosition;
            end = endPosition;
        }

        final String range =
                "bytes=" + (start == -1 ? "" : start) + "-" + (end == -1 ? "" : end);

        return doGetFileByRange(urlPath, app, instance, filePath, start, end, range);
    }

    protected Map doGetLogs(String urlPath, String appName, String instance) {
        Object appId = getFileAppId(appName);
        String logFiles = doGetFile(urlPath, appId, instance, LOGS_LOCATION, -1, -1);
        String[] lines = logFiles.split("\n");
        List fileNames = new ArrayList();
        for (String line : lines) {
            String[] parts = line.split("\\s");
            if (parts.length > 0 && parts[0] != null) {
                fileNames.add(parts[0]);
            }
        }
        Map logs = new HashMap(fileNames.size());
        for (String fileName : fileNames) {
    }
            String logFile = LOGS_LOCATION + "/" + fileName;
            logs.put(logFile, doGetFile(urlPath, appId, instance, logFile, -1, -1));
        }
        return logs;
    }

    @SuppressWarnings("unchecked")
    protected void doOpenFile(String urlPath, Object app, int instanceIndex, String filePath,
                              ClientHttpResponseCallback callback) {
        getRestTemplate().execute(getUrl(urlPath), HttpMethod.GET, null, new ResponseExtractorWrapper(callback), app,
                String.valueOf(instanceIndex), filePath);
    }

    protected void extractUriInfo(Map domains, String uri, Map uriInfo) {
        URI newUri = URI.create(uri);
        String authority = newUri.getScheme() != null ? newUri.getAuthority() : newUri.getPath();
        for (String domain : domains.keySet()) {
            if (authority != null && authority.endsWith(domain)) {
                String previousDomain = uriInfo.get("domainName");
                if (previousDomain == null || domain.length() > previousDomain.length()) {
                    //Favor most specific subdomains
                    uriInfo.put("domainName", domain);
                    if (domain.length() < authority.length()) {
                        uriInfo.put("host", authority.substring(0, authority.indexOf(domain) - 1));
                    } else if (domain.length() == authority.length()) {
                        uriInfo.put("host", "");
                    }
                }
            }
        }
        if (uriInfo.get("domainName") == null) {
            throw new IllegalArgumentException("Domain not found for URI " + uri);
        }
        if (uriInfo.get("host") == null) {
            throw new IllegalArgumentException("Invalid URI " + uri +
                    " -- host not specified for domain " + uriInfo.get("domainName"));
        }
    }

    protected Object getFileAppId(String appName) {
        return getAppId(appName);
    }

    protected String getFileUrlPath() {
        return "/v2/apps/{appId}/instances/{instance}/files/{filePath}";
    }

    protected RestTemplate getRestTemplate() {
        return this.restTemplate;
    }

    protected String getUrl(String path) {
        return cloudControllerUrl + (path.startsWith("/") ? path : "/" + path);
    }

    @SuppressWarnings("unchecked")
    private String addPageOfResources(String nextUrl, List> allResources) {
        String resp = getRestTemplate().getForObject(getUrl(nextUrl), String.class);
        Map respMap = JsonUtil.convertJsonToMap(resp);
        List> newResources = (List>) respMap.get("resources");
        if (newResources != null && newResources.size() > 0) {
            allResources.addAll(newResources);
        }
        return (String) respMap.get("next_url");
    }

    private void addStagingToRequest(Staging staging, HashMap appRequest) {
        if (staging.getBuildpackUrl() != null) {
            appRequest.put("buildpack", staging.getBuildpackUrl());
        }
        if (staging.getCommand() != null) {
            appRequest.put("command", staging.getCommand());
        }
        if (staging.getStack() != null) {
            appRequest.put("stack_guid", getStack(staging.getStack()).getMeta().getGuid());
        }
        if (staging.getHealthCheckTimeout() != null) {
            appRequest.put("health_check_timeout", staging.getHealthCheckTimeout());
        }
    }

    private void addUris(List uris, UUID appGuid) {
        Map domains = getDomainGuids();
        for (String uri : uris) {
            Map uriInfo = new HashMap(2);
            extractUriInfo(domains, uri, uriInfo);
            UUID domainGuid = domains.get(uriInfo.get("domainName"));
            bindRoute(uriInfo.get("host"), domainGuid, appGuid);

    private void assertSpaceProvided(String operation) {
        Assert.notNull(sessionSpace, "Unable to " + operation + " without specifying organization and space to use.");
    }

    private void bindRoute(String host, UUID domainGuid, UUID appGuid) {
        UUID routeGuid = getRouteGuid(host, domainGuid);
        if (routeGuid == null) {
            routeGuid = doAddRoute(host, domainGuid);
        }
        String bindPath = "/v2/apps/{app}/routes/{route}";
        Map bindVars = new HashMap();
        bindVars.put("app", appGuid);
        bindVars.put("route", routeGuid);
        HashMap bindRequest = new HashMap();
        getRestTemplate().put(getUrl(bindPath), bindRequest, bindVars);
    }

    private File createTemporaryUploadFile(InputStream inputStream) throws IOException {
        File file = File.createTempFile("cfjava", null);
        file.deleteOnExit();
        FileOutputStream outputStream = new FileOutputStream(file);
        FileCopyUtils.copy(inputStream, outputStream);
        outputStream.close();
        return file;
    }

    private void createUserProvidedServiceDelegate(CloudService service, Map credentials, String
            syslogDrainUrl) {
        assertSpaceProvided("create service");
        Assert.notNull(credentials, "Service credentials must not be null");
        Assert.notNull(service, "Service must not be null");
        Assert.notNull(service.getName(), "Service name must not be null");
        Assert.isNull(service.getLabel(), "Service label is not valid for user-provided services");
        Assert.isNull(service.getProvider(), "Service provider is not valid for user-provided services");
        Assert.isNull(service.getVersion(), "Service version is not valid for user-provided services");
        Assert.isNull(service.getPlan(), "Service plan is not valid for user-provided services");

        HashMap serviceRequest = new HashMap<>();
        serviceRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        serviceRequest.put("name", service.getName());
        serviceRequest.put("credentials", credentials);
        if (syslogDrainUrl != null && !syslogDrainUrl.equals("")) {
            serviceRequest.put("syslog_drain_url", syslogDrainUrl);
        }

        getRestTemplate().postForObject(getUrl("/v2/user_provided_service_instances"), serviceRequest, String.class);
    }

    private UUID doAddRoute(String host, UUID domainGuid) {
        assertSpaceProvided("add route");

        HashMap routeRequest = new HashMap();
        routeRequest.put("host", host);
        routeRequest.put("domain_guid", domainGuid);
        routeRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        String routeResp = getRestTemplate().postForObject(getUrl("/v2/routes"), routeRequest, String.class);
        Map routeEntity = JsonUtil.convertJsonToMap(routeResp);
        return CloudEntityResourceMapper.getMeta(routeEntity).getGuid();
    }

    private void doBindService(UUID appId, UUID serviceId) {
        HashMap serviceRequest = new HashMap();
        serviceRequest.put("service_instance_guid", serviceId);
        serviceRequest.put("app_guid", appId);
        getRestTemplate().postForObject(getUrl("/v2/service_bindings"), serviceRequest, String.class);
    }

    private UUID doCreateDomain(String domainName) {
        String urlPath = "/v2/private_domains";
        HashMap domainRequest = new HashMap();
        domainRequest.put("owning_organization_guid", sessionSpace.getOrganization().getMeta().getGuid());
        domainRequest.put("name", domainName);
        domainRequest.put("wildcard", true);
        String resp = getRestTemplate().postForObject(getUrl(urlPath), domainRequest, String.class);
        Map respMap = JsonUtil.convertJsonToMap(resp);
        return resourceMapper.getGuidOfResource(respMap);
    }

    private UUID doCreateSpace(String spaceName, UUID orgGuid) {
        String urlPath = "/v2/spaces";
        HashMap spaceRequest = new HashMap();
        spaceRequest.put("organization_guid", orgGuid);
        spaceRequest.put("name", spaceName);
        String resp = getRestTemplate().postForObject(getUrl(urlPath), spaceRequest, String.class);
        Map respMap = JsonUtil.convertJsonToMap(resp);
        return resourceMapper.getGuidOfResource(respMap);
    }

    private void doDeleteApplication(UUID appId) {
        getRestTemplate().delete(getUrl("/v2/apps/{guid}?recursive=true"), appId);
    }

    private void doDeleteDomain(UUID domainGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/private_domains/{domain}";
        urlVars.put("domain", domainGuid);
        getRestTemplate().delete(getUrl(urlPath), urlVars);
    }

    private void doDeleteRoute(UUID routeGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/routes/{route}";
        urlVars.put("route", routeGuid);
        getRestTemplate().delete(getUrl(urlPath), urlVars);
    }

    private void doDeleteService(CloudService cloudService) {
        List appIds = getAppsBoundToService(cloudService);
        if (appIds.size() > 0) {
            for (UUID appId : appIds) {
                doUnbindService(appId, cloudService.getMeta().getGuid());
            }
        }
        getRestTemplate().delete(getUrl("/v2/service_instances/{guid}"), cloudService.getMeta().getGuid());
    }

    private void doDeleteSpace(UUID spaceGuid) {
        getRestTemplate().delete(getUrl("/v2/spaces/{guid}?async=false"), spaceGuid);
    }

    @SuppressWarnings("unchecked")
    private InstancesInfo doGetApplicationInstances(UUID appId) {
        try {
            List> instanceList = new ArrayList>();
            Map respMap = getInstanceInfoForApp(appId, "instances");
            List keys = new ArrayList(respMap.keySet());
            Collections.sort(keys);
            for (String instanceId : keys) {
                Integer index;
                try {
                    index = Integer.valueOf(instanceId);
                } catch (NumberFormatException e) {
                    index = -1;
                }
                Map instanceMap = (Map) respMap.get(instanceId);
                instanceMap.put("index", index);
                instanceList.add(instanceMap);
            }
            return new InstancesInfo(instanceList);
        } catch (CloudFoundryException e) {
            if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
                return null;
            } else {
                throw e;
            }

        }
    }

    @SuppressWarnings("unchecked")
    private ApplicationStats doGetApplicationStats(UUID appId, CloudApplication.AppState appState) {
        List instanceList = new ArrayList();
        if (appState.equals(CloudApplication.AppState.STARTED)) {
            Map respMap = getInstanceInfoForApp(appId, "stats");
            for (String instanceId : respMap.keySet()) {
                InstanceStats instanceStats =
                        new InstanceStats(instanceId, (Map) respMap.get(instanceId));
                instanceList.add(instanceStats);
            }
        }
        return new ApplicationStats(instanceList);
    }

    private List doGetDomains(CloudOrganization org) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (org != null) {
            urlVars.put("org", org.getMeta().getGuid());
            urlPath = urlPath + "/organizations/{org}";
        }
        urlPath = urlPath + "/domains";
        return doGetDomains(urlPath, urlVars);
    }

    private List doGetDomains(String urlPath) {
        return doGetDomains(urlPath, null);
    }

    private List doGetDomains(String urlPath, Map urlVars) {
        List> domainResources = getAllResources(urlPath, urlVars);
        List domains = new ArrayList();
        for (Map resource : domainResources) {
            domains.add(resourceMapper.mapResource(resource, CloudDomain.class));
        }
        return domains;
    }

    private String doGetFileByRange(String urlPath, Object app, String instance, String filePath, int start, int end,
                                    String range) {

        boolean supportsRanges;
        try {
            supportsRanges = getRestTemplate().execute(getUrl(urlPath),
                    HttpMethod.HEAD,
                    new RequestCallback() {
                        public void doWithRequest(ClientHttpRequest request) throws IOException {
                            request.getHeaders().set("Range", "bytes=0-");
                        }
                    },
                    new ResponseExtractor() {
                        public Boolean extractData(ClientHttpResponse response) throws IOException {
                            return response.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT);
                        }
                    },
                    app, instance, filePath);
        } catch (CloudFoundryException e) {
            if (e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)) {
                // must be a 0 byte file
                return "";
            } else {
                throw e;
            }
        }
        HttpHeaders headers = new HttpHeaders();
        if (supportsRanges) {
            headers.set("Range", range);
        }
        HttpEntity requestEntity = new HttpEntity(headers);
        ResponseEntity responseEntity = getRestTemplate().exchange(getUrl(urlPath),
                HttpMethod.GET, requestEntity, String.class, app, instance, filePath);
        String response = responseEntity.getBody();
        boolean partialFile = false;
        if (responseEntity.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT)) {
            partialFile = true;
        }
        if (!partialFile && response != null) {
            if (start == -1) {
                return response.substring(response.length() - end);
            } else {
                if (start >= response.length()) {
                    if (response.length() == 0) {
                        return "";
                    }
                    throw new CloudFoundryException(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
                            "The starting position " + start + " is past the end of the file content.");
                }
                if (end != -1) {
                    if (end >= response.length()) {
                        end = response.length() - 1;
                    }
                    return response.substring(start, end + 1);
                } else {
                    return response.substring(start);
                }
            }
        }
        return response;
    }

    private List doGetRoutes(UUID domainGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
//		TODO: NOT implemented ATM:
//		if (sessionSpace != null) {
//			urlVars.put("space", sessionSpace.getMeta().getGuid());
Solution content
        deleteDomain(domainName);

    private URL cloudControllerUrl;

    private LoggregatorClient loggregatorClient;

    private OauthClient oauthClient;

    private CloudEntityResourceMapper resourceMapper = new CloudEntityResourceMapper();

    private RestTemplate restTemplate;

    private CloudSpace sessionSpace;

    public CloudControllerClientImpl(URL cloudControllerUrl, RestTemplate restTemplate,
                                     OauthClient oauthClient, LoggregatorClient loggregatorClient,
                                     CloudCredentials cloudCredentials, CloudSpace sessionSpace) {
        logger = LogFactory.getLog(getClass().getName());

        initialize(cloudControllerUrl, restTemplate, oauthClient, loggregatorClient, cloudCredentials);

        this.sessionSpace = sessionSpace;
    }

    public CloudControllerClientImpl(URL cloudControllerUrl, RestTemplate restTemplate,
                                     OauthClient oauthClient, LoggregatorClient loggregatorClient,
                                     CloudCredentials cloudCredentials, String orgName, String spaceName) {
        logger = LogFactory.getLog(getClass().getName());
        CloudControllerClientImpl tempClient =
                new CloudControllerClientImpl(cloudControllerUrl, restTemplate,
                        oauthClient, loggregatorClient, cloudCredentials, null);

        initialize(cloudControllerUrl, restTemplate, oauthClient, loggregatorClient, cloudCredentials);

        this.sessionSpace = validateSpaceAndOrg(spaceName, orgName, tempClient);
    }

    /**
     * Only for unit tests. This works around the fact that the initialize method is called within the constructor and
     * hence can not be overloaded, making it impossible to write unit tests that don't trigger network calls.
     */
    protected CloudControllerClientImpl() {
        logger = LogFactory.getLog(getClass().getName());
    }

    @Override
    public void addDomain(String domainName) {
        assertSpaceProvided("add domain");
        UUID domainGuid = getDomainGuid(domainName, false);
        if (domainGuid == null) {
            doCreateDomain(domainName);
        }
    }

    @Override
    public void addRoute(String host, String domainName) {
        assertSpaceProvided("add route for domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        doAddRoute(host, domainGuid);
    }

    @Override
    public void associateAuditorWithSpace(String orgName, String spaceName, String userGuid) {
        String urlPath = "/v2/spaces/{guid}/auditors/{userGuid}";
        associateRoleWithSpace(orgName, spaceName, userGuid, urlPath);
    }

    @Override
    public void associateDeveloperWithSpace(String orgName, String spaceName, String userGuid) {
        String urlPath = "/v2/spaces/{guid}/developers/{userGuid}";
        associateRoleWithSpace(orgName, spaceName, userGuid, urlPath);
    }

    @Override
    public void associateManagerWithSpace(String orgName, String spaceName, String userGuid) {
        String urlPath = "/v2/spaces/{guid}/managers/{userGuid}";
        associateRoleWithSpace(orgName, spaceName, userGuid, urlPath);
    }

    @Override
    public void bindRunningSecurityGroup(String securityGroupName) {
        CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

        String path = "/v2/config/running_security_groups/{guid}";

        Map pathVariables = new HashMap();
        pathVariables.put("guid", group.getMeta().getGuid());

        getRestTemplate().put(getUrl(path), null, pathVariables);
    }

    @Override
    public void bindSecurityGroup(String orgName, String spaceName, String securityGroupName) {
        UUID spaceGuid = getSpaceGuid(orgName, spaceName);
        CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

        String path = "/v2/security_groups/{group_guid}/spaces/{space_guid}";

        Map pathVariables = new HashMap();
        pathVariables.put("group_guid", group.getMeta().getGuid());
        pathVariables.put("space_guid", spaceGuid);

        getRestTemplate().put(getUrl(path), null, pathVariables);
    }

    @Override
    public void bindService(String appName, String serviceName) {
        CloudService cloudService = getService(serviceName);
        UUID appId = getAppId(appName);
        doBindService(appId, cloudService.getMeta().getGuid());
    }

    @Override
    public void bindStagingSecurityGroup(String securityGroupName) {
        CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

        String path = "/v2/config/staging_security_groups/{guid}";

        Map pathVariables = new HashMap();
        pathVariables.put("guid", group.getMeta().getGuid());

        getRestTemplate().put(getUrl(path), null, pathVariables);
    }

    @Override
    public void createApplication(String appName, Staging staging, Integer memory, List uris,
                                  List serviceNames) {
        createApplication(appName, staging, null, memory, uris, serviceNames);
    }

    @Override

    public void createApplication(String appName, Staging staging, Integer disk, Integer memory,
                                  List uris, List serviceNames) {
        HashMap appRequest = new HashMap();
        appRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        appRequest.put("name", appName);
        appRequest.put("memory", memory);
        if (disk != null) {
            appRequest.put("disk_quota", disk);
        }
        appRequest.put("instances", 1);
        addStagingToRequest(staging, appRequest);
        appRequest.put("state", CloudApplication.AppState.STOPPED);

        String appResp = getRestTemplate().postForObject(getUrl("/v2/apps"), appRequest, String.class);
        Map appEntity = JsonUtil.convertJsonToMap(appResp);
        UUID newAppGuid = CloudEntityResourceMapper.getMeta(appEntity).getGuid();

        if (serviceNames != null && serviceNames.size() > 0) {
            updateApplicationServices(appName, serviceNames);
        }

        if (uris != null && uris.size() > 0) {
            addUris(uris, newAppGuid);
        }
    }

    /**
     * Create quota from a CloudQuota instance (Quota Plan)
     *
     * @param quota
     */
    public void createQuota(CloudQuota quota) {
        String setPath = "/v2/quota_definitions";
        HashMap setRequest = new HashMap();
        setRequest.put("name", quota.getName());
        setRequest.put("memory_limit", quota.getMemoryLimit());
        setRequest.put("total_routes", quota.getTotalRoutes());
        setRequest.put("total_services", quota.getTotalServices());
        setRequest.put("non_basic_services_allowed", quota.isNonBasicServicesAllowed());
        getRestTemplate().postForObject(getUrl(setPath), setRequest, String.class);
    }

    @Override
    public void createSecurityGroup(CloudSecurityGroup securityGroup) {
        doCreateSecurityGroup(securityGroup.getName(),
                convertToList(securityGroup.getRules()));
    }

    @Override
    public void createSecurityGroup(String name, InputStream jsonRulesFile) {
        doCreateSecurityGroup(name, JsonUtil.convertToJsonList(jsonRulesFile));
    }

    @Override
    public void createService(CloudService service) {
        assertSpaceProvided("create service");
        Assert.notNull(service, "Service must not be null");
        Assert.notNull(service.getName(), "Service name must not be null");
        Assert.notNull(service.getLabel(), "Service label must not be null");
        Assert.notNull(service.getPlan(), "Service plan must not be null");

        CloudServicePlan cloudServicePlan = findPlanForService(service);

        HashMap serviceRequest = new HashMap();
        serviceRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        serviceRequest.put("name", service.getName());
        serviceRequest.put("service_plan_guid", cloudServicePlan.getMeta().getGuid());
        getRestTemplate().postForObject(getUrl("/v2/service_instances"), serviceRequest, String.class);
    }

    @Override
    public void createServiceBroker(CloudServiceBroker serviceBroker) {
        Assert.notNull(serviceBroker, "Service Broker must not be null");
        Assert.notNull(serviceBroker.getName(), "Service Broker name must not be null");
        Assert.notNull(serviceBroker.getUrl(), "Service Broker URL must not be null");
        Assert.notNull(serviceBroker.getUsername(), "Service Broker username must not be null");
        Assert.notNull(serviceBroker.getPassword(), "Service Broker password must not be null");

        HashMap serviceRequest = new HashMap<>();
        serviceRequest.put("name", serviceBroker.getName());
        serviceRequest.put("broker_url", serviceBroker.getUrl());
        serviceRequest.put("auth_username", serviceBroker.getUsername());
        serviceRequest.put("auth_password", serviceBroker.getPassword());
        getRestTemplate().postForObject(getUrl("/v2/service_brokers"), serviceRequest, String.class);
    }
    @Override
    public void createSpace(String spaceName) {
        assertSpaceProvided("create a new space");
        UUID orgGuid = sessionSpace.getOrganization().getMeta().getGuid();
        UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
        if (spaceGuid == null) {
            doCreateSpace(spaceName, orgGuid);
        }
    }

    @Override
    public void createUserProvidedService(CloudService service, Map credentials) {
        createUserProvidedServiceDelegate(service, credentials, "");
    }

    @Override
    public void createUserProvidedService(CloudService service, Map credentials, String
            syslogDrainUrl) {
        createUserProvidedServiceDelegate(service, credentials, syslogDrainUrl);
    }

    @Override
    public void debugApplication(String appName, CloudApplication.DebugMode mode) {
        throw new UnsupportedOperationException("Feature is not yet implemented.");
    }

    @Override
    public void deleteAllApplications() {
        List cloudApps = getApplications();
        for (CloudApplication cloudApp : cloudApps) {
            deleteApplication(cloudApp.getName());
        }
    }

    @Override
    public void deleteAllServices() {
        List cloudServices = getServices();
        for (CloudService cloudService : cloudServices) {
            doDeleteService(cloudService);
        }
    }

    @Override
    public void deleteApplication(String appName) {
        UUID appId = getAppId(appName);
        doDeleteApplication(appId);
    }

    @Override
    public void deleteDomain(String domainName) {
        assertSpaceProvided("delete domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        List routes = getRoutes(domainName);
        if (routes.size() > 0) {
            throw new IllegalStateException("Unable to remove domain that is in use --" +
                    " it has " + routes.size() + " routes.");
        }
        doDeleteDomain(domainGuid);
    }

    /**
     * Delete routes that do not have any application which is assigned to them.
     *
     * @return deleted routes or an empty list if no routes have been found
     */
    @Override
    public List deleteOrphanedRoutes() {
        List orphanRoutes = new ArrayList<>();
        for (CloudDomain cloudDomain : getDomainsForOrg()) {
            orphanRoutes.addAll(fetchOrphanRoutes(cloudDomain.getName()));
        }

        List deletedCloudRoutes = new ArrayList<>();
        for (CloudRoute orphanRoute : orphanRoutes) {
            deleteRoute(orphanRoute.getHost(), orphanRoute.getDomain().getName());
            deletedCloudRoutes.add(orphanRoute);
        }

        return deletedCloudRoutes;
    }

    public void deleteQuota(String quotaName) {
        CloudQuota quota = this.getQuotaByName(quotaName, true);
        String setPath = "/v2/quota_definitions/{quotaGuid}";
        Map setVars = new HashMap();
        setVars.put("quotaGuid", quota.getMeta().getGuid());
        getRestTemplate().delete(getUrl(setPath), setVars);
    }

    @Override
    public void deleteRoute(String host, String domainName) {
        assertSpaceProvided("delete route for domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        UUID routeGuid = getRouteGuid(host, domainGuid);
        if (routeGuid == null) {
            throw new IllegalArgumentException("Host '" + host + "' not found for domain '" + domainName + "'.");
        }
        doDeleteRoute(routeGuid);
    }

    @Override
    public void deleteSecurityGroup(String securityGroupName) {
        CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

        String path = "/v2/security_groups/{guid}";
        Map pathVariables = new HashMap();
        pathVariables.put("guid", group.getMeta().getGuid());

        getRestTemplate().delete(getUrl(path), pathVariables);
    }

    @Override
    public void deleteService(String serviceName) {
        CloudService cloudService = getService(serviceName);
        doDeleteService(cloudService);
    }

    @Override
    public void deleteServiceBroker(String name) {
        CloudServiceBroker existingBroker = getServiceBroker(name);
        Assert.notNull(existingBroker, "Cannot update broker if it does not first exist");

        getRestTemplate().delete(getUrl("/v2/service_brokers/{guid}"), existingBroker.getMeta().getGuid());
    }

    @Override
    public void deleteSpace(String spaceName) {
        assertSpaceProvided("delete a space");
        UUID orgGuid = sessionSpace.getOrganization().getMeta().getGuid();
        UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
        if (spaceGuid != null) {
            doDeleteSpace(spaceGuid);
        }
    }

    @Override
    public CloudApplication getApplication(String appName) {
        Map resource = findApplicationResource(appName, true);
        if (resource == null) {
            throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Not Found", "Application not found");
        }
        return mapCloudApplication(resource);
    }

    @Override
    public CloudApplication getApplication(UUID appGuid) {
        Map resource = findApplicationResource(appGuid, true);
        if (resource == null) {
            throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Not Found", "Application not found");
        }
        return mapCloudApplication(resource);
    }

    @Override
    public Map getApplicationEnvironment(UUID appGuid) {
        String url = getUrl("/v2/apps/{guid}/env");
        Map urlVars = new HashMap();
        urlVars.put("guid", appGuid);
        String resp = restTemplate.getForObject(url, String.class, urlVars);
        return JsonUtil.convertJsonToMap(resp);
    }

    @Override
    public Map getApplicationEnvironment(String appName) {
        UUID appId = getAppId(appName);
        return getApplicationEnvironment(appId);
    }

    @Override
    public List getApplicationEvents(String appName) {
        UUID appId = getAppId(appName);
        Map urlVars = new HashMap();
        urlVars.put("appId", appId);
        String urlPath = "/v2/events?q=actee:{appId}";
        return doGetEvents(urlPath, urlVars);
    }

    @Override
    public InstancesInfo getApplicationInstances(String appName) {
        CloudApplication app = getApplication(appName);
        return getApplicationInstances(app);
    }

    @Override
    public InstancesInfo getApplicationInstances(CloudApplication app) {
        if (app.getState().equals(CloudApplication.AppState.STARTED)) {
            return doGetApplicationInstances(app.getMeta().getGuid());
        }
        return null;
    }

    @Override
    public ApplicationStats getApplicationStats(String appName) {
        CloudApplication app = getApplication(appName);
        return doGetApplicationStats(app.getMeta().getGuid(), app.getState());
    }

    @Override
    public List getApplications() {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlPath = urlPath + "/apps?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, urlVars);
        List apps = new ArrayList();
        for (Map resource : resourceList) {
            processApplicationResource(resource, true);
            apps.add(mapCloudApplication(resource));
        }
        return apps;
    }

    @Override
    public URL getCloudControllerUrl() {
        return this.cloudControllerUrl;
    }

    @Override
    public Map getCrashLogs(String appName) {
        String urlPath = getFileUrlPath();
        CrashesInfo crashes = getCrashes(appName);
        if (crashes.getCrashes().isEmpty()) {
            return Collections.emptyMap();
        }
        TreeMap crashInstances = new TreeMap();
        for (CrashInfo crash : crashes.getCrashes()) {
            crashInstances.put(crash.getSince(), crash.getInstance());
        }
        String instance = crashInstances.get(crashInstances.lastKey());
        return doGetLogs(urlPath, appName, instance);
    }

    @SuppressWarnings("unchecked")
    @Override
    public CrashesInfo getCrashes(String appName) {
        UUID appId = getAppId(appName);
        if (appId == null) {
            throw new IllegalArgumentException("Application '" + appName + "' not found.");
        }
        Map urlVars = new HashMap();
        urlVars.put("guid", appId);
        String resp = getRestTemplate().getForObject(getUrl("/v2/apps/{guid}/crashes"), String.class, urlVars);
        Map respMap = JsonUtil.convertJsonToMap("{ \"crashes\" : " + resp + " }");
        List> attributes = (List>) respMap.get("crashes");
        return new CrashesInfo(attributes);
    }

    @Override
    public CloudDomain getDefaultDomain() {
        List sharedDomains = getSharedDomains();
        if (sharedDomains.isEmpty()) {
            return null;
        } else {
            return sharedDomains.get(0);
        }
    }

    @Override
    public List getDomains() {
        return doGetDomains((CloudOrganization) null);
    }

    @Override
    public List getDomainsForOrg() {
        assertSpaceProvided("access organization domains");
        return doGetDomains(sessionSpace.getOrganization());
    }

    @Override
    public List getEvents() {
        String urlPath = "/v2/events";
        return doGetEvents(urlPath, null);
    }

    @Override
    public String getFile(String appName, int instanceIndex, String filePath, int startPosition, int endPosition) {
        String urlPath = getFileUrlPath();
        Object appId = getFileAppId(appName);
        return doGetFile(urlPath, appId, instanceIndex, filePath, startPosition, endPosition);
    }

    @SuppressWarnings("unchecked")
    @Override
    public CloudInfo getInfo() {
        }
        // info comes from two end points: /info and /v2/info

        String infoV2Json = getRestTemplate().getForObject(getUrl("/v2/info"), String.class);
        Map infoV2Map = JsonUtil.convertJsonToMap(infoV2Json);

        Map userMap = getUserInfo((String) infoV2Map.get("user"));

        String infoJson = getRestTemplate().getForObject(getUrl("/info"), String.class);
        Map infoMap = JsonUtil.convertJsonToMap(infoJson);
        Map limitMap = (Map) infoMap.get("limits");
        Map usageMap = (Map) infoMap.get("usage");

        String name = CloudUtil.parse(String.class, infoV2Map.get("name"));
        String support = CloudUtil.parse(String.class, infoV2Map.get("support"));
        String authorizationEndpoint = CloudUtil.parse(String.class, infoV2Map.get("authorization_endpoint"));
        String build = CloudUtil.parse(String.class, infoV2Map.get("build"));
        String version = "" + CloudUtil.parse(Number.class, infoV2Map.get("version"));
        String description = CloudUtil.parse(String.class, infoV2Map.get("description"));

        CloudInfo.Limits limits = null;
        CloudInfo.Usage usage = null;
        boolean debug = false;
        if (oauthClient.getToken() != null) {
            limits = new CloudInfo.Limits(limitMap);
            usage = new CloudInfo.Usage(usageMap);
            debug = CloudUtil.parse(Boolean.class, infoMap.get("allow_debug"));
        }

        String loggregatorEndpoint = CloudUtil.parse(String.class, infoV2Map.get("logging_endpoint"));

        return new CloudInfo(name, support, authorizationEndpoint, build, version, (String) userMap.get("user_name"),
                description, limits, usage, debug, loggregatorEndpoint);
    }

    @Override
    public Map getLogs(String appName) {
        String urlPath = getFileUrlPath();
        String instance = String.valueOf(0);
        return doGetLogs(urlPath, appName, instance);
    }

    /**
     * Get organization by given name.
     *
     * @param orgName
     * @param required
     * @return CloudOrganization instance
     */
    public CloudOrganization getOrgByName(String orgName, boolean required) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/organizations?inline-relations-depth=1&q=name:{name}";
        urlVars.put("name", orgName);
        CloudOrganization org = null;
        List> resourceList = getAllResources(urlPath,
                urlVars);
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            org = resourceMapper.mapResource(resource, CloudOrganization.class);
        }

        if (org == null && required) {
            throw new IllegalArgumentException("Organization '" + orgName
                    + "' not found.");
        }

        return org;
    }

    @Override
    public Map getOrganizationUsers(String orgName) {
        String urlPath = "/v2/organizations/{guid}/users";
        CloudOrganization organization = getOrgByName(orgName, true);

        UUID orgGuid = organization.getMeta().getGuid();
        Map urlVars = new HashMap();
        urlVars.put("guid", orgGuid);

        List> resourceList = getAllResources(urlPath, urlVars);
        Map orgUsers = new HashMap();
        for (Map resource : resourceList) {
            CloudUser user = resourceMapper.mapResource(resource, CloudUser.class);
            orgUsers.put(user.getUsername(), user);
        }
        return orgUsers;
    }

    @Override
    public List getOrganizations() {
        return groups;
        String urlPath = "/v2/organizations?inline-relations-depth=0";
        List> resourceList = getAllResources(urlPath, null);
        List orgs = new ArrayList();
        for (Map resource : resourceList) {
            orgs.add(resourceMapper.mapResource(resource, CloudOrganization.class));
        }
        return orgs;
    }

    @Override
    public List getPrivateDomains() {
        return doGetDomains("/v2/private_domains");
    }

    /**
     * Get quota by given name.
     *
     * @param quotaName
     * @param required
     * @return CloudQuota instance
     */
    public CloudQuota getQuotaByName(String quotaName, boolean required) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/quota_definitions?q=name:{name}";
        urlVars.put("name", quotaName);
        CloudQuota quota = null;
        List> resourceList = getAllResources(urlPath, urlVars);
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            quota = resourceMapper.mapResource(resource, CloudQuota.class);
        }

        if (quota == null && required) {
            throw new IllegalArgumentException("Quota '" + quotaName
                    + "' not found.");
        }

        return quota;
    }

    public List getQuotas() {
        String urlPath = "/v2/quota_definitions";
        List> resourceList = getAllResources(urlPath, null);
        List quotas = new ArrayList();
        for (Map resource : resourceList) {
            quotas.add(resourceMapper.mapResource(resource, CloudQuota.class));
        }
        return quotas;
    }

    @Override
    public List getRecentLogs(String appName) {
        UUID appId = getAppId(appName);

        String endpoint = getInfo().getLoggregatorEndpoint();
        String uri = loggregatorClient.getRecentHttpEndpoint(endpoint);

        ApplicationLogs logs = getRestTemplate().getForObject(uri + "?app={guid}", ApplicationLogs.class, appId);

        Collections.sort(logs);

        return logs;
    }

    @Override
    public List getRoutes(String domainName) {
        assertSpaceProvided("get routes for domain");
        UUID domainGuid = getDomainGuid(domainName, true);
        return doGetRoutes(domainGuid);
    }

    @Override
    public List getRunningSecurityGroups() {
        String urlPath = "/v2/config/running_security_groups";
        List> resourceList = getAllResources(urlPath, null);
        List groups = new ArrayList();
        for (Map resource : resourceList) {
            groups.add(resourceMapper.mapResource(resource,
                    CloudSecurityGroup.class));
        }
        return groups;
    }

    @Override
    public CloudSecurityGroup getSecurityGroup(String securityGroupName) {
        return doGetSecurityGroup(securityGroupName, false);
    }

    @Override
    public List getSecurityGroups() {
        String urlPath = "/v2/security_groups";
        List> resourceList = getAllResources(urlPath, null);
        List groups = new ArrayList();
        for (Map resource : resourceList) {
            groups.add(resourceMapper.mapResource(resource,
                    CloudSecurityGroup.class));
    }

    @Override
    public CloudService getService(String serviceName) {
        Map resource = doGetServiceInstance(serviceName, 0);

        if (resource == null) {
            return null;
        }

        return resourceMapper.mapResource(resource, CloudService.class);
    }

    @Override
    public CloudServiceBroker getServiceBroker(String name) {
        String urlPath = "/v2/service_brokers?q={q}";
        Map urlVars = new HashMap<>();
        urlVars.put("q", "name:" + name);
        List> resourceList = getAllResources(urlPath, urlVars);
        CloudServiceBroker serviceBroker = null;
        if (resourceList.size() > 0) {
            final Map resource = resourceList.get(0);
            serviceBroker = resourceMapper.mapResource(resource, CloudServiceBroker.class);
        }
        return serviceBroker;
    }

    @Override
    public List getServiceBrokers() {
        String urlPath = "/v2/service_brokers?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, null);
        List serviceBrokers = new ArrayList();
        for (Map resource : resourceList) {
            CloudServiceBroker broker = resourceMapper.mapResource(resource, CloudServiceBroker.class);
            serviceBrokers.add(broker);
        }
        return serviceBrokers;
    }

    @Override
    public CloudServiceInstance getServiceInstance(String serviceName) {
        Map resource = doGetServiceInstance(serviceName, 1);

        if (resource == null) {
            return null;
        }

        return resourceMapper.mapResource(resource, CloudServiceInstance.class);
    }

    @Override
    public List getServiceOfferings() {
        String urlPath = "/v2/services?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, null);
        List serviceOfferings = new ArrayList();
        for (Map resource : resourceList) {
            CloudServiceOffering serviceOffering = resourceMapper.mapResource(resource, CloudServiceOffering.class);
            serviceOfferings.add(serviceOffering);
        }
        return serviceOfferings;
    }

    @Override
    public List getServices() {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlPath = urlPath + "/service_instances?inline-relations-depth=1&return_user_provided_service_instances=true";
        List> resourceList = getAllResources(urlPath, urlVars);
        List services = new ArrayList();
        for (Map resource : resourceList) {
            if (hasEmbeddedResource(resource, "service_plan")) {
                fillInEmbeddedResource(resource, "service_plan", "service");
            }
            services.add(resourceMapper.mapResource(resource, CloudService.class));
        }
        return services;
    }

    @Override
    public List getSharedDomains() {
        return doGetDomains("/v2/shared_domains");
    }

    @Override
    public CloudSpace getSpace(String spaceName) {
        String urlPath = "/v2/spaces?inline-relations-depth=1&q=name:{name}";
        HashMap spaceRequest = new HashMap();
        spaceRequest.put("name", spaceName);
        List> resourceList = getAllResources(urlPath, spaceRequest);
        CloudSpace space = null;
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            space = resourceMapper.mapResource(resource, CloudSpace.class);
        }
        return space;
    }

    @Override
    public List getSpaceAuditors(String orgName, String spaceName) {
        String urlPath = "/v2/spaces/{guid}/auditors";
        return getSpaceUserGuids(orgName, spaceName, urlPath);
    }

    @Override
    public List getSpaceDevelopers(String orgName, String spaceName) {
        String urlPath = "/v2/spaces/{guid}/developers";
        return getSpaceUserGuids(orgName, spaceName, urlPath);
    }

    @Override
    public List getSpaceManagers(String orgName, String spaceName) {
        String urlPath = "/v2/spaces/{guid}/managers";
        return getSpaceUserGuids(orgName, spaceName, urlPath);
    }

    @Override
    public List getSpaces() {
        String urlPath = "/v2/spaces?inline-relations-depth=1";
        List> resourceList = getAllResources(urlPath, null);
        List spaces = new ArrayList();
        for (Map resource : resourceList) {
            spaces.add(resourceMapper.mapResource(resource, CloudSpace.class));
        }
        return spaces;
    }

    @Override
    public List getSpacesBoundToSecurityGroup(String securityGroupName) {
        Map urlVars = new HashMap();
        // Need to go a few levels out to get the Organization that Spaces needs
        String urlPath = "/v2/security_groups?q=name:{name}&inline-relations-depth=2";
        urlVars.put("name", securityGroupName);
        List> resourceList = getAllResources(urlPath,
                urlVars);
        List spaces = new ArrayList();
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);

            Map securityGroupResource = CloudEntityResourceMapper.getEntity(resource);
            List> spaceResources = CloudEntityResourceMapper.getEmbeddedResourceList
                    (securityGroupResource, "spaces");
            for (Map spaceResource : spaceResources) {
                spaces.add(resourceMapper.mapResource(spaceResource, CloudSpace.class));
            }
        } else {
            throw new IllegalArgumentException("Security group named '" + securityGroupName
                    + "' not found.");
        }
        return spaces;
    }

    @Override
    public CloudStack getStack(String name) {
        String urlPath = "/v2/stacks?q={q}";
        Map urlVars = new HashMap();
        urlVars.put("q", "name:" + name);
        List> resources = getAllResources(urlPath, urlVars);
        if (resources.size() > 0) {
            Map resource = resources.get(0);
            return resourceMapper.mapResource(resource, CloudStack.class);
        }
        return null;
    }

    @Override
    public List getStacks() {
        String urlPath = "/v2/stacks";
        List> resources = getAllResources(urlPath, null);
        List stacks = new ArrayList();
        for (Map resource : resources) {
            stacks.add(resourceMapper.mapResource(resource, CloudStack.class));
        }
        return stacks;
    }

    /**
     * Returns null if no further content is available. Two errors that will lead to a null value are 404 Bad Request
     * errors, which are handled in the implementation, meaning that no further log file contents are available, or
     * ResourceAccessException, also handled in the implementation, indicating a possible timeout in the server serving
     * the content. Note that any other CloudFoundryException or RestClientException exception not related to the two
     * errors mentioned above may still be thrown (e.g. 500 level errors, Unauthorized or Forbidden exceptions, etc..)
     *
     * @return content if available, which may contain multiple lines, or null if no further content is available.
     */
    @Override
    public String getStagingLogs(StartingInfo info, int offset) {
        String stagingFile = info.getStagingFile();
        if (stagingFile != null) {
            CloudFoundryClientHttpRequestFactory cfRequestFactory = null;
            try {
                HashMap logsRequest = new HashMap();
                logsRequest.put("offset", offset);

                cfRequestFactory = getRestTemplate().getRequestFactory() instanceof
                        CloudFoundryClientHttpRequestFactory ? (CloudFoundryClientHttpRequestFactory) getRestTemplate()
                        .getRequestFactory() : null;
                if (cfRequestFactory != null) {
                    cfRequestFactory
                            .increaseReadTimeoutForStreamedTailedLogs(5 * 60 * 1000);
                }
                return getRestTemplate().getForObject(
                        stagingFile + "&tail&tail_offset={offset}",
                        String.class, logsRequest);
            } catch (CloudFoundryException e) {
                if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                    // Content is no longer available
                    return null;
                } else {
                    throw e;
                }
            } catch (ResourceAccessException e) {
                // Likely read timeout, the directory server won't serve
                // the content again
                logger.debug("Caught exception while fetching staging logs. Aborting. Caught:" + e,
                        e);
            } finally {
                if (cfRequestFactory != null) {
                    cfRequestFactory
                            .increaseReadTimeoutForStreamedTailedLogs(-1);
                }
            }
        }
        return null;
    }

    @Override
    public List getStagingSecurityGroups() {
        String urlPath = "/v2/config/staging_security_groups";
        List> resourceList = getAllResources(urlPath, null);
        List groups = new ArrayList();
        for (Map resource : resourceList) {
            groups.add(resourceMapper.mapResource(resource,
                    CloudSecurityGroup.class));
        }
        return groups;
    }

    @Override
    public OAuth2AccessToken login() {
        oauthClient.init(cloudCredentials);
        return oauthClient.getToken();
    }

    @Override
    public void logout() {
        oauthClient.clear();
    }

    @Override
    public void openFile(String appName, int instanceIndex, String filePath, ClientHttpResponseCallback callback) {
        String urlPath = getFileUrlPath();
        Object appId = getFileAppId(appName);
        doOpenFile(urlPath, appId, instanceIndex, filePath, callback);
    }

    @Override
    public void register(String email, String password) {
        throw new UnsupportedOperationException("Feature is not yet implemented.");
    }

    @Override
    public void registerRestLogListener(RestLogCallback callBack) {
        if (getRestTemplate() instanceof LoggingRestTemplate) {
            ((LoggingRestTemplate) getRestTemplate()).registerRestLogListener(callBack);
        }
    }

    @Override
    public void removeDomain(String domainName) {
    }

    @Override
    public void rename(String appName, String newName) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("name", newName);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public StartingInfo restartApplication(String appName) {
        stopApplication(appName);
        return startApplication(appName);
    }

    /**
     * Set quota to organization
     *
     * @param orgName
     * @param quotaName
     */
    public void setQuotaToOrg(String orgName, String quotaName) {
        CloudQuota quota = this.getQuotaByName(quotaName, true);
        CloudOrganization org = this.getOrgByName(orgName, true);

        doSetQuotaToOrg(org.getMeta().getGuid(), quota.getMeta().getGuid());
    }

    @Override
    public void setResponseErrorHandler(ResponseErrorHandler errorHandler) {
        this.restTemplate.setErrorHandler(errorHandler);
    }

    @Override
    public StartingInfo startApplication(String appName) {
        CloudApplication app = getApplication(appName);
        if (app.getState() != CloudApplication.AppState.STARTED) {
            HashMap appRequest = new HashMap();
            appRequest.put("state", CloudApplication.AppState.STARTED);

            HttpEntity requestEntity = new HttpEntity(
                    appRequest);
            ResponseEntity entity = getRestTemplate().exchange(
                    getUrl("/v2/apps/{guid}?stage_async=true"), HttpMethod.PUT, requestEntity,
                    String.class, app.getMeta().getGuid());

            HttpHeaders headers = entity.getHeaders();

            // Return a starting info, even with a null staging log value, as a non-null starting info
            // indicates that the response entity did have headers. The API contract is to return starting info
            // if there are headers in the response, null otherwise.
            if (headers != null && !headers.isEmpty()) {
                String stagingFile = headers.getFirst("x-app-staging-log");

                if (stagingFile != null) {
                    try {
                        stagingFile = URLDecoder.decode(stagingFile, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        logger.error("unexpected inability to UTF-8 decode", e);
                    }
                }
                // Return the starting info even if decoding failed or staging file is null
                return new StartingInfo(stagingFile);
            }
        }
        return null;
    }

    @Override
    public void stopApplication(String appName) {
        CloudApplication app = getApplication(appName);
        if (app.getState() != CloudApplication.AppState.STOPPED) {
            HashMap appRequest = new HashMap();
            appRequest.put("state", CloudApplication.AppState.STOPPED);
            getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, app.getMeta().getGuid());
        }
    }

    @Override
    public StreamingLogToken streamLogs(String appName, ApplicationLogListener listener) {
        return streamLoggregatorLogs(appName, listener, false);
    }

    @Override
    public void unRegisterRestLogListener(RestLogCallback callBack) {
        if (getRestTemplate() instanceof LoggingRestTemplate) {
            ((LoggingRestTemplate) getRestTemplate()).unRegisterRestLogListener(callBack);
        }
    }

    @Override
    public void unbindRunningSecurityGroup(String securityGroupName) {
        CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

        Map urlVars = new HashMap();
        String urlPath = "/v2/config/running_security_groups/{guid}";
        urlVars.put("guid", group.getMeta().getGuid());
        getRestTemplate().delete(getUrl(urlPath), urlVars);
    }

    @Override
    public void unbindSecurityGroup(String orgName, String spaceName, String securityGroupName) {
        UUID spaceGuid = getSpaceGuid(orgName, spaceName);
        CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

        String path = "/v2/security_groups/{group_guid}/spaces/{space_guid}";

        Map pathVariables = new HashMap();
        pathVariables.put("group_guid", group.getMeta().getGuid());
        pathVariables.put("space_guid", spaceGuid);

        getRestTemplate().delete(getUrl(path), pathVariables);
    }

    @Override
    public void unbindService(String appName, String serviceName) {
        CloudService cloudService = getService(serviceName);
        UUID appId = getAppId(appName);
        doUnbindService(appId, cloudService.getMeta().getGuid());
    }

    @Override
    public void unbindStagingSecurityGroup(String securityGroupName) {
        CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

        Map urlVars = new HashMap();
        String urlPath = "/v2/config/staging_security_groups/{guid}";
        urlVars.put("guid", group.getMeta().getGuid());
        getRestTemplate().delete(getUrl(urlPath), urlVars);
    }

    @Override
    public void unregister() {
        throw new UnsupportedOperationException("Feature is not yet implemented.");
    }

    @Override
    public void updateApplicationDiskQuota(String appName, int disk) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("disk_quota", disk);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationEnv(String appName, Map env) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("environment_json", env);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationEnv(String appName, List env) {
        Map envHash = new HashMap();
        for (String s : env) {
            if (!s.contains("=")) {
                throw new IllegalArgumentException("Environment setting without '=' is invalid: " + s);
            }
            String key = s.substring(0, s.indexOf('=')).trim();
            String value = s.substring(s.indexOf('=') + 1).trim();
            envHash.put(key, value);
        }
        updateApplicationEnv(appName, envHash);
    }

    @Override
    public void updateApplicationInstances(String appName, int instances) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("instances", instances);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationMemory(String appName, int memory) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        appRequest.put("memory", memory);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationServices(String appName, List services) {
        CloudApplication app = getApplication(appName);
        List addServices = new ArrayList();
        List deleteServices = new ArrayList();
        // services to add
        for (String serviceName : services) {
            if (!app.getServices().contains(serviceName)) {
                CloudService cloudService = getService(serviceName);
                if (cloudService != null) {
                    addServices.add(cloudService.getMeta().getGuid());
                } else {
                    throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Service with name " + serviceName +
                            " not found in current space " + sessionSpace.getName());
                }
            }
        }
        // services to delete
        for (String serviceName : app.getServices()) {
            if (!services.contains(serviceName)) {
                CloudService cloudService = getService(serviceName);
                if (cloudService != null) {
                    deleteServices.add(cloudService.getMeta().getGuid());
                }
            }
        }
        for (UUID serviceId : addServices) {
            doBindService(app.getMeta().getGuid(), serviceId);
        }
        for (UUID serviceId : deleteServices) {
            doUnbindService(app.getMeta().getGuid(), serviceId);
        }
    }

    @Override
    public void updateApplicationStaging(String appName, Staging staging) {
        UUID appId = getAppId(appName);
        HashMap appRequest = new HashMap();
        addStagingToRequest(staging, appRequest);
        getRestTemplate().put(getUrl("/v2/apps/{guid}"), appRequest, appId);
    }

    @Override
    public void updateApplicationUris(String appName, List uris) {
        CloudApplication app = getApplication(appName);
        List newUris = new ArrayList(uris);
        newUris.removeAll(app.getUris());
        List removeUris = app.getUris();
        removeUris.removeAll(uris);
        removeUris(removeUris, app.getMeta().getGuid());
        addUris(newUris, app.getMeta().getGuid());
    }

    @Override
    public void updatePassword(String newPassword) {
        updatePassword(cloudCredentials, newPassword);
    }

    @Override
    public void updatePassword(CloudCredentials credentials, String newPassword) {
        oauthClient.changePassword(credentials.getPassword(), newPassword);
        CloudCredentials newCloudCredentials = new CloudCredentials(credentials.getEmail(), newPassword);
        if (cloudCredentials.getProxyUser() != null) {
            cloudCredentials = newCloudCredentials.proxyForUser(cloudCredentials.getProxyUser());
        } else {
            cloudCredentials = newCloudCredentials;
        }
    }

    public void updateQuota(CloudQuota quota, String name) {
        CloudQuota oldQuota = this.getQuotaByName(name, true);

        String setPath = "/v2/quota_definitions/{quotaGuid}";

        Map setVars = new HashMap();
        setVars.put("quotaGuid", oldQuota.getMeta().getGuid());

        HashMap setRequest = new HashMap();
        setRequest.put("name", quota.getName());
        setRequest.put("memory_limit", quota.getMemoryLimit());
        setRequest.put("total_routes", quota.getTotalRoutes());
        setRequest.put("total_services", quota.getTotalServices());
        setRequest.put("non_basic_services_allowed", quota.isNonBasicServicesAllowed());

        getRestTemplate().put(getUrl(setPath), setRequest, setVars);
    }

    @Override
    public void updateSecurityGroup(CloudSecurityGroup securityGroup) {
        CloudSecurityGroup oldGroup = doGetSecurityGroup(securityGroup.getName(), true);
        doUpdateSecurityGroup(oldGroup, securityGroup.getName(), convertToList(securityGroup.getRules()));
    }

    @Override
    public void updateSecurityGroup(String name, InputStream jsonRulesFile) {
        CloudSecurityGroup oldGroup = doGetSecurityGroup(name, true);
        doUpdateSecurityGroup(oldGroup, name, JsonUtil.convertToJsonList(jsonRulesFile));
    }

    @Override
    public void updateServiceBroker(CloudServiceBroker serviceBroker) {
        Assert.notNull(serviceBroker, "Service Broker must not be null");
        Assert.notNull(serviceBroker.getName(), "Service Broker name must not be null");
        Assert.notNull(serviceBroker.getUrl(), "Service Broker URL must not be null");
        Assert.notNull(serviceBroker.getUsername(), "Service Broker username must not be null");
        Assert.notNull(serviceBroker.getPassword(), "Service Broker password must not be null");

        CloudServiceBroker existingBroker = getServiceBroker(serviceBroker.getName());
        Assert.notNull(existingBroker, "Cannot update broker if it does not first exist");

        HashMap serviceRequest = new HashMap<>();
        serviceRequest.put("name", serviceBroker.getName());
        serviceRequest.put("broker_url", serviceBroker.getUrl());
        serviceRequest.put("auth_username", serviceBroker.getUsername());
        serviceRequest.put("auth_password", serviceBroker.getPassword());
        getRestTemplate().put(getUrl("/v2/service_brokers/{guid}"), serviceRequest, existingBroker.getMeta().getGuid());
    }

    @Override
    public void updateServicePlanVisibilityForBroker(String name, boolean visibility) {
        CloudServiceBroker broker = getServiceBroker(name);

        String urlPath = "/v2/services?q={q}";
        Map urlVars = new HashMap<>();
        urlVars.put("q", "service_broker_guid:" + broker.getMeta().getGuid());
        List> serviceResourceList = getAllResources(urlPath, urlVars);

        for (Map serviceResource : serviceResourceList) {
            Map metadata = (Map) serviceResource.get("metadata");
            String serviceGuid = (String) metadata.get("guid");

            urlPath = "/v2/service_plans?q={q}";
            urlVars = new HashMap<>();
            urlVars.put("q", "service_guid:" + serviceGuid);
            List> planResourceList = getAllResources(urlPath, urlVars);
            for (Map planResource : planResourceList) {
                metadata = (Map) planResource.get("metadata");
                String planGuid = (String) metadata.get("guid");

                HashMap planUpdateRequest = new HashMap<>();
                planUpdateRequest.put("public", visibility);
                getRestTemplate().put(getUrl("/v2/service_plans/{guid}"), planUpdateRequest, planGuid);
            }
        }
    }

    @Override
    public void uploadApplication(String appName, File file, UploadStatusCallback callback) throws IOException {
        Assert.notNull(file, "File must not be null");
        if (file.isDirectory()) {
            ApplicationArchive archive = new DirectoryApplicationArchive(file);
            uploadApplication(appName, archive, callback);
        } else {
            try (ZipFile zipFile = new ZipFile(file)) {
                ApplicationArchive archive = new ZipApplicationArchive(zipFile);
                uploadApplication(appName, archive, callback);
            }
        }
    }

    @Override
    public void uploadApplication(String appName, String fileName, InputStream inputStream, UploadStatusCallback
            callback) throws IOException {
        Assert.notNull(fileName, "FileName must not be null");
        Assert.notNull(inputStream, "InputStream must not be null");

        File file = createTemporaryUploadFile(inputStream);

        try (ZipFile zipFile = new ZipFile(file)) {
            ApplicationArchive archive = new ZipApplicationArchive(zipFile);
            uploadApplication(appName, archive, callback);
        }

        file.delete();
    }

    @Override
    public void uploadApplication(String appName, ApplicationArchive archive, UploadStatusCallback callback)
            throws IOException {
        Assert.notNull(appName, "AppName must not be null");
        Assert.notNull(archive, "Archive must not be null");
        UUID appId = getAppId(appName);

        if (callback == null) {
            callback = UploadStatusCallback.NONE;
        }
        CloudResources knownRemoteResources = getKnownRemoteResources(archive);
        callback.onCheckResources();
        callback.onMatchedFileNames(knownRemoteResources.getFilenames());
        UploadApplicationPayload payload = new UploadApplicationPayload(archive, knownRemoteResources);
        callback.onProcessMatchedResources(payload.getTotalUncompressedSize());
        HttpEntity entity = generatePartialResourceRequest(payload, knownRemoteResources);
        ResponseEntity> responseEntity =
                getRestTemplate().exchange(getUrl("/v2/apps/{guid}/bits?async=true"),
                        HttpMethod.PUT, entity,
                        new ParameterizedTypeReference>() {
                        }, appId);
        processAsyncJob(responseEntity.getBody(), callback);
    }

    protected void configureCloudFoundryRequestFactory(RestTemplate restTemplate) {
        ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory();
        if (!(requestFactory instanceof CloudFoundryClientHttpRequestFactory)) {
            restTemplate.setRequestFactory(
                    new CloudFoundryClientHttpRequestFactory(requestFactory));
        }
    }

    protected String doGetFile(String urlPath, Object app, int instanceIndex, String filePath, int startPosition, int
            endPosition) {
        return doGetFile(urlPath, app, String.valueOf(instanceIndex), filePath, startPosition, endPosition);
    }

    protected String doGetFile(String urlPath, Object app, String instance, String filePath, int startPosition, int
            endPosition) {
        Assert.isTrue(startPosition >= -1, "Invalid start position value: " + startPosition);
        Assert.isTrue(endPosition >= -1, "Invalid end position value: " + endPosition);
        Assert.isTrue(startPosition < 0 || endPosition < 0 || endPosition >= startPosition,
                "The end position (" + endPosition + ") can't be less than the start position (" + startPosition + ")");

        int start, end;
        if (startPosition == -1 && endPosition == -1) {
            start = 0;
            end = -1;
        } else {
            start = startPosition;
            end = endPosition;
        }

        final String range =
                "bytes=" + (start == -1 ? "" : start) + "-" + (end == -1 ? "" : end);

        return doGetFileByRange(urlPath, app, instance, filePath, start, end, range);
    }

    protected Map doGetLogs(String urlPath, String appName, String instance) {
        Object appId = getFileAppId(appName);
        String logFiles = doGetFile(urlPath, appId, instance, LOGS_LOCATION, -1, -1);
        String[] lines = logFiles.split("\n");
        List fileNames = new ArrayList();
        for (String line : lines) {
            String[] parts = line.split("\\s");
            if (parts.length > 0 && parts[0] != null) {
                fileNames.add(parts[0]);
            }
        }
        Map logs = new HashMap(fileNames.size());
        for (String fileName : fileNames) {
            String logFile = LOGS_LOCATION + "/" + fileName;
            logs.put(logFile, doGetFile(urlPath, appId, instance, logFile, -1, -1));
        }
        return logs;
    }

    @SuppressWarnings("unchecked")
    protected void doOpenFile(String urlPath, Object app, int instanceIndex, String filePath,
                              ClientHttpResponseCallback callback) {
        getRestTemplate().execute(getUrl(urlPath), HttpMethod.GET, null, new ResponseExtractorWrapper(callback), app,
                String.valueOf(instanceIndex), filePath);
    }

    protected void extractUriInfo(Map domains, String uri, Map uriInfo) {
        URI newUri = URI.create(uri);
        String host = newUri.getScheme() != null ? newUri.getHost() : newUri.getPath();
        for (String domain : domains.keySet()) {
            if (host != null && host.endsWith(domain)) {
                String previousDomain = uriInfo.get("domainName");
                if (previousDomain == null || domain.length() > previousDomain.length()) {
                    //Favor most specific subdomains
                    uriInfo.put("domainName", domain);
                    if (domain.length() < host.length()) {
                        uriInfo.put("host", host.substring(0, host.indexOf(domain) - 1));
                    } else if (domain.length() == host.length()) {
                        uriInfo.put("host", "");
                    }
                }
            }
        }
        if (uriInfo.get("domainName") == null) {
            throw new IllegalArgumentException("Domain not found for URI " + uri);
        }
        if (uriInfo.get("host") == null) {
            throw new IllegalArgumentException("Invalid URI " + uri +
                    " -- host not specified for domain " + uriInfo.get("domainName"));
        }
    }

    protected Object getFileAppId(String appName) {
        return getAppId(appName);
    }

    protected String getFileUrlPath() {
        return "/v2/apps/{appId}/instances/{instance}/files/{filePath}";
    }

    protected RestTemplate getRestTemplate() {
        return this.restTemplate;
    }

    protected String getUrl(String path) {
        return cloudControllerUrl + (path.startsWith("/") ? path : "/" + path);
    }

    @SuppressWarnings("unchecked")
    private String addPageOfResources(String nextUrl, List> allResources) {
        String resp = getRestTemplate().getForObject(getUrl(nextUrl), String.class);
        Map respMap = JsonUtil.convertJsonToMap(resp);
        List> newResources = (List>) respMap.get("resources");
        if (newResources != null && newResources.size() > 0) {
            allResources.addAll(newResources);
        }
        return (String) respMap.get("next_url");
    }

    private void addStagingToRequest(Staging staging, HashMap appRequest) {
        if (staging.getBuildpackUrl() != null) {
            appRequest.put("buildpack", staging.getBuildpackUrl());
        }
        if (staging.getCommand() != null) {
            appRequest.put("command", staging.getCommand());
        }
        if (staging.getStack() != null) {
            appRequest.put("stack_guid", getStack(staging.getStack()).getMeta().getGuid());
        }
        if (staging.getHealthCheckTimeout() != null) {
            appRequest.put("health_check_timeout", staging.getHealthCheckTimeout());
        }
    }

    private void addUris(List uris, UUID appGuid) {
        Map domains = getDomainGuids();
        for (String uri : uris) {
            Map uriInfo = new HashMap(2);
            extractUriInfo(domains, uri, uriInfo);
            UUID domainGuid = domains.get(uriInfo.get("domainName"));
            bindRoute(uriInfo.get("host"), domainGuid, appGuid);
        }
    }

    private void assertSpaceProvided(String operation) {
        Assert.notNull(sessionSpace, "Unable to " + operation + " without specifying organization and space to use.");
    }

    private void associateRoleWithSpace(String orgName, String spaceName, String userGuid, String urlPath) {
        assertSpaceProvided("associate roles");

        CloudOrganization organization = (orgName == null ? sessionSpace.getOrganization() : getOrgByName(orgName,
                true));
        UUID orgGuid = organization.getMeta().getGuid();

        UUID spaceGuid = getSpaceGuid(spaceName, orgGuid);
        HashMap spaceRequest = new HashMap();
        spaceRequest.put("guid", spaceGuid);

        String userId = (userGuid == null ? getCurrentUserId() : userGuid);

        getRestTemplate().put(getUrl(urlPath), spaceRequest, spaceGuid, userId);
    }

    private void bindRoute(String host, UUID domainGuid, UUID appGuid) {
        UUID routeGuid = getRouteGuid(host, domainGuid);
        if (routeGuid == null) {
            routeGuid = doAddRoute(host, domainGuid);
        }
        String bindPath = "/v2/apps/{app}/routes/{route}";
        Map bindVars = new HashMap();
        bindVars.put("app", appGuid);
        bindVars.put("route", routeGuid);
        HashMap bindRequest = new HashMap();
        getRestTemplate().put(getUrl(bindPath), bindRequest, bindVars);
    }

    private List> convertToList(
            List rules) {
        List> ruleList = new ArrayList>();
        for (SecurityGroupRule rule : rules) {
            Map ruleMap = new HashMap();
            ruleMap.put("protocol", rule.getProtocol());
            ruleMap.put("destination", rule.getDestination());
            if (rule.getPorts() != null) {
                ruleMap.put("ports", rule.getPorts());
            }
            if (rule.getLog() != null) {
                ruleMap.put("log", rule.getLog());
            }
            if (rule.getType() != null) {
                ruleMap.put("type", rule.getType());
            }
            if (rule.getCode() != null) {
                ruleMap.put("code", rule.getCode());
            }
            ruleList.add(ruleMap);
        }
        return ruleList;
    }

    private File createTemporaryUploadFile(InputStream inputStream) throws IOException {
        File file = File.createTempFile("cfjava", null);
        FileOutputStream outputStream = new FileOutputStream(file);
        FileCopyUtils.copy(inputStream, outputStream);
        outputStream.close();
        return file;
    }

    private void createUserProvidedServiceDelegate(CloudService service, Map credentials, String
            syslogDrainUrl) {
        assertSpaceProvided("create service");
        Assert.notNull(credentials, "Service credentials must not be null");
        Assert.notNull(service, "Service must not be null");
        Assert.notNull(service.getName(), "Service name must not be null");
        Assert.isNull(service.getLabel(), "Service label is not valid for user-provided services");
        Assert.isNull(service.getProvider(), "Service provider is not valid for user-provided services");
        Assert.isNull(service.getVersion(), "Service version is not valid for user-provided services");
        Assert.isNull(service.getPlan(), "Service plan is not valid for user-provided services");

        HashMap serviceRequest = new HashMap<>();
        serviceRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        serviceRequest.put("name", service.getName());
        serviceRequest.put("credentials", credentials);
        if (syslogDrainUrl != null && !syslogDrainUrl.equals("")) {
            serviceRequest.put("syslog_drain_url", syslogDrainUrl);
        }

        getRestTemplate().postForObject(getUrl("/v2/user_provided_service_instances"), serviceRequest, String.class);
    }

    private UUID doAddRoute(String host, UUID domainGuid) {
        assertSpaceProvided("add route");

        HashMap routeRequest = new HashMap();
        routeRequest.put("host", host);
        routeRequest.put("domain_guid", domainGuid);
        routeRequest.put("space_guid", sessionSpace.getMeta().getGuid());
        String routeResp = getRestTemplate().postForObject(getUrl("/v2/routes"), routeRequest, String.class);
        Map routeEntity = JsonUtil.convertJsonToMap(routeResp);
        return CloudEntityResourceMapper.getMeta(routeEntity).getGuid();
    }

    private void doBindService(UUID appId, UUID serviceId) {
        HashMap serviceRequest = new HashMap();
        serviceRequest.put("service_instance_guid", serviceId);
        serviceRequest.put("app_guid", appId);
        getRestTemplate().postForObject(getUrl("/v2/service_bindings"), serviceRequest, String.class);
    }

    private UUID doCreateDomain(String domainName) {
        String urlPath = "/v2/private_domains";
        HashMap domainRequest = new HashMap();
        domainRequest.put("owning_organization_guid", sessionSpace.getOrganization().getMeta().getGuid());
        domainRequest.put("name", domainName);
        domainRequest.put("wildcard", true);
        String resp = getRestTemplate().postForObject(getUrl(urlPath), domainRequest, String.class);
        Map respMap = JsonUtil.convertJsonToMap(resp);
        return resourceMapper.getGuidOfResource(respMap);
    }

    private void doCreateSecurityGroup(String name, List> rules) {
        String path = "/v2/security_groups";
        HashMap request = new HashMap();
        request.put("name", name);
        request.put("rules", rules);
        getRestTemplate().postForObject(getUrl(path), request, String.class);
    }

    private UUID doCreateSpace(String spaceName, UUID orgGuid) {
        String urlPath = "/v2/spaces";
        HashMap spaceRequest = new HashMap();
        spaceRequest.put("organization_guid", orgGuid);
        spaceRequest.put("name", spaceName);
        String resp = getRestTemplate().postForObject(getUrl(urlPath), spaceRequest, String.class);
        Map respMap = JsonUtil.convertJsonToMap(resp);
        return resourceMapper.getGuidOfResource(respMap);
    }

    private void doDeleteApplication(UUID appId) {
        getRestTemplate().delete(getUrl("/v2/apps/{guid}?recursive=true"), appId);
    }

    private void doDeleteDomain(UUID domainGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/private_domains/{domain}";
        urlVars.put("domain", domainGuid);
        getRestTemplate().delete(getUrl(urlPath), urlVars);
    }

    private void doDeleteRoute(UUID routeGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/routes/{route}";
        urlVars.put("route", routeGuid);
        getRestTemplate().delete(getUrl(urlPath), urlVars);
    }

    private void doDeleteService(CloudService cloudService) {
        List appIds = getAppsBoundToService(cloudService);
        if (appIds.size() > 0) {
            for (UUID appId : appIds) {
                doUnbindService(appId, cloudService.getMeta().getGuid());
            }
        }
        ResponseEntity> response =
                getRestTemplate().exchange(getUrl("/v2/service_instances/{guid}?async=true"),
                        HttpMethod.DELETE, HttpEntity.EMPTY,
                        new ParameterizedTypeReference>() {
                        },
                        cloudService.getMeta().getGuid());
        waitForAsyncJobCompletion(response.getBody());
    }

    private void doDeleteSpace(UUID spaceGuid) {
        getRestTemplate().delete(getUrl("/v2/spaces/{guid}?async=false"), spaceGuid);
    }

    @SuppressWarnings("unchecked")
    private InstancesInfo doGetApplicationInstances(UUID appId) {
        try {
            List> instanceList = new ArrayList>();
            Map respMap = getInstanceInfoForApp(appId, "instances");
            List keys = new ArrayList(respMap.keySet());
            Collections.sort(keys);
            for (String instanceId : keys) {
                Integer index;
                try {
                    index = Integer.valueOf(instanceId);
                } catch (NumberFormatException e) {
                    index = -1;
                }
                Map instanceMap = (Map) respMap.get(instanceId);
                instanceMap.put("index", index);
                instanceList.add(instanceMap);
            }
            return new InstancesInfo(instanceList);
        } catch (CloudFoundryException e) {
            if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
                return null;
            } else {
                throw e;
            }

        }
    }

    @SuppressWarnings("unchecked")
    private ApplicationStats doGetApplicationStats(UUID appId, CloudApplication.AppState appState) {
        List instanceList = new ArrayList();
        if (appState.equals(CloudApplication.AppState.STARTED)) {
            Map respMap = getInstanceInfoForApp(appId, "stats");
            for (String instanceId : respMap.keySet()) {
                InstanceStats instanceStats =
                        new InstanceStats(instanceId, (Map) respMap.get(instanceId));
                instanceList.add(instanceStats);
            }
        }
        return new ApplicationStats(instanceList);
    }

    private List doGetDomains(CloudOrganization org) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (org != null) {
            urlVars.put("org", org.getMeta().getGuid());
            urlPath = urlPath + "/organizations/{org}";
        }
        urlPath = urlPath + "/domains";
        return doGetDomains(urlPath, urlVars);
    }

    private List doGetDomains(String urlPath) {
        return doGetDomains(urlPath, null);
    }

    private List doGetDomains(String urlPath, Map urlVars) {
        List> domainResources = getAllResources(urlPath, urlVars);
        List domains = new ArrayList();
        for (Map resource : domainResources) {
            domains.add(resourceMapper.mapResource(resource, CloudDomain.class));
        }
        return domains;
    }

    private List doGetEvents(String urlPath, Map urlVars) {
        List> resourceList = getAllResources(urlPath, urlVars);
        List events = new ArrayList();
        for (Map resource : resourceList) {
            if (resource != null) {
                events.add(resourceMapper.mapResource(resource, CloudEvent.class));
            }
        }
        return events;
    }

    private String doGetFileByRange(String urlPath, Object app, String instance, String filePath, int start, int end,
                                    String range) {

        boolean supportsRanges;
        try {
            supportsRanges = getRestTemplate().execute(getUrl(urlPath),
                    HttpMethod.HEAD,
                    new RequestCallback() {
                        public void doWithRequest(ClientHttpRequest request) throws IOException {
                            request.getHeaders().set("Range", "bytes=0-");
                        }
                    },
                    new ResponseExtractor() {
                        public Boolean extractData(ClientHttpResponse response) throws IOException {
                            return response.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT);
                        }
                    },
                    app, instance, filePath);
        } catch (CloudFoundryException e) {
            if (e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)) {
                // must be a 0 byte file
                return "";
            } else {
                throw e;
            }
        }
        HttpHeaders headers = new HttpHeaders();
        if (supportsRanges) {
            headers.set("Range", range);
        }
        HttpEntity requestEntity = new HttpEntity(headers);
        ResponseEntity responseEntity = getRestTemplate().exchange(getUrl(urlPath),
                HttpMethod.GET, requestEntity, String.class, app, instance, filePath);
        String response = responseEntity.getBody();
        boolean partialFile = false;
        if (responseEntity.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT)) {
            partialFile = true;
        }
        if (!partialFile && response != null) {
            if (start == -1) {
                return response.substring(response.length() - end);
            } else {
                if (start >= response.length()) {
                    if (response.length() == 0) {
                        return "";
                    }
                    throw new CloudFoundryException(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
                            "The starting position " + start + " is past the end of the file content.");
                }
                if (end != -1) {
                    if (end >= response.length()) {
                        end = response.length() - 1;
                    }
                    return response.substring(start, end + 1);
                } else {
                    return response.substring(start);
                }
            }
        }
        return response;
    }

    private List doGetRoutes(UUID domainGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
//		TODO: NOT implemented ATM:
//		if (sessionSpace != null) {
//			urlVars.put("space", sessionSpace.getMeta().getGuid());
File
CloudControllerClientImpl.java
Developer's decision
Manual
Kind of conflict
Annotation
Attribute
Class declaration
Comment
For statement
Method declaration
Method invocation
Method signature
Throw statement
Variable
Chunk
Conflicting content
        List routes = new ArrayList();
        for (Map route : allRoutes) {
//			TODO: move space_guid to path once implemented (see above):
<<<<<<< HEAD
			UUID space = CloudEntityResourceMapper.getEntityAttribute(route, "space_guid", UUID.class);
			UUID domain = CloudEntityResourceMapper.getEntityAttribute(route, "domain_guid", UUID.class);
			if (sessionSpace.getMeta().getGuid().equals(space) && domainGuid.equals(domain)) {
				//routes.add(CloudEntityResourceMapper.getEntityAttribute(route, "host", String.class));
				routes.add(resourceMapper.mapResource(route, CloudRoute.class));
			}
		}
		return routes;
	}

	private void doDeleteService(CloudService cloudService) {
		List appIds = getAppsBoundToService(cloudService);
		if (appIds.size() > 0) {
			for (UUID appId : appIds) {
				doUnbindService(appId, cloudService.getMeta().getGuid());
			}
		}
		ResponseEntity> response =
			getRestTemplate().exchange(getUrl("/v2/service_instances/{guid}?async=true"),
				HttpMethod.DELETE, HttpEntity.EMPTY,
				new ParameterizedTypeReference>() {},
				cloudService.getMeta().getGuid());
		waitForAsyncJobCompletion(response.getBody());
	}

	private void waitForAsyncJobCompletion(Map jobResponse) {


		if (resource != null) {
			}
		long timeout = System.currentTimeMillis() + JOB_TIMEOUT;
		while (System.currentTimeMillis() < timeout) {
			CloudJob job = resourceMapper.mapResource(jobResponse, CloudJob.class);

			if (job.getStatus() == CloudJob.Status.FINISHED) {
				return;
			}

			if (job.getStatus() == CloudJob.Status.FAILED) {
				throw new CloudOperationException(job.getErrorDetails().getDescription());
			}

			try {
				Thread.sleep(JOB_POLLING_PERIOD);
			} catch (InterruptedException e) {
				return;
			}

			jobResponse = getRestTemplate().exchange(getUrl(job.getMeta().getUrl()),
				HttpMethod.GET, HttpEntity.EMPTY,
				new ParameterizedTypeReference>() {}).getBody();
		}
	}

	@SuppressWarnings("unchecked")
	private List getAppsBoundToService(CloudService cloudService) {
		List appGuids = new ArrayList();
		String urlPath = "/v2";
		Map urlVars = new HashMap();
		if (sessionSpace != null) {
			urlVars.put("space", sessionSpace.getMeta().getGuid());
			urlPath = urlPath + "/spaces/{space}";
		}
		urlVars.put("q", "name:" + cloudService.getName());
		urlPath = urlPath + "/service_instances?q={q}";
		List> resourceList = getAllResources(urlPath, urlVars);
		for (Map resource : resourceList) {
			fillInEmbeddedResource(resource, "service_bindings");
			List> bindings =
					CloudEntityResourceMapper.getEntityAttribute(resource, "service_bindings", List.class);
			for (Map binding : bindings) {
				String appId = CloudEntityResourceMapper.getEntityAttribute(binding, "app_guid", String.class);
				if (appId != null) {
					appGuids.add(UUID.fromString(appId));
				}
			}
		}
		return appGuids;
	}

	private void doDeleteApplication(UUID appId) {
		getRestTemplate().delete(getUrl("/v2/apps/{guid}?recursive=true"), appId);
	}

	private List getServiceOfferings(String label) {
		Assert.notNull(label, "Service label must not be null");
		List> resourceList = getAllResources("/v2/services?inline-relations-depth=1", null);
		List results = new ArrayList();
		for (Map resource : resourceList) {
			CloudServiceOffering cloudServiceOffering =
					resourceMapper.mapResource(resource, CloudServiceOffering.class);
			if (cloudServiceOffering.getLabel() != null && label.equals(cloudServiceOffering.getLabel())) {
				results.add(cloudServiceOffering);
		}
		return results;
	}

	@SuppressWarnings("unchecked")
	private UUID getServiceBindingId(UUID appId, UUID serviceId ) {
		Map urlVars = new HashMap();
		urlVars.put("guid", appId);
		List> resourceList = getAllResources("/v2/apps/{guid}/service_bindings", urlVars);
		UUID serviceBindingId = null;
		if (resourceList != null && resourceList.size() > 0) {
			for (Map resource : resourceList) {
				Map bindingMeta = (Map) resource.get("metadata");
				Map bindingEntity = (Map) resource.get("entity");
				String serviceInstanceGuid = (String) bindingEntity.get("service_instance_guid");
				if (serviceInstanceGuid != null && serviceInstanceGuid.equals(serviceId.toString())) {
					String bindingGuid = (String) bindingMeta.get("guid");
					serviceBindingId = UUID.fromString(bindingGuid);
					break;
				}
			}
		}
		return serviceBindingId;
	}

	@SuppressWarnings("unchecked")
	private UUID getAppId(String appName) {
		Map resource = findApplicationResource(appName, false);
		UUID guid = null;
			Map appMeta = (Map) resource.get("metadata");
			guid = UUID.fromString(String.valueOf(appMeta.get("guid")));
		}
		return guid;
	}

	private StreamingLogToken streamLoggregatorLogs(String appName, ApplicationLogListener listener, boolean recent) {
		ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
			public void beforeRequest(Map> headers) {
				String authorizationHeader = oauthClient.getAuthorizationHeader();
				if (authorizationHeader != null) {
					headers.put(AUTHORIZATION_HEADER_KEY, Arrays.asList(authorizationHeader));
				}
			}
		};

		String endpoint = getInfo().getLoggregatorEndpoint();
		String mode = recent ? "dump" : "tail";
		UUID appId = getAppId(appName);
		return loggregatorClient.connectToLoggregator(endpoint, mode, appId, listener, configurator);
	}

	private class AccumulatingApplicationLogListener implements ApplicationLogListener {
		private List logs = new ArrayList();

		@Override
		public void onMessage(ApplicationLog log) {
			logs.add(log);
		}

		@Override
		public void onError(Throwable exception) {
			synchronized (this) {
				this.notify();
			}
		}

		@Override
		public void onComplete() {
			synchronized (this) {
				this.notify();
			}
		}

		public List getLogs() {
			Collections.sort(logs);
			return logs;
		}
	}

	private Map findApplicationResource(UUID appGuid, boolean fetchServiceInfo) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/apps/{app}?inline-relations-depth=1";
		urlVars.put("app", appGuid);
		String resp = getRestTemplate().getForObject(getUrl(urlPath), String.class, urlVars);

		return processApplicationResource(JsonUtil.convertJsonToMap(resp), fetchServiceInfo);
	}


	private Map findApplicationResource(String appName, boolean fetchServiceInfo) {
		Map urlVars = new HashMap();
		String urlPath = "/v2";
		if (sessionSpace != null) {
			urlVars.put("space", sessionSpace.getMeta().getGuid());
			urlPath = urlPath + "/spaces/{space}";
		}
		urlVars.put("q", "name:" + appName);
		urlPath = urlPath + "/apps?inline-relations-depth=1&q={q}";

		List> allResources = getAllResources(urlPath, urlVars);
		if(!allResources.isEmpty()) {
			return processApplicationResource(allResources.get(0), fetchServiceInfo);
		}
		return null;
	}

	private Map processApplicationResource(Map resource, boolean fetchServiceInfo) {
		if (fetchServiceInfo) {
			fillInEmbeddedResource(resource, "service_bindings", "service_instance");
		}
		fillInEmbeddedResource(resource, "stack");
		return resource;
	}

	private List findApplicationUris(UUID appGuid) {
		String urlPath = "/v2/apps/{app}/routes?inline-relations-depth=1";
		Map urlVars = new HashMap();
		urlVars.put("app", appGuid);
		List> resourceList = getAllResources(urlPath, urlVars);
		List uris =  new ArrayList();
		for (Map resource : resourceList) {
			Map domainResource = CloudEntityResourceMapper.getEmbeddedResource(resource, "domain");
			String host = CloudEntityResourceMapper.getEntityAttribute(resource, "host", String.class);
			String domain = CloudEntityResourceMapper.getEntityAttribute(domainResource, "name", String.class);
			if (host != null && host.length() > 0)
				uris.add(host + "." + domain);
			else
				uris.add(domain);
		}
		return uris;
	}

	@SuppressWarnings("restriction")
	private Map getUserInfo(String user) {
//		String userJson = getRestTemplate().getForObject(getUrl("/v2/users/{guid}"), String.class, user);
//		Map userInfo = (Map) JsonUtil.convertJsonToMap(userJson);
//		return userInfo();
		//TODO: remove this temporary hack once the /v2/users/ uri can be accessed by mere mortals
		String userJson = "{}";
		OAuth2AccessToken accessToken = oauthClient.getToken();
		if (accessToken != null) {
			String tokenString = accessToken.getValue();
			int x = tokenString.indexOf('.');
			int y = tokenString.indexOf('.', x + 1);
			String encodedString = tokenString.substring(x + 1, y);
			try {
				byte[] decodedBytes = new sun.misc.BASE64Decoder().decodeBuffer(encodedString);
				userJson = new String(decodedBytes, 0, decodedBytes.length, "UTF-8");
			} catch (IOException e) {}
		}
		return(JsonUtil.convertJsonToMap(userJson));
	}

	@SuppressWarnings("unchecked")
	private void fillInEmbeddedResource(Map resource, String... resourcePath) {
		if (resourcePath.length == 0) {
			return;
		}
		Map entity = (Map) resource.get("entity");

		String headKey = resourcePath[0];
		String[] tailPath = Arrays.copyOfRange(resourcePath, 1, resourcePath.length);

		if (!entity.containsKey(headKey)) {
			String pathUrl = entity.get(headKey + "_url").toString();
			Object response = getRestTemplate().getForObject(getUrl(pathUrl), Object.class);
			if (response instanceof Map) {
				Map responseMap = (Map) response;
				if (responseMap.containsKey("resources")) {
					response = responseMap.get("resources");
				}
			}
			entity.put(headKey, response);
		}
		Object embeddedResource = entity.get(headKey);

		if (embeddedResource instanceof Map) {
			Map embeddedResourceMap = (Map) embeddedResource;
			//entity = (Map) embeddedResourceMap.get("entity");
			fillInEmbeddedResource(embeddedResourceMap, tailPath);
		} else if (embeddedResource instanceof List) {
			List embeddedResourcesList = (List) embeddedResource;
			for (Object r: embeddedResourcesList) {
				fillInEmbeddedResource((Map)r, tailPath);
			}
		} else {
			// no way to proceed
			return;
		}
	}

	@SuppressWarnings("unchecked")
	private boolean hasEmbeddedResource(Map resource, String resourceKey) {
		Map entity = (Map) resource.get("entity");
		return entity.containsKey(resourceKey) || entity.containsKey(resourceKey + "_url");
	}

	private static class ResponseExtractorWrapper implements ResponseExtractor {

		private ClientHttpResponseCallback callback;

		public ResponseExtractorWrapper(ClientHttpResponseCallback callback) {
			this.callback = callback;
		}

		@Override
		public Object extractData(ClientHttpResponse clientHttpResponse) throws IOException {
			callback.onClientHttpResponse(clientHttpResponse);
			return null;
		}

	}

	// Security Group operations

	@Override
	public List getSecurityGroups() {
		String urlPath = "/v2/security_groups";
		List> resourceList = getAllResources(urlPath, null);
		List groups = new ArrayList();
		for (Map resource : resourceList) {
			groups.add(resourceMapper.mapResource(resource,
					CloudSecurityGroup.class));
		}
		return groups;
	}

	@Override
	public CloudSecurityGroup getSecurityGroup(String securityGroupName) {
		return doGetSecurityGroup(securityGroupName, false);
	}

	private CloudSecurityGroup doGetSecurityGroup(String securityGroupName, boolean required) {
		Map urlVars = new HashMap();
		String urlPath = "/v2/security_groups?q=name:{name}";
		urlVars.put("name", securityGroupName);
		CloudSecurityGroup securityGroup = null;
		List> resourceList = getAllResources(urlPath,
				urlVars);
		if (resourceList.size() > 0) {
			Map resource = resourceList.get(0);
			securityGroup = resourceMapper.mapResource(resource,
					CloudSecurityGroup.class);
		}else if(required && resourceList.size() == 0){
			throw new IllegalArgumentException("Security group named '" + securityGroupName
					+ "' not found.");
		}

		return securityGroup;
	}

	@Override
	public void createSecurityGroup(CloudSecurityGroup securityGroup) {
		doCreateSecurityGroup(securityGroup.getName(),
				convertToList(securityGroup.getRules()));
	}

	private List> convertToList(
			List rules) {
		List> ruleList = new ArrayList>();
		for (SecurityGroupRule rule : rules) {
			Map ruleMap = new HashMap();
			ruleMap.put("protocol", rule.getProtocol());
			ruleMap.put("destination", rule.getDestination());
			if (rule.getPorts() != null) {
				ruleMap.put("ports", rule.getPorts());
			}
			if(rule.getLog() != null){
				ruleMap.put("log", rule.getLog());
			}
			if(rule.getType() != null){
				ruleMap.put("type", rule.getType());
			}
			if(rule.getCode() != null){
				ruleMap.put("code", rule.getCode());
			}
			ruleList.add(ruleMap);
		}
		return ruleList;
	}

	@Override
	public void createSecurityGroup(String name, InputStream jsonRulesFile) {
		doCreateSecurityGroup(name, JsonUtil.convertToJsonList(jsonRulesFile));
	}

	private void doCreateSecurityGroup(String name, List> rules) {
		String path = "/v2/security_groups";
		HashMap request = new HashMap();
		request.put("name", name);
		request.put("rules", rules);
		getRestTemplate().postForObject(getUrl(path), request, String.class);
	}

	@Override
	public void updateSecurityGroup(CloudSecurityGroup securityGroup) {
		CloudSecurityGroup oldGroup = doGetSecurityGroup(securityGroup.getName(), true);
		doUpdateSecurityGroup(oldGroup, securityGroup.getName(), convertToList(securityGroup.getRules()));
	}

	@Override
	public void updateSecurityGroup(String name, InputStream jsonRulesFile) {
		CloudSecurityGroup oldGroup = doGetSecurityGroup(name, true);
		doUpdateSecurityGroup(oldGroup, name, JsonUtil.convertToJsonList(jsonRulesFile));
	}

	private void doUpdateSecurityGroup(CloudSecurityGroup currentGroup, String name, List> rules){
		String path = "/v2/security_groups/{guid}";

		Map pathVariables = new HashMap();
		pathVariables.put("guid", currentGroup.getMeta().getGuid());

		HashMap request = new HashMap();
		request.put("name", name);
		request.put("rules", rules);
		// Updates of bindings to spaces and default staging/running groups must be done
		// through explicit calls to those methods and not through this generic update

		getRestTemplate().put(getUrl(path), request, pathVariables);
	}

	@Override
	public void deleteSecurityGroup(String securityGroupName) {
		CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

		String path = "/v2/security_groups/{guid}";
		Map pathVariables = new HashMap();
		pathVariables.put("guid", group.getMeta().getGuid());

		getRestTemplate().delete(getUrl(path), pathVariables);
	}

	@Override
	public void bindStagingSecurityGroup(String securityGroupName) {
		CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

		String path = "/v2/config/staging_security_groups/{guid}";

		Map pathVariables = new HashMap();
		pathVariables.put("guid", group.getMeta().getGuid());

		getRestTemplate().put(getUrl(path), null, pathVariables);
	}

	@Override
	public List getStagingSecurityGroups() {
		String urlPath = "/v2/config/staging_security_groups";
		List> resourceList = getAllResources(urlPath, null);
		List groups = new ArrayList();
		for (Map resource : resourceList) {
			groups.add(resourceMapper.mapResource(resource,
					CloudSecurityGroup.class));
		}
		return groups;
	}

	@Override
	public void unbindStagingSecurityGroup(String securityGroupName) {
		CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

		Map urlVars = new HashMap();
		String urlPath = "/v2/config/staging_security_groups/{guid}";
		urlVars.put("guid", group.getMeta().getGuid());
		getRestTemplate().delete(getUrl(urlPath), urlVars);
	}

	@Override
	public List getRunningSecurityGroups() {
		String urlPath = "/v2/config/running_security_groups";
		List> resourceList = getAllResources(urlPath, null);
		List groups = new ArrayList();
		for (Map resource : resourceList) {
			groups.add(resourceMapper.mapResource(resource,
					CloudSecurityGroup.class));
		}
		return groups;
	}

	@Override
	public void bindRunningSecurityGroup(String securityGroupName) {
		CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

		String path = "/v2/config/running_security_groups/{guid}";

		Map pathVariables = new HashMap();
		pathVariables.put("guid", group.getMeta().getGuid());

		getRestTemplate().put(getUrl(path), null, pathVariables);
	}

	@Override
	public void unbindRunningSecurityGroup(String securityGroupName) {
		CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

		Map urlVars = new HashMap();
		String urlPath = "/v2/config/running_security_groups/{guid}";
		urlVars.put("guid", group.getMeta().getGuid());
		getRestTemplate().delete(getUrl(urlPath), urlVars);
	}

	@Override
	public List getSpacesBoundToSecurityGroup(String securityGroupName) {
		Map urlVars = new HashMap();
		// Need to go a few levels out to get the Organization that Spaces needs
		String urlPath = "/v2/security_groups?q=name:{name}&inline-relations-depth=2";
		urlVars.put("name", securityGroupName);
		List> resourceList = getAllResources(urlPath,
				urlVars);
		List spaces = new ArrayList();
		if (resourceList.size() > 0) {
			Map resource = resourceList.get(0);

			Map securityGroupResource = CloudEntityResourceMapper.getEntity(resource);
			List> spaceResources = CloudEntityResourceMapper.getEmbeddedResourceList(securityGroupResource, "spaces");
			for(Map spaceResource: spaceResources){
				spaces.add(resourceMapper.mapResource(spaceResource, CloudSpace.class));
			}
		}else {
			throw new IllegalArgumentException("Security group named '" + securityGroupName
					+ "' not found.");
		}
		return spaces;
	}

	@Override
	public void bindSecurityGroup(String orgName, String spaceName, String securityGroupName) {
		UUID spaceGuid = getSpaceGuid(orgName, spaceName);
		CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

		String path = "/v2/security_groups/{group_guid}/spaces/{space_guid}";

		Map pathVariables = new HashMap();
		pathVariables.put("group_guid", group.getMeta().getGuid());
		pathVariables.put("space_guid", spaceGuid);

		getRestTemplate().put(getUrl(path), null, pathVariables);
	}

	@Override
	public void unbindSecurityGroup(String orgName, String spaceName, String securityGroupName) {
		UUID spaceGuid = getSpaceGuid(orgName, spaceName);
		CloudSecurityGroup group = doGetSecurityGroup(securityGroupName, true);

		String path = "/v2/security_groups/{group_guid}/spaces/{space_guid}";

		Map pathVariables = new HashMap();
		pathVariables.put("group_guid", group.getMeta().getGuid());
		pathVariables.put("space_guid", spaceGuid);

		getRestTemplate().delete(getUrl(path), pathVariables);
	}



=======
            UUID space = CloudEntityResourceMapper.getEntityAttribute(route, "space_guid", UUID.class);
            UUID domain = CloudEntityResourceMapper.getEntityAttribute(route, "domain_guid", UUID.class);
            if (sessionSpace.getMeta().getGuid().equals(space) && domainGuid.equals(domain)) {
                //routes.add(CloudEntityResourceMapper.getEntityAttribute(route, "host", String.class));
                routes.add(resourceMapper.mapResource(route, CloudRoute.class));
            }
        }
        return routes;
    }

    private void doSetQuotaToOrg(UUID orgGuid, UUID quotaGuid) {
        String setPath = "/v2/organizations/{org}";
        Map setVars = new HashMap();
        setVars.put("org", orgGuid);
        HashMap setRequest = new HashMap();
        setRequest.put("quota_definition_guid", quotaGuid);

        getRestTemplate().put(getUrl(setPath), setRequest, setVars);
    }

    private void doUnbindService(UUID appId, UUID serviceId) {
        UUID serviceBindingId = getServiceBindingId(appId, serviceId);
        getRestTemplate().delete(getUrl("/v2/service_bindings/{guid}"), serviceBindingId);
    }

    private List fetchOrphanRoutes(String domainName) {
        List orphanRoutes = new ArrayList<>();
        for (CloudRoute cloudRoute : getRoutes(domainName)) {
            if (isOrphanRoute(cloudRoute)) {
                orphanRoutes.add(cloudRoute);
            }
        }

        return orphanRoutes;
    }

    @SuppressWarnings("unchecked")
    private void fillInEmbeddedResource(Map resource, String... resourcePath) {
        if (resourcePath.length == 0) {
            return;
        }
        Map entity = (Map) resource.get("entity");

        String headKey = resourcePath[0];
        String[] tailPath = Arrays.copyOfRange(resourcePath, 1, resourcePath.length);

        if (!entity.containsKey(headKey)) {
            String pathUrl = entity.get(headKey + "_url").toString();
            Object response = getRestTemplate().getForObject(getUrl(pathUrl), Object.class);
            if (response instanceof Map) {
                Map responseMap = (Map) response;
                if (responseMap.containsKey("resources")) {
                    response = responseMap.get("resources");
                }
            }
            entity.put(headKey, response);
        }
        Object embeddedResource = entity.get(headKey);

        if (embeddedResource instanceof Map) {
            Map embeddedResourceMap = (Map) embeddedResource;
            //entity = (Map) embeddedResourceMap.get("entity");
            fillInEmbeddedResource(embeddedResourceMap, tailPath);
        } else if (embeddedResource instanceof List) {
            List embeddedResourcesList = (List) embeddedResource;
            for (Object r : embeddedResourcesList) {
                fillInEmbeddedResource((Map) r, tailPath);
            }
        } else {
            // no way to proceed
            return;
        }
    }

    private Map findApplicationResource(UUID appGuid, boolean fetchServiceInfo) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/apps/{app}?inline-relations-depth=1";
        urlVars.put("app", appGuid);
        String resp = getRestTemplate().getForObject(getUrl(urlPath), String.class, urlVars);

        return processApplicationResource(JsonUtil.convertJsonToMap(resp), fetchServiceInfo);
    }

    private Map findApplicationResource(String appName, boolean fetchServiceInfo) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlVars.put("q", "name:" + appName);
        urlPath = urlPath + "/apps?inline-relations-depth=1&q={q}";

        List> allResources = getAllResources(urlPath, urlVars);
        if (!allResources.isEmpty()) {
            return processApplicationResource(allResources.get(0), fetchServiceInfo);
        }
        return null;
    }

    private List findApplicationUris(UUID appGuid) {
        String urlPath = "/v2/apps/{app}/routes?inline-relations-depth=1";
        Map urlVars = new HashMap();
        urlVars.put("app", appGuid);
        List> resourceList = getAllResources(urlPath, urlVars);
        List uris = new ArrayList();
        for (Map resource : resourceList) {
            Map domainResource = CloudEntityResourceMapper.getEmbeddedResource(resource, "domain");
            String host = CloudEntityResourceMapper.getEntityAttribute(resource, "host", String.class);
            String domain = CloudEntityResourceMapper.getEntityAttribute(domainResource, "name", String.class);
            if (host != null && host.length() > 0)
                uris.add(host + "." + domain);
            else
                uris.add(domain);
        }
        return uris;
    }

    private CloudServicePlan findPlanForService(CloudService service) {
        List offerings = getServiceOfferings(service.getLabel());
        for (CloudServiceOffering offering : offerings) {
            if (service.getVersion() == null || service.getVersion().equals(offering.getVersion())) {
                for (CloudServicePlan plan : offering.getCloudServicePlans()) {
                    if (service.getPlan() != null && service.getPlan().equals(plan.getName())) {
                        return plan;
                    }
                }
            }
        }
        throw new IllegalArgumentException("Service plan " + service.getPlan() + " not found");
    }

    private HttpEntity> generatePartialResourceRequest(UploadApplicationPayload application,
                                                                                CloudResources knownRemoteResources)
            throws IOException {
        MultiValueMap body = new LinkedMultiValueMap(2);
        body.add("application", application);
        ObjectMapper mapper = new ObjectMapper();
        String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
        body.add("resources", knownRemoteResourcesPayload);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return new HttpEntity>(body, headers);
    }

    @SuppressWarnings("unchecked")
    private List> getAllResources(String urlPath, Map urlVars) {
        List> allResources = new ArrayList>();
        String resp;
        if (urlVars != null) {
            resp = getRestTemplate().getForObject(getUrl(urlPath), String.class, urlVars);
        } else {
            resp = getRestTemplate().getForObject(getUrl(urlPath), String.class);
        }
        Map respMap = JsonUtil.convertJsonToMap(resp);
        List> newResources = (List>) respMap.get("resources");
        if (newResources != null && newResources.size() > 0) {
            allResources.addAll(newResources);
        }
        String nextUrl = (String) respMap.get("next_url");
        while (nextUrl != null && nextUrl.length() > 0) {
            nextUrl = addPageOfResources(nextUrl, allResources);
        }
        return allResources;
    }

    @SuppressWarnings("unchecked")
    private UUID getAppId(String appName) {
        Map resource = findApplicationResource(appName, false);
        UUID guid = null;
        if (resource != null) {
            Map appMeta = (Map) resource.get("metadata");
            guid = UUID.fromString(String.valueOf(appMeta.get("guid")));
        }
        return guid;
    }

    @SuppressWarnings("unchecked")
    private List getAppsBoundToService(CloudService cloudService) {
        List appGuids = new ArrayList();
        String urlPath = "/v2";
        Map urlVars = new HashMap();
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlVars.put("q", "name:" + cloudService.getName());
        urlPath = urlPath + "/service_instances?q={q}";
        List> resourceList = getAllResources(urlPath, urlVars);
        for (Map resource : resourceList) {
            fillInEmbeddedResource(resource, "service_bindings");
            List> bindings =
                    CloudEntityResourceMapper.getEntityAttribute(resource, "service_bindings", List.class);
            for (Map binding : bindings) {
                String appId = CloudEntityResourceMapper.getEntityAttribute(binding, "app_guid", String.class);
                if (appId != null) {
                    appGuids.add(UUID.fromString(appId));
                }
            }
        }
        return appGuids;
    }

    private UUID getDomainGuid(String domainName, boolean required) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/domains?inline-relations-depth=1&q=name:{name}";
        urlVars.put("name", domainName);
        List> resourceList = getAllResources(urlPath, urlVars);
        UUID domainGuid = null;
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            domainGuid = resourceMapper.getGuidOfResource(resource);
        }
        if (domainGuid == null && required) {
            throw new IllegalArgumentException("Domain '" + domainName + "' not found.");
        }
        return domainGuid;
    }
    private Map getDomainGuids() {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        String domainPath = urlPath + "/domains?inline-relations-depth=1";
        List> resourceList = getAllResources(domainPath, urlVars);
        Map domains = new HashMap(resourceList.size());
        for (Map d : resourceList) {
            domains.put(
                    CloudEntityResourceMapper.getEntityAttribute(d, "name", String.class),
                    CloudEntityResourceMapper.getMeta(d).getGuid());
        }
        return domains;
    }

    private Map getInstanceInfoForApp(UUID appId, String path) {
        String url = getUrl("/v2/apps/{guid}/" + path);
        Map urlVars = new HashMap();
        urlVars.put("guid", appId);
        String resp = getRestTemplate().getForObject(url, String.class, urlVars);
        return JsonUtil.convertJsonToMap(resp);
    }

    private CloudResources getKnownRemoteResources(ApplicationArchive archive) throws IOException {
        CloudResources archiveResources = new CloudResources(archive);
        String json = JsonUtil.convertToJson(archiveResources);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(JsonUtil.JSON_MEDIA_TYPE);
        HttpEntity requestEntity = new HttpEntity(json, headers);
        ResponseEntity responseEntity =
                getRestTemplate().exchange(getUrl("/v2/resource_match"), HttpMethod.PUT, requestEntity, String.class);
        List cloudResources = JsonUtil.convertJsonToCloudResourceList(responseEntity.getBody());
        return new CloudResources(cloudResources);
    }

    private UUID getRouteGuid(String host, UUID domainGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        urlPath = urlPath + "/routes?inline-relations-depth=0&q=host:{host}";
        urlVars.put("host", host);
        List> allRoutes = getAllResources(urlPath, urlVars);
        UUID routeGuid = null;
        for (Map route : allRoutes) {
            UUID routeSpace = CloudEntityResourceMapper.getEntityAttribute(route, "space_guid", UUID.class);
            UUID routeDomain = CloudEntityResourceMapper.getEntityAttribute(route, "domain_guid", UUID.class);
            if (sessionSpace.getMeta().getGuid().equals(routeSpace) &&
                    domainGuid.equals(routeDomain)) {
                routeGuid = CloudEntityResourceMapper.getMeta(route).getGuid();
            }
        }
        return routeGuid;
    }

    private int getRunningInstances(UUID appId, CloudApplication.AppState appState) {
        int running = 0;
        ApplicationStats appStats = doGetApplicationStats(appId, appState);
        if (appStats != null && appStats.getRecords() != null) {
            for (InstanceStats inst : appStats.getRecords()) {
                if (InstanceState.RUNNING == inst.getState()) {
                    running++;
                }
            }
        }
        return running;
    }

    @SuppressWarnings("unchecked")
    private UUID getServiceBindingId(UUID appId, UUID serviceId) {
        Map urlVars = new HashMap();
        urlVars.put("guid", appId);
        List> resourceList = getAllResources("/v2/apps/{guid}/service_bindings", urlVars);
        UUID serviceBindingId = null;
        if (resourceList != null && resourceList.size() > 0) {
            for (Map resource : resourceList) {
                Map bindingMeta = (Map) resource.get("metadata");
                Map bindingEntity = (Map) resource.get("entity");
                String serviceInstanceGuid = (String) bindingEntity.get("service_instance_guid");
                if (serviceInstanceGuid != null && serviceInstanceGuid.equals(serviceId.toString())) {
    @SuppressWarnings("unchecked")
                    String bindingGuid = (String) bindingMeta.get("guid");
                    serviceBindingId = UUID.fromString(bindingGuid);
                    break;
                }
            }
        }
        return serviceBindingId;
    }

    private List getServiceOfferings(String label) {
        Assert.notNull(label, "Service label must not be null");
        List> resourceList = getAllResources("/v2/services?inline-relations-depth=1", null);
        List results = new ArrayList();
        for (Map resource : resourceList) {
            CloudServiceOffering cloudServiceOffering =
                    resourceMapper.mapResource(resource, CloudServiceOffering.class);
            if (cloudServiceOffering.getLabel() != null && label.equals(cloudServiceOffering.getLabel())) {
                results.add(cloudServiceOffering);
            }
        }
        return results;
    }

    private UUID getSpaceGuid(String spaceName, UUID orgGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/organizations/{orgGuid}/spaces?inline-relations-depth=1&q=name:{name}";
        urlVars.put("orgGuid", orgGuid);
        urlVars.put("name", spaceName);
        List> resourceList = getAllResources(urlPath, urlVars);
        UUID spaceGuid = null;
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            spaceGuid = resourceMapper.getGuidOfResource(resource);
        }
        return spaceGuid;
    }

    @SuppressWarnings("restriction")
    private Map getUserInfo(String user) {
//		String userJson = getRestTemplate().getForObject(getUrl("/v2/users/{guid}"), String.class, user);
//		Map userInfo = (Map) JsonUtil.convertJsonToMap(userJson);
//		return userInfo();
        //TODO: remove this temporary hack once the /v2/users/ uri can be accessed by mere mortals
        String userJson = "{}";
        OAuth2AccessToken accessToken = oauthClient.getToken();
        if (accessToken != null) {
            String tokenString = accessToken.getValue();
            int x = tokenString.indexOf('.');
            int y = tokenString.indexOf('.', x + 1);
            String encodedString = tokenString.substring(x + 1, y);
            try {
                byte[] decodedBytes = new sun.misc.BASE64Decoder().decodeBuffer(encodedString);
                userJson = new String(decodedBytes, 0, decodedBytes.length, "UTF-8");
            } catch (IOException e) {
            }
        }
        return (JsonUtil.convertJsonToMap(userJson));
    }

    @SuppressWarnings("unchecked")
    private boolean hasEmbeddedResource(Map resource, String resourceKey) {
        Map entity = (Map) resource.get("entity");
        return entity.containsKey(resourceKey) || entity.containsKey(resourceKey + "_url");
    }

    private void initialize(URL cloudControllerUrl, RestTemplate restTemplate, OauthClient oauthClient,
                            LoggregatorClient loggregatorClient, CloudCredentials cloudCredentials) {
        Assert.notNull(cloudControllerUrl, "CloudControllerUrl cannot be null");
        Assert.notNull(restTemplate, "RestTemplate cannot be null");
        Assert.notNull(oauthClient, "OauthClient cannot be null");

        oauthClient.init(cloudCredentials);

        this.cloudCredentials = cloudCredentials;

        this.cloudControllerUrl = cloudControllerUrl;

        this.restTemplate = restTemplate;
        configureCloudFoundryRequestFactory(restTemplate);

        this.oauthClient = oauthClient;

        this.loggregatorClient = loggregatorClient;
    }

    private boolean isOrphanRoute(CloudRoute cloudRoute) {
        return cloudRoute.getAppsUsingRoute() == 0;
    }
    private CloudApplication mapCloudApplication(Map resource) {
        UUID appId = resourceMapper.getGuidOfResource(resource);
        CloudApplication cloudApp = null;
        if (resource != null) {
            int running = getRunningInstances(appId,
                    CloudApplication.AppState.valueOf(
                            CloudEntityResourceMapper.getEntityAttribute(resource, "state", String.class)));
            ((Map) resource.get("entity")).put("running_instances", running);
            cloudApp = resourceMapper.mapResource(resource, CloudApplication.class);
            cloudApp.setUris(findApplicationUris(cloudApp.getMeta().getGuid()));
        }
        return cloudApp;
    }

    private Map processApplicationResource(Map resource, boolean fetchServiceInfo) {
        if (fetchServiceInfo) {
            fillInEmbeddedResource(resource, "service_bindings", "service_instance");
        }
        fillInEmbeddedResource(resource, "stack");
        return resource;
    }

    private void processAsyncJob(ResponseEntity>> jobCreationEntity,
                                 UploadStatusCallback callback) {
        Map jobEntity = jobCreationEntity.getBody().get("entity");
        String jobStatus;
        do {
            jobStatus = jobEntity.get("status");
            boolean unsubscribe = callback.onProgress(jobStatus);
            if (unsubscribe) {
                return;
            } else {
                try {
                    Thread.sleep(JOB_POLLING_PERIOD);
                } catch (InterruptedException ex) {
                    return;
                }
            }
            String jobId = jobEntity.get("guid");
            ResponseEntity>> jobProgressEntity =
                    getRestTemplate().exchange(getUrl("/v2/jobs/{guid}"), HttpMethod.GET, HttpEntity.EMPTY,
                            new ParameterizedTypeReference>>() {
                            }, jobId);
            jobEntity = jobProgressEntity.getBody().get("entity");
        } while (!jobStatus.equals("finished"));
    }

    private void removeUris(List uris, UUID appGuid) {
        Map domains = getDomainGuids();
        for (String uri : uris) {
            Map uriInfo = new HashMap(2);
            extractUriInfo(domains, uri, uriInfo);
            UUID domainGuid = domains.get(uriInfo.get("domainName"));
            unbindRoute(uriInfo.get("host"), domainGuid, appGuid);
        }
    }

    private StreamingLogToken streamLoggregatorLogs(String appName, ApplicationLogListener listener, boolean recent) {
        ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
            public void beforeRequest(Map> headers) {
                String authorizationHeader = oauthClient.getAuthorizationHeader();
                if (authorizationHeader != null) {
                    headers.put(AUTHORIZATION_HEADER_KEY, Arrays.asList(authorizationHeader));
                }
            }
        };

        String endpoint = getInfo().getLoggregatorEndpoint();
        String mode = recent ? "dump" : "tail";
        UUID appId = getAppId(appName);
        return loggregatorClient.connectToLoggregator(endpoint, mode, appId, listener, configurator);
    }

    private void unbindRoute(String host, UUID domainGuid, UUID appGuid) {
        UUID routeGuid = getRouteGuid(host, domainGuid);
        if (routeGuid != null) {
            String bindPath = "/v2/apps/{app}/routes/{route}";
            Map bindVars = new HashMap();
            bindVars.put("app", appGuid);
            bindVars.put("route", routeGuid);
            getRestTemplate().delete(getUrl(bindPath), bindVars);
        }
    }

    private CloudSpace validateSpaceAndOrg(String spaceName, String orgName, CloudControllerClientImpl client) {
        List spaces = client.getSpaces();

        for (CloudSpace space : spaces) {
            if (space.getName().equals(spaceName)) {
                CloudOrganization org = space.getOrganization();
                if (orgName == null || org.getName().equals(orgName)) {
                    return space;
                }
            }
        }

        throw new IllegalArgumentException("No matching organization and space found for org: " + orgName + " space: " +
                "" + spaceName);
    }

    private static class ResponseExtractorWrapper implements ResponseExtractor {

        private ClientHttpResponseCallback callback;

        public ResponseExtractorWrapper(ClientHttpResponseCallback callback) {
            this.callback = callback;
        }

        @Override
        public Object extractData(ClientHttpResponse clientHttpResponse) throws IOException {
            callback.onClientHttpResponse(clientHttpResponse);
            return null;
        }

    }

    private class AccumulatingApplicationLogListener implements ApplicationLogListener {

        private List logs = new ArrayList();

        public List getLogs() {
            Collections.sort(logs);
            return logs;
        }

        @Override
        public void onComplete() {
            synchronized (this) {
                this.notify();
            }
        }

        @Override
        public void onError(Throwable exception) {
            synchronized (this) {
                this.notify();
            }
        }

        @Override
        public void onMessage(ApplicationLog log) {
            logs.add(log);
        }
    }

    private class CloudFoundryClientHttpRequestFactory implements ClientHttpRequestFactory {

        private Integer defaultSocketTimeout = 0;

        private ClientHttpRequestFactory delegate;

        public CloudFoundryClientHttpRequestFactory(ClientHttpRequestFactory delegate) {
            this.delegate = delegate;
            captureDefaultReadTimeout();
        }

        @Override
        public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
            ClientHttpRequest request = delegate.createRequest(uri, httpMethod);

            String authorizationHeader = oauthClient.getAuthorizationHeader();
            if (authorizationHeader != null) {
                request.getHeaders().add(AUTHORIZATION_HEADER_KEY, authorizationHeader);
            }

            if (cloudCredentials != null && cloudCredentials.getProxyUser() != null) {
                request.getHeaders().add(PROXY_USER_HEADER_KEY, cloudCredentials.getProxyUser());
            }

            return request;
        }

        public void increaseReadTimeoutForStreamedTailedLogs(int timeout) {
            // May temporary increase read timeout on other unrelated concurrent
            // threads, but per-request read timeout don't seem easily
            // accessible
            if (delegate instanceof HttpComponentsClientHttpRequestFactory) {
                HttpComponentsClientHttpRequestFactory httpRequestFactory =
                        (HttpComponentsClientHttpRequestFactory) delegate;

                if (timeout > 0) {
                    httpRequestFactory.setReadTimeout(timeout);
                } else {
                    httpRequestFactory
                            .setReadTimeout(defaultSocketTimeout);
                }
            }
        }

        private void captureDefaultReadTimeout() {
            if (delegate instanceof HttpComponentsClientHttpRequestFactory) {
                HttpComponentsClientHttpRequestFactory httpRequestFactory =
                        (HttpComponentsClientHttpRequestFactory) delegate;
                defaultSocketTimeout = (Integer) httpRequestFactory
                        .getHttpClient().getParams()
                        .getParameter("http.socket.timeout");
                if (defaultSocketTimeout == null) {
                    try {
                        defaultSocketTimeout = new Socket().getSoTimeout();
                    } catch (SocketException e) {
                        defaultSocketTimeout = 0;
                    }
                }
            }
        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
        List routes = new ArrayList();
        for (Map route : allRoutes) {
//			TODO: move space_guid to path once implemented (see above):
            UUID space = CloudEntityResourceMapper.getEntityAttribute(route, "space_guid", UUID.class);
            UUID domain = CloudEntityResourceMapper.getEntityAttribute(route, "domain_guid", UUID.class);
            if (sessionSpace.getMeta().getGuid().equals(space) && domainGuid.equals(domain)) {
                //routes.add(CloudEntityResourceMapper.getEntityAttribute(route, "host", String.class));
                routes.add(resourceMapper.mapResource(route, CloudRoute.class));
            }
        }
        return routes;
    }

    private CloudSecurityGroup doGetSecurityGroup(String securityGroupName, boolean required) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/security_groups?q=name:{name}";
        urlVars.put("name", securityGroupName);
        CloudSecurityGroup securityGroup = null;
        List> resourceList = getAllResources(urlPath,
                urlVars);
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            securityGroup = resourceMapper.mapResource(resource,
                    CloudSecurityGroup.class);
        } else if (required && resourceList.size() == 0) {
            throw new IllegalArgumentException("Security group named '" + securityGroupName
                    + "' not found.");
        }

        return securityGroup;
    }

    private Map doGetServiceInstance(String serviceName, int inlineDepth) {
        String urlPath = "/v2";
        Map urlVars = new HashMap();
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlVars.put("q", "name:" + serviceName);
        urlPath = urlPath + "/service_instances?q={q}&return_user_provided_service_instances=true";
        if (inlineDepth > 0) {
            urlPath = urlPath + "&inline-relations-depth=" + inlineDepth;
        }

        List> resources = getAllResources(urlPath, urlVars);

        if (resources.size() > 0) {
            Map serviceResource = resources.get(0);
            if (hasEmbeddedResource(serviceResource, "service_plan")) {
                fillInEmbeddedResource(serviceResource, "service_plan", "service");
            }
            return serviceResource;
        }
        return null;
    }

    private void doSetQuotaToOrg(UUID orgGuid, UUID quotaGuid) {
        String setPath = "/v2/organizations/{org}";
        Map setVars = new HashMap();
        setVars.put("org", orgGuid);
        HashMap setRequest = new HashMap();
        setRequest.put("quota_definition_guid", quotaGuid);

        getRestTemplate().put(getUrl(setPath), setRequest, setVars);
    }

    private void doUnbindService(UUID appId, UUID serviceId) {
        UUID serviceBindingId = getServiceBindingId(appId, serviceId);
        getRestTemplate().delete(getUrl("/v2/service_bindings/{guid}"), serviceBindingId);
    }

    private void doUpdateSecurityGroup(CloudSecurityGroup currentGroup, String name, List> rules) {
        String path = "/v2/security_groups/{guid}";

        Map pathVariables = new HashMap();
        pathVariables.put("guid", currentGroup.getMeta().getGuid());

        HashMap request = new HashMap();
        request.put("name", name);
        request.put("rules", rules);
        // Updates of bindings to spaces and default staging/running groups must be done
        // through explicit calls to those methods and not through this generic update

        getRestTemplate().put(getUrl(path), request, pathVariables);
    }

    private List fetchOrphanRoutes(String domainName) {
        List orphanRoutes = new ArrayList<>();
        for (CloudRoute cloudRoute : getRoutes(domainName)) {
            if (isOrphanRoute(cloudRoute)) {
                orphanRoutes.add(cloudRoute);
            }
        }

        return orphanRoutes;
    }

    @SuppressWarnings("unchecked")
    private void fillInEmbeddedResource(Map resource, String... resourcePath) {
        if (resourcePath.length == 0) {
            return;
        }
        Map entity = (Map) resource.get("entity");

        String headKey = resourcePath[0];
        String[] tailPath = Arrays.copyOfRange(resourcePath, 1, resourcePath.length);

        if (!entity.containsKey(headKey)) {
            String pathUrl = entity.get(headKey + "_url").toString();
            Object response = getRestTemplate().getForObject(getUrl(pathUrl), Object.class);
            if (response instanceof Map) {
                Map responseMap = (Map) response;
                if (responseMap.containsKey("resources")) {
                    response = responseMap.get("resources");
                }
            }
            entity.put(headKey, response);
        }
        Object embeddedResource = entity.get(headKey);

        if (embeddedResource instanceof Map) {
            Map embeddedResourceMap = (Map) embeddedResource;
            //entity = (Map) embeddedResourceMap.get("entity");
            fillInEmbeddedResource(embeddedResourceMap, tailPath);
        } else if (embeddedResource instanceof List) {
            List embeddedResourcesList = (List) embeddedResource;
            for (Object r : embeddedResourcesList) {
                fillInEmbeddedResource((Map) r, tailPath);
            }
        } else {
            // no way to proceed
            return;
        }
    }

    private Map findApplicationResource(UUID appGuid, boolean fetchServiceInfo) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/apps/{app}?inline-relations-depth=1";
        urlVars.put("app", appGuid);
        String resp = getRestTemplate().getForObject(getUrl(urlPath), String.class, urlVars);

        return processApplicationResource(JsonUtil.convertJsonToMap(resp), fetchServiceInfo);
    }

    private Map findApplicationResource(String appName, boolean fetchServiceInfo) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlVars.put("q", "name:" + appName);
        urlPath = urlPath + "/apps?inline-relations-depth=1&q={q}";

        List> allResources = getAllResources(urlPath, urlVars);
        if (!allResources.isEmpty()) {
            return processApplicationResource(allResources.get(0), fetchServiceInfo);
        }
        return null;
    }

    private List findApplicationUris(UUID appGuid) {
        String urlPath = "/v2/apps/{app}/routes?inline-relations-depth=1";
        Map urlVars = new HashMap();
        urlVars.put("app", appGuid);
        List> resourceList = getAllResources(urlPath, urlVars);
        List uris = new ArrayList();
        for (Map resource : resourceList) {
            Map domainResource = CloudEntityResourceMapper.getEmbeddedResource(resource, "domain");
            String host = CloudEntityResourceMapper.getEntityAttribute(resource, "host", String.class);
            String domain = CloudEntityResourceMapper.getEntityAttribute(domainResource, "name", String.class);
            if (host != null && host.length() > 0)
                uris.add(host + "." + domain);
            else
                uris.add(domain);
        }
        return uris;
    }

    private CloudServicePlan findPlanForService(CloudService service) {
        List offerings = getServiceOfferings(service.getLabel());
        for (CloudServiceOffering offering : offerings) {
            if (service.getVersion() == null || service.getVersion().equals(offering.getVersion())) {
                for (CloudServicePlan plan : offering.getCloudServicePlans()) {
                    if (service.getPlan() != null && service.getPlan().equals(plan.getName())) {
                        return plan;
                    }
                }
            }
        }
        throw new IllegalArgumentException("Service plan " + service.getPlan() + " not found");
    }

    private HttpEntity> generatePartialResourceRequest(UploadApplicationPayload application,
                                                                                CloudResources knownRemoteResources)
            throws IOException {
        MultiValueMap body = new LinkedMultiValueMap(2);
        body.add("application", application);
        ObjectMapper mapper = new ObjectMapper();
        String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
        body.add("resources", knownRemoteResourcesPayload);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return new HttpEntity>(body, headers);
    }

    @SuppressWarnings("unchecked")
    private List> getAllResources(String urlPath, Map urlVars) {
        List> allResources = new ArrayList>();
        String resp;
        if (urlVars != null) {
            resp = getRestTemplate().getForObject(getUrl(urlPath), String.class, urlVars);
        } else {
            resp = getRestTemplate().getForObject(getUrl(urlPath), String.class);
        }
        Map respMap = JsonUtil.convertJsonToMap(resp);
        List> newResources = (List>) respMap.get("resources");
        if (newResources != null && newResources.size() > 0) {
            allResources.addAll(newResources);
        }
        String nextUrl = (String) respMap.get("next_url");
        while (nextUrl != null && nextUrl.length() > 0) {
            nextUrl = addPageOfResources(nextUrl, allResources);
        }
        return allResources;
    }

    @SuppressWarnings("unchecked")
    private UUID getAppId(String appName) {
        Map resource = findApplicationResource(appName, false);
        UUID guid = null;
        if (resource != null) {
            Map appMeta = (Map) resource.get("metadata");
            guid = UUID.fromString(String.valueOf(appMeta.get("guid")));
        }
        return guid;
    }

    @SuppressWarnings("unchecked")
    private List getAppsBoundToService(CloudService cloudService) {
        List appGuids = new ArrayList();
        String urlPath = "/v2";
        Map urlVars = new HashMap();
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        urlVars.put("q", "name:" + cloudService.getName());
        urlPath = urlPath + "/service_instances?q={q}";
        List> resourceList = getAllResources(urlPath, urlVars);
        for (Map resource : resourceList) {
            fillInEmbeddedResource(resource, "service_bindings");
            List> bindings =
                    CloudEntityResourceMapper.getEntityAttribute(resource, "service_bindings", List.class);
            for (Map binding : bindings) {
                String appId = CloudEntityResourceMapper.getEntityAttribute(binding, "app_guid", String.class);
                if (appId != null) {
                    appGuids.add(UUID.fromString(appId));
                }
            }
        }
        return appGuids;
    }

    private String getCurrentUserId() {
        String username = getInfo().getUser();
        Map userMap = getUserInfo(username);
        String userId = (String) userMap.get("user_id");
        return userId;
    }

    private UUID getDomainGuid(String domainName, boolean required) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/domains?inline-relations-depth=1&q=name:{name}";
        urlVars.put("name", domainName);
        List> resourceList = getAllResources(urlPath, urlVars);
        UUID domainGuid = null;
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            domainGuid = resourceMapper.getGuidOfResource(resource);
        }
        if (domainGuid == null && required) {
            throw new IllegalArgumentException("Domain '" + domainName + "' not found.");
        }
        return domainGuid;
    }

    private Map getDomainGuids() {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        if (sessionSpace != null) {
            urlVars.put("space", sessionSpace.getMeta().getGuid());
            urlPath = urlPath + "/spaces/{space}";
        }
        String domainPath = urlPath + "/domains?inline-relations-depth=1";
        List> resourceList = getAllResources(domainPath, urlVars);
        Map domains = new HashMap(resourceList.size());
        for (Map d : resourceList) {
            domains.put(
                    CloudEntityResourceMapper.getEntityAttribute(d, "name", String.class),
                    CloudEntityResourceMapper.getMeta(d).getGuid());
        }
        return domains;
    }

    private Map getInstanceInfoForApp(UUID appId, String path) {
        String url = getUrl("/v2/apps/{guid}/" + path);
        Map urlVars = new HashMap();
        urlVars.put("guid", appId);
        String resp = getRestTemplate().getForObject(url, String.class, urlVars);
        return JsonUtil.convertJsonToMap(resp);
    }

    private CloudResources getKnownRemoteResources(ApplicationArchive archive) throws IOException {
        CloudResources archiveResources = new CloudResources(archive);
        String json = JsonUtil.convertToJson(archiveResources);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(JsonUtil.JSON_MEDIA_TYPE);
        HttpEntity requestEntity = new HttpEntity(json, headers);
        ResponseEntity responseEntity =
                getRestTemplate().exchange(getUrl("/v2/resource_match"), HttpMethod.PUT, requestEntity, String.class);
        List cloudResources = JsonUtil.convertJsonToCloudResourceList(responseEntity.getBody());
        return new CloudResources(cloudResources);
    }

    private UUID getRouteGuid(String host, UUID domainGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2";
        urlPath = urlPath + "/routes?inline-relations-depth=0&q=host:{host}";
        urlVars.put("host", host);
        List> allRoutes = getAllResources(urlPath, urlVars);
        UUID routeGuid = null;
        for (Map route : allRoutes) {
            UUID routeSpace = CloudEntityResourceMapper.getEntityAttribute(route, "space_guid", UUID.class);
            UUID routeDomain = CloudEntityResourceMapper.getEntityAttribute(route, "domain_guid", UUID.class);
            if (sessionSpace.getMeta().getGuid().equals(routeSpace) &&
                    domainGuid.equals(routeDomain)) {
                routeGuid = CloudEntityResourceMapper.getMeta(route).getGuid();
            }
        }
        return routeGuid;
    }

    private int getRunningInstances(UUID appId, CloudApplication.AppState appState) {
        int running = 0;
        ApplicationStats appStats = doGetApplicationStats(appId, appState);
        if (appStats != null && appStats.getRecords() != null) {
            for (InstanceStats inst : appStats.getRecords()) {
                if (InstanceState.RUNNING == inst.getState()) {
                    running++;
                }
            }
        }
        return running;
    }

    // Security Group operations

    @SuppressWarnings("unchecked")
    private UUID getServiceBindingId(UUID appId, UUID serviceId) {
        Map urlVars = new HashMap();
        urlVars.put("guid", appId);
        List> resourceList = getAllResources("/v2/apps/{guid}/service_bindings", urlVars);
        UUID serviceBindingId = null;
        if (resourceList != null && resourceList.size() > 0) {
            for (Map resource : resourceList) {
                Map bindingMeta = (Map) resource.get("metadata");
                Map bindingEntity = (Map) resource.get("entity");
                String serviceInstanceGuid = (String) bindingEntity.get("service_instance_guid");
                if (serviceInstanceGuid != null && serviceInstanceGuid.equals(serviceId.toString())) {
                    String bindingGuid = (String) bindingMeta.get("guid");
                    serviceBindingId = UUID.fromString(bindingGuid);
                    break;
                }
            }
        }
        return serviceBindingId;
    }

    private List getServiceOfferings(String label) {
        Assert.notNull(label, "Service label must not be null");
        List> resourceList = getAllResources("/v2/services?inline-relations-depth=1", null);
        List results = new ArrayList();
        for (Map resource : resourceList) {
            CloudServiceOffering cloudServiceOffering =
                    resourceMapper.mapResource(resource, CloudServiceOffering.class);
            if (cloudServiceOffering.getLabel() != null && label.equals(cloudServiceOffering.getLabel())) {
                results.add(cloudServiceOffering);
            }
        }
        return results;
    }

    private UUID getSpaceGuid(String spaceName, UUID orgGuid) {
        Map urlVars = new HashMap();
        String urlPath = "/v2/organizations/{orgGuid}/spaces?inline-relations-depth=1&q=name:{name}";
        urlVars.put("orgGuid", orgGuid);
        urlVars.put("name", spaceName);
        List> resourceList = getAllResources(urlPath, urlVars);
        if (resourceList.size() > 0) {
            Map resource = resourceList.get(0);
            return resourceMapper.getGuidOfResource(resource);
        }
        return null;
    }

    private UUID getSpaceGuid(String orgName, String spaceName) {
        CloudOrganization org = getOrgByName(orgName, true);
        return getSpaceGuid(spaceName, org.getMeta().getGuid());
    }

    private List getSpaceUserGuids(String orgName, String spaceName, String urlPath) {
        if (orgName == null || spaceName == null) {
            assertSpaceProvided("get space users");
        }

        UUID spaceGuid;
        if (spaceName == null) {
            spaceGuid = sessionSpace.getMeta().getGuid();
        } else {
            CloudOrganization organization = (orgName == null ? sessionSpace.getOrganization() : getOrgByName
                    (orgName, true));
            spaceGuid = getSpaceGuid(spaceName, organization.getMeta().getGuid());
        }

        Map urlVars = new HashMap();
        urlVars.put("guid", spaceGuid);

        List managersGuid = new ArrayList();
        List> resourceList = getAllResources(urlPath, urlVars);
        for (Map resource : resourceList) {
            UUID userGuid = resourceMapper.getGuidOfResource(resource);
            managersGuid.add(userGuid);
        }
        return managersGuid;
    }

    @SuppressWarnings("restriction")
    private Map getUserInfo(String user) {
//		String userJson = getRestTemplate().getForObject(getUrl("/v2/users/{guid}"), String.class, user);
//		Map userInfo = (Map) JsonUtil.convertJsonToMap(userJson);
//		return userInfo();
        //TODO: remove this temporary hack once the /v2/users/ uri can be accessed by mere mortals
        String userJson = "{}";
        OAuth2AccessToken accessToken = oauthClient.getToken();
        if (accessToken != null) {
            String tokenString = accessToken.getValue();
            int x = tokenString.indexOf('.');
            int y = tokenString.indexOf('.', x + 1);
            String encodedString = tokenString.substring(x + 1, y);
            try {
                byte[] decodedBytes = new sun.misc.BASE64Decoder().decodeBuffer(encodedString);
                userJson = new String(decodedBytes, 0, decodedBytes.length, "UTF-8");
            } catch (IOException e) {
            }
        }
        return (JsonUtil.convertJsonToMap(userJson));
    }

    @SuppressWarnings("unchecked")
    private boolean hasEmbeddedResource(Map resource, String resourceKey) {
        Map entity = (Map) resource.get("entity");
        return entity.containsKey(resourceKey) || entity.containsKey(resourceKey + "_url");
    }

    private void initialize(URL cloudControllerUrl, RestTemplate restTemplate, OauthClient oauthClient,
                            LoggregatorClient loggregatorClient, CloudCredentials cloudCredentials) {
        Assert.notNull(cloudControllerUrl, "CloudControllerUrl cannot be null");
        Assert.notNull(restTemplate, "RestTemplate cannot be null");
        Assert.notNull(oauthClient, "OauthClient cannot be null");

        oauthClient.init(cloudCredentials);

        this.cloudCredentials = cloudCredentials;

        this.cloudControllerUrl = cloudControllerUrl;

        this.restTemplate = restTemplate;
        configureCloudFoundryRequestFactory(restTemplate);

        this.oauthClient = oauthClient;

        this.loggregatorClient = loggregatorClient;
    }

    private boolean isOrphanRoute(CloudRoute cloudRoute) {
        return cloudRoute.getAppsUsingRoute() == 0;
    }

    @SuppressWarnings("unchecked")
    private CloudApplication mapCloudApplication(Map resource) {
        UUID appId = resourceMapper.getGuidOfResource(resource);
        CloudApplication cloudApp = null;
        if (resource != null) {
            int running = getRunningInstances(appId,
                    CloudApplication.AppState.valueOf(
                            CloudEntityResourceMapper.getEntityAttribute(resource, "state", String.class)));
            ((Map) resource.get("entity")).put("running_instances", running);
            cloudApp = resourceMapper.mapResource(resource, CloudApplication.class);
            cloudApp.setUris(findApplicationUris(cloudApp.getMeta().getGuid()));
        }
        return cloudApp;
    }

    private Map processApplicationResource(Map resource, boolean fetchServiceInfo) {
        if (fetchServiceInfo) {
            fillInEmbeddedResource(resource, "service_bindings", "service_instance");
        }
        fillInEmbeddedResource(resource, "stack");
        return resource;
    }

    private void processAsyncJob(Map jobResource, UploadStatusCallback callback) {
        CloudJob job = resourceMapper.mapResource(jobResource, CloudJob.class);
        do {
            boolean unsubscribe = callback.onProgress(job.getStatus().toString());
            if (unsubscribe) {
                return;
            }
            if (job.getStatus() == CloudJob.Status.FAILED) {
                return;
            }

            try {
                Thread.sleep(JOB_POLLING_PERIOD);
            } catch (InterruptedException ex) {
                return;
            }

            ResponseEntity> jobProgressEntity =
                    getRestTemplate().exchange(getUrl(job.getMeta().getUrl()),
                            HttpMethod.GET, HttpEntity.EMPTY,
                            new ParameterizedTypeReference>() {
                            });
            job = resourceMapper.mapResource(jobProgressEntity.getBody(), CloudJob.class);
        } while (job.getStatus() != CloudJob.Status.FINISHED);
    }

    private void removeUris(List uris, UUID appGuid) {
        Map domains = getDomainGuids();
        for (String uri : uris) {
            Map uriInfo = new HashMap(2);
            extractUriInfo(domains, uri, uriInfo);
            UUID domainGuid = domains.get(uriInfo.get("domainName"));
            unbindRoute(uriInfo.get("host"), domainGuid, appGuid);
        }
    }

    private StreamingLogToken streamLoggregatorLogs(String appName, ApplicationLogListener listener, boolean recent) {
        ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
            public void beforeRequest(Map> headers) {
                String authorizationHeader = oauthClient.getAuthorizationHeader();
                if (authorizationHeader != null) {
                    headers.put(AUTHORIZATION_HEADER_KEY, Arrays.asList(authorizationHeader));
                }
            }
        };

        String endpoint = getInfo().getLoggregatorEndpoint();
        String mode = recent ? "dump" : "tail";
        UUID appId = getAppId(appName);
        return loggregatorClient.connectToLoggregator(endpoint, mode, appId, listener, configurator);
    }

    private void unbindRoute(String host, UUID domainGuid, UUID appGuid) {
        UUID routeGuid = getRouteGuid(host, domainGuid);
        if (routeGuid != null) {
            String bindPath = "/v2/apps/{app}/routes/{route}";
            Map bindVars = new HashMap();
            bindVars.put("app", appGuid);
            bindVars.put("route", routeGuid);
            getRestTemplate().delete(getUrl(bindPath), bindVars);
        }
    }

    private CloudSpace validateSpaceAndOrg(String spaceName, String orgName, CloudControllerClientImpl client) {
        List spaces = client.getSpaces();

        for (CloudSpace space : spaces) {
            if (space.getName().equals(spaceName)) {
                CloudOrganization org = space.getOrganization();
                if (orgName == null || org.getName().equals(orgName)) {
                    return space;
                }
            }
        }

        throw new IllegalArgumentException("No matching organization and space found for org: " + orgName + " space: " +
                "" + spaceName);
    }

    private void waitForAsyncJobCompletion(Map jobResponse) {
        long timeout = System.currentTimeMillis() + JOB_TIMEOUT;
        while (System.currentTimeMillis() < timeout) {
            CloudJob job = resourceMapper.mapResource(jobResponse, CloudJob.class);

            if (job.getStatus() == CloudJob.Status.FINISHED) {
                return;
            }

            if (job.getStatus() == CloudJob.Status.FAILED) {
                throw new CloudOperationException(job.getErrorDetails().getDescription());
            }

            try {
                Thread.sleep(JOB_POLLING_PERIOD);
            } catch (InterruptedException e) {
                return;
            }

            jobResponse = getRestTemplate().exchange(getUrl(job.getMeta().getUrl()),
                    HttpMethod.GET, HttpEntity.EMPTY,
                    new ParameterizedTypeReference>() {
                    }).getBody();
        }
    }

    private static class ResponseExtractorWrapper implements ResponseExtractor {

        private ClientHttpResponseCallback callback;

        public ResponseExtractorWrapper(ClientHttpResponseCallback callback) {
            this.callback = callback;
        }

        @Override
        public Object extractData(ClientHttpResponse clientHttpResponse) throws IOException {
            callback.onClientHttpResponse(clientHttpResponse);
            return null;
        }

    }

    private class AccumulatingApplicationLogListener implements ApplicationLogListener {

        private List logs = new ArrayList();

        public List getLogs() {
            Collections.sort(logs);
            return logs;
        }

        @Override
        public void onComplete() {
            synchronized (this) {
                this.notify();
            }
        }

        @Override
        public void onError(Throwable exception) {
            synchronized (this) {
                this.notify();
            }
        }

        @Override
        public void onMessage(ApplicationLog log) {
            logs.add(log);
        }
    }

    private class CloudFoundryClientHttpRequestFactory implements ClientHttpRequestFactory {

        private Integer defaultSocketTimeout = 0;

        private ClientHttpRequestFactory delegate;

        public CloudFoundryClientHttpRequestFactory(ClientHttpRequestFactory delegate) {
            this.delegate = delegate;
            captureDefaultReadTimeout();
        }

        @Override
        public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
            ClientHttpRequest request = delegate.createRequest(uri, httpMethod);

            String authorizationHeader = oauthClient.getAuthorizationHeader();
            if (authorizationHeader != null) {
                request.getHeaders().add(AUTHORIZATION_HEADER_KEY, authorizationHeader);
            }

            if (cloudCredentials != null && cloudCredentials.getProxyUser() != null) {
                request.getHeaders().add(PROXY_USER_HEADER_KEY, cloudCredentials.getProxyUser());
            }

            return request;
        }

        public void increaseReadTimeoutForStreamedTailedLogs(int timeout) {
            // May temporary increase read timeout on other unrelated concurrent
            // threads, but per-request read timeout don't seem easily
            // accessible
            if (delegate instanceof HttpComponentsClientHttpRequestFactory) {
                HttpComponentsClientHttpRequestFactory httpRequestFactory =
                        (HttpComponentsClientHttpRequestFactory) delegate;

                if (timeout > 0) {
                    httpRequestFactory.setReadTimeout(timeout);
                } else {
                    httpRequestFactory
                            .setReadTimeout(defaultSocketTimeout);
                }
            }
        }

        private void captureDefaultReadTimeout() {
            // As of HttpClient 4.3.x, obtaining the default parameters is deprecated and removed,
            // so we fallback to java.net.Socket.

            if (defaultSocketTimeout == null) {
                try {
                    defaultSocketTimeout = new Socket().getSoTimeout();
                } catch (SocketException e) {
                    defaultSocketTimeout = 0;
                }
            }
        }
    }


}
File
CloudControllerClientImpl.java
Developer's decision
Manual
Kind of conflict
Annotation
Class declaration
Comment
If statement
Method declaration
Method invocation
Return statement
Variable
Chunk
Conflicting content
import java.util.UUID;

public class LoggregatorClient {
<<<<<<< HEAD
	private static final UriTemplate loggregatorStreamUriTemplate = new UriTemplate("{endpoint}/{kind}/?app={appId}");
	private static final UriTemplate loggregatorRecentUriTemplate = new UriTemplate("{scheme}://{host}/recent");

	private boolean trustSelfSignedCerts;

	public LoggregatorClient(boolean trustSelfSignedCerts) {
		this.trustSelfSignedCerts = trustSelfSignedCerts;
	}

	public String getRecentHttpEndpoint(String endpoint) {
		URI uri = stringToUri(endpoint);

		String scheme = uri.getScheme();
		String host = uri.getHost();

		if ("wss".equals(scheme)) {
			scheme = "https";
		} else {
			scheme = "http";
		}

		return loggregatorRecentUriTemplate.expand(scheme, host).toString();
	}

	private URI stringToUri(String endPoint) {
		try {
			return new URI(endPoint);
		} catch (URISyntaxException e) {
			throw new CloudOperationException("Unable to parse Loggregator endpoint " + endPoint);
		}
	}

	public StreamingLogTokenImpl connectToLoggregator(String endpoint, String mode, UUID appId,
	                                                  ApplicationLogListener listener,
	                                                  ClientEndpointConfig.Configurator configurator) {
		URI loggregatorUri = loggregatorStreamUriTemplate.expand(endpoint, mode, appId);

		try {
			WebSocketContainer container = ContainerProvider.getWebSocketContainer();
			ClientEndpointConfig config = buildClientConfig(configurator);
			Session session = container.connectToServer(new LoggregatorEndpoint(listener), config, loggregatorUri);
			return new StreamingLogTokenImpl(session);
		} catch (DeploymentException e) {
			throw new CloudOperationException(e);
		} catch (IOException e) {
			throw new CloudOperationException(e);
		}
	}

	private ClientEndpointConfig buildClientConfig(ClientEndpointConfig.Configurator configurator) {
		ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(configurator).build();

		if (trustSelfSignedCerts) {
			SSLContext sslContext = buildSslContext();
			Map userProperties = config.getUserProperties();
			userProperties.put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
		}

		return config;
	}

	private SSLContext buildSslContext() {
		try {
			SSLContextBuilder contextBuilder = new SSLContextBuilder().
					useTLS().
					loadTrustMaterial(null, new TrustSelfSignedStrategy());

			return contextBuilder.build();
		} catch (GeneralSecurityException e) {
			throw new CloudOperationException(e);
		}
	}
=======

    private static final UriTemplate loggregatorRecentUriTemplate = new UriTemplate("{scheme}://{host}/recent");

    private static final UriTemplate loggregatorStreamUriTemplate = new UriTemplate("{endpoint}/{kind}/?app={appId}");

    private boolean trustSelfSignedCerts;

    public LoggregatorClient(boolean trustSelfSignedCerts) {
        this.trustSelfSignedCerts = trustSelfSignedCerts;
    }

    public StreamingLogTokenImpl connectToLoggregator(String endpoint, String mode, UUID appId,
                                                      ApplicationLogListener listener,
                                                      ClientEndpointConfig.Configurator configurator) {
        URI loggregatorUri = loggregatorStreamUriTemplate.expand(endpoint, mode, appId);

        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            ClientEndpointConfig config = buildClientConfig(configurator);
            Session session = container.connectToServer(new LoggregatorEndpoint(listener), config, loggregatorUri);
            return new StreamingLogTokenImpl(session);
        } catch (DeploymentException e) {
            throw new CloudOperationException(e);
        } catch (IOException e) {
            throw new CloudOperationException(e);
        }
    }

    public String getRecentHttpEndpoint(String endpoint) {
        URI uri = stringToUri(endpoint);

        String scheme = uri.getScheme();
        String host = uri.getHost();

        if ("wss".equals(scheme)) {
            scheme = "https";
        } else {
            scheme = "http";
        }

        return loggregatorRecentUriTemplate.expand(scheme, host).toString();
    }

    private ClientEndpointConfig buildClientConfig(ClientEndpointConfig.Configurator configurator) {
        ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(configurator).build();

        if (trustSelfSignedCerts) {
            SSLContext sslContext = createSslContext();
            Map userProperties = config.getUserProperties();
            userProperties.put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
        }

        return config;
    }

    private SSLContext createSslContext() {
        try {
            TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws
                        CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws
                        CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }};

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, null);

            return sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new CloudOperationException(e);
        } catch (KeyManagementException e) {
            throw new CloudOperationException(e);
        }
    }

    private URI stringToUri(String endPoint) {
        try {
            return new URI(endPoint);
        } catch (URISyntaxException e) {
            throw new CloudOperationException("Unable to parse Loggregator endpoint " + endPoint);
        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
import java.util.UUID;

public class LoggregatorClient {

    private static final UriTemplate loggregatorRecentUriTemplate = new UriTemplate("{scheme}://{host}/recent");

    private static final UriTemplate loggregatorStreamUriTemplate = new UriTemplate("{endpoint}/{kind}/?app={appId}");

    private boolean trustSelfSignedCerts;

    public LoggregatorClient(boolean trustSelfSignedCerts) {
        this.trustSelfSignedCerts = trustSelfSignedCerts;
    }

    public StreamingLogTokenImpl connectToLoggregator(String endpoint, String mode, UUID appId,
                                                      ApplicationLogListener listener,
                                                      ClientEndpointConfig.Configurator configurator) {
        URI loggregatorUri = loggregatorStreamUriTemplate.expand(endpoint, mode, appId);

        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            ClientEndpointConfig config = buildClientConfig(configurator);
            Session session = container.connectToServer(new LoggregatorEndpoint(listener), config, loggregatorUri);
            return new StreamingLogTokenImpl(session);
        } catch (DeploymentException e) {
            throw new CloudOperationException(e);
        } catch (IOException e) {
            throw new CloudOperationException(e);
        }
    }

    public String getRecentHttpEndpoint(String endpoint) {
        URI uri = stringToUri(endpoint);

        String scheme = uri.getScheme();
        String host = uri.getHost();

        if ("wss".equals(scheme)) {
            scheme = "https";
        } else {
            scheme = "http";
        }

        return loggregatorRecentUriTemplate.expand(scheme, host).toString();
    }

    private ClientEndpointConfig buildClientConfig(ClientEndpointConfig.Configurator configurator) {
        ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(configurator).build();

        if (trustSelfSignedCerts) {
            SSLContext sslContext = buildSslContext();
            Map userProperties = config.getUserProperties();
            userProperties.put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
        }

        return config;
    }

    private SSLContext buildSslContext() {
        try {
            SSLContextBuilder contextBuilder = new SSLContextBuilder().
                    useTLS().
                    loadTrustMaterial(null, new TrustSelfSignedStrategy());

            return contextBuilder.build();
        } catch (GeneralSecurityException e) {
            throw new CloudOperationException(e);
        }
    }

    private URI stringToUri(String endPoint) {
        try {
            return new URI(endPoint);
        } catch (URISyntaxException e) {
            throw new CloudOperationException("Unable to parse Loggregator endpoint " + endPoint);
        }
    }
}
File
LoggregatorClient.java
Developer's decision
Combination
Kind of conflict
Attribute
Method declaration
Method invocation
Chunk
Conflicting content
import org.cloudfoundry.client.lib.domain.CloudQuota;
import org.cloudfoundry.client.lib.domain.CloudRoute;
import org.cloudfoundry.client.lib.domain.CloudService;
<<<<<<< HEAD
import org.cloudfoundry.client.lib.domain.CloudServiceBinding;
import org.cloudfoundry.client.lib.domain.CloudServiceInstance;
=======
import org.cloudfoundry.client.lib.domain.CloudServiceBroker;
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
import org.cloudfoundry.client.lib.domain.CloudServiceOffering;
import org.cloudfoundry.client.lib.domain.CloudServicePlan;
import org.cloudfoundry.client.lib.domain.CloudSpace;
Solution content
import org.cloudfoundry.client.lib.domain.CloudQuota;
import org.cloudfoundry.client.lib.domain.CloudRoute;
import org.cloudfoundry.client.lib.domain.CloudSecurityGroup;
import org.cloudfoundry.client.lib.domain.CloudService;
import org.cloudfoundry.client.lib.domain.CloudServiceBinding;
import org.cloudfoundry.client.lib.domain.CloudServiceBroker;
import org.cloudfoundry.client.lib.domain.CloudServiceInstance;
import org.cloudfoundry.client.lib.domain.CloudServiceOffering;
import org.cloudfoundry.client.lib.domain.CloudServicePlan;
import org.cloudfoundry.client.lib.domain.CloudSpace;
File
CloudEntityResourceMapper.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
                "Error during mapping - unsupported class for attribute mapping " + targetClass.getName());
    }

<<<<<<< HEAD
	@SuppressWarnings("unchecked")
	public  T mapResource(Map resource, Class targetClass) {
		if (targetClass == CloudSpace.class) {
			return (T) mapSpaceResource(resource);
		}
		if (targetClass == CloudOrganization.class) {
			return (T) mapOrganizationResource(resource);
		}
		if (targetClass == CloudDomain.class) {
			return (T) mapDomainResource(resource);
		}
		if (targetClass == CloudRoute.class) {
			return (T) mapRouteResource(resource);
		}
		if (targetClass == CloudApplication.class) {
			return (T) mapApplicationResource(resource);
		}
		if (targetClass == CloudEvent.class) {
			return (T) mapEventResource(resource);
		}
		if (targetClass == CloudService.class) {
			return (T) mapServiceResource(resource);
		}
		if (targetClass == CloudServiceInstance.class) {
			return (T) mapServiceInstanceResource(resource);
		}
		if (targetClass == CloudServiceOffering.class) {
			return (T) mapServiceOfferingResource(resource);
		}
		if (targetClass == CloudServiceBroker.class) {
			return (T) mapServiceBrokerResource(resource);
		}
		if (targetClass == CloudStack.class) {
			return (T) mapStackResource(resource);
		}
		if (targetClass == CloudQuota.class) {
			return (T) mapQuotaResource(resource);
		}
		if (targetClass == CloudSecurityGroup.class) {
			return (T) mapApplicationSecurityGroupResource(resource);
		}
		if (targetClass == CloudJob.class) {
			return (T) mapJobResource(resource);
		}
		if (targetClass == CloudUser.class){
            return (T) mapUserResource(resource);
=======
    @SuppressWarnings("unchecked")
    public static CloudEntity.Meta getMeta(Map resource) {
        Map metadata = (Map) resource.get("metadata");
        UUID guid = UUID.fromString(String.valueOf(metadata.get("guid")));
        Date createdDate = parseDate(String.valueOf(metadata.get("created_at")));
        Date updatedDate = parseDate(String.valueOf(metadata.get("updated_at")));
        return new CloudEntity.Meta(guid, createdDate, updatedDate);
    }

    private static Date parseDate(String dateString) {
        if (dateString != null) {
            try {
                // if the time zone part of the dateString contains a colon (e.g. 2013-09-19T21:56:36+00:00)
                // then remove it before parsing
                String isoDateString = dateString.replaceFirst(":(?=[0-9]{2}$)", "");
                return dateFormatter.parse(isoDateString);
            } catch (Exception ignore) {
            }
        }
        return null;
    }

    public UUID getGuidOfResource(Map resource) {
        return getMeta(resource).getGuid();
    }

    public String getNameOfResource(Map resource) {
        return getEntityAttribute(resource, "name", String.class);
    }

    @SuppressWarnings("unchecked")
    public  T mapResource(Map resource, Class targetClass) {
        if (targetClass == CloudSpace.class) {
            return (T) mapSpaceResource(resource);
        }
        if (targetClass == CloudOrganization.class) {
            return (T) mapOrganizationResource(resource);
        }
        if (targetClass == CloudDomain.class) {
            return (T) mapDomainResource(resource);
        }
        if (targetClass == CloudRoute.class) {
            return (T) mapRouteResource(resource);
        }
        if (targetClass == CloudApplication.class) {
            return (T) mapApplicationResource(resource);
        }
        if (targetClass == CloudService.class) {
            return (T) mapServiceInstanceResource(resource);
        }
        if (targetClass == CloudServiceOffering.class) {
            return (T) mapServiceResource(resource);
        }
        if (targetClass == CloudServiceBroker.class) {
            return (T) mapServiceBrokerResource(resource);
        }
        if (targetClass == CloudStack.class) {
            return (T) mapStackResource(resource);
        }
        if (targetClass == CloudQuota.class) {
            return (T) mapQuotaResource(resource);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
        }
        throw new IllegalArgumentException(
                "Error during mapping - unsupported class for entity mapping " + targetClass.getName());
Solution content
                "Error during mapping - unsupported class for attribute mapping " + targetClass.getName());
    }

    @SuppressWarnings("unchecked")
    public static CloudEntity.Meta getMeta(Map resource) {
        Map metadata = (Map) resource.get("metadata");
        UUID guid;
        try {
            guid = UUID.fromString(String.valueOf(metadata.get("guid")));
        } catch (IllegalArgumentException e) {
            guid = null;
        }
        Date createdDate = parseDate(String.valueOf(metadata.get("created_at")));
        Date updatedDate = parseDate(String.valueOf(metadata.get("updated_at")));
        String url = String.valueOf(metadata.get("url"));
        return new CloudEntity.Meta(guid, createdDate, updatedDate, url);
    }

    private static Date parseDate(String dateString) {
        if (dateString != null) {
            try {
                // if the time zone part of the dateString contains a colon (e.g. 2013-09-19T21:56:36+00:00)
                // then remove it before parsing
                String isoDateString = dateString.replaceFirst(":(?=[0-9]{2}$)", "").replaceFirst("Z$", "+0000");
                return dateFormatter.parse(isoDateString);
            } catch (Exception ignore) {
            }
        }
        return null;
    }

    public UUID getGuidOfResource(Map resource) {
        return getMeta(resource).getGuid();
    }

    public String getNameOfResource(Map resource) {
        return getEntityAttribute(resource, "name", String.class);
    }

    @SuppressWarnings("unchecked")
    public  T mapResource(Map resource, Class targetClass) {
        if (targetClass == CloudSpace.class) {
            return (T) mapSpaceResource(resource);
        }
        if (targetClass == CloudOrganization.class) {
            return (T) mapOrganizationResource(resource);
        }
        if (targetClass == CloudDomain.class) {
            return (T) mapDomainResource(resource);
        }
        if (targetClass == CloudRoute.class) {
            return (T) mapRouteResource(resource);
        }
        if (targetClass == CloudApplication.class) {
            return (T) mapApplicationResource(resource);
        }
        if (targetClass == CloudEvent.class) {
            return (T) mapEventResource(resource);
        }
        if (targetClass == CloudService.class) {
            return (T) mapServiceResource(resource);
        }
        if (targetClass == CloudServiceInstance.class) {
            return (T) mapServiceInstanceResource(resource);
        }
        if (targetClass == CloudServiceOffering.class) {
            return (T) mapServiceOfferingResource(resource);
        }
        if (targetClass == CloudServiceBroker.class) {
            return (T) mapServiceBrokerResource(resource);
        }
        if (targetClass == CloudStack.class) {
            return (T) mapStackResource(resource);
        }
        if (targetClass == CloudQuota.class) {
            return (T) mapQuotaResource(resource);
        }
        if (targetClass == CloudSecurityGroup.class) {
            return (T) mapApplicationSecurityGroupResource(resource);
        }
        if (targetClass == CloudJob.class) {
            return (T) mapJobResource(resource);
        }
        if (targetClass == CloudUser.class) {
            return (T) mapUserResource(resource);
        }
        throw new IllegalArgumentException(
                "Error during mapping - unsupported class for entity mapping " + targetClass.getName());
File
CloudEntityResourceMapper.java
Developer's decision
Manual
Kind of conflict
Annotation
Cast expression
If statement
Method declaration
Method signature
Return statement
Chunk
Conflicting content
        }
        //TODO: debug
        app.setDebug(null);

<<<<<<< HEAD
    private CloudUser mapUserResource(Map resource) {
        boolean isActiveUser = getEntityAttribute(resource, "active", Boolean.class);
        boolean isAdminUser = getEntityAttribute(resource, "admin", Boolean.class);
        String defaultSpaceGuid = getEntityAttribute(resource, "default_space_guid", String.class);
        String username = getEntityAttribute(resource, "username", String.class);

        return new CloudUser(getMeta(resource), username,isAdminUser,isActiveUser,defaultSpaceGuid);
    }

    private CloudSpace mapSpaceResource(Map resource) {
		Map organizationMap = getEmbeddedResource(resource, "organization");
		CloudOrganization organization = null;
		if (organizationMap != null) {
			organization = mapOrganizationResource(organizationMap);
		}
		return new CloudSpace(getMeta(resource), getNameOfResource(resource), organization);
	}

	private CloudOrganization mapOrganizationResource(Map resource) {
		Boolean billingEnabled = getEntityAttribute(resource, "billing_enabled", Boolean.class);
		Map quotaDefinition = getEmbeddedResource(resource, "quota_definition");
		CloudQuota quota = null;
		if (quotaDefinition != null) {
			quota = mapQuotaResource(quotaDefinition);
		}
		return new CloudOrganization(getMeta(resource), getNameOfResource(resource), quota, billingEnabled);
	}
=======
        Integer runningInstancesAttribute = getEntityAttribute(resource, "running_instances", Integer.class);
        if (runningInstancesAttribute != null) {
            app.setRunningInstances(runningInstancesAttribute);
        }
        String command = getEntityAttribute(resource, "command", String.class);
        String buildpack = getEntityAttribute(resource, "buildpack", String.class);
        Map stackResource = getEmbeddedResource(resource, "stack");
        CloudStack stack = mapStackResource(stackResource);
        Integer healthCheckTimeout = getEntityAttribute(resource, "health_check_timeout", Integer.class);
        Staging staging = new Staging(command, buildpack, stack.getName(), healthCheckTimeout);
        app.setStaging(staging);

        Map envMap = getEntityAttribute(resource, "environment_json", Map.class);
        if (envMap.size() > 0) {
            app.setEnv(envMap);
        app.setMemory(getEntityAttribute(resource, "memory", Integer.class));
        app.setDiskQuota(getEntityAttribute(resource, "disk_quota", Integer.class));
        List> serviceBindings = getEntityAttribute(resource, "service_bindings", List.class);
        List serviceList = new ArrayList();
        for (Map binding : serviceBindings) {
            Map service = getEntityAttribute(binding, "service_instance", Map.class);
            String serviceName = getNameOfResource(service);
            if (serviceName != null) {
                serviceList.add(serviceName);
            }
        }
        app.setServices(serviceList);
        return app;
    }

    private CloudDomain mapDomainResource(Map resource) {
        @SuppressWarnings("unchecked")
        Map ownerResource = getEntityAttribute(resource, "owning_organization", Map.class);
        CloudOrganization owner;
        if (ownerResource == null) {
            owner = new CloudOrganization(CloudEntity.Meta.defaultMeta(), "none");
        } else {
            owner = mapOrganizationResource(ownerResource);
        }
        return new CloudDomain(getMeta(resource), getNameOfResource(resource), owner);
    }

    private CloudOrganization mapOrganizationResource(
            Map resource) {
        Boolean billingEnabled = getEntityAttribute(resource,
                "billing_enabled", Boolean.class);
        Map quotaDefinition = getEmbeddedResource(resource,
                "quota_definition");
        CloudQuota quota = null;
        if (quotaDefinition != null) {
            quota = mapQuotaResource(quotaDefinition);
        }
        return new CloudOrganization(getMeta(resource),
                getNameOfResource(resource), quota, billingEnabled);
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

	private CloudQuota mapQuotaResource(Map resource) {
		Boolean nonBasicServicesAllowed = getEntityAttribute(resource, "non_basic_services_allowed", Boolean.class);
Solution content
        //TODO: debug
        app.setDebug(null);

        Integer runningInstancesAttribute = getEntityAttribute(resource, "running_instances", Integer.class);
        if (runningInstancesAttribute != null) {
            app.setRunningInstances(runningInstancesAttribute);
        }
        String command = getEntityAttribute(resource, "command", String.class);
        String buildpack = getEntityAttribute(resource, "buildpack", String.class);
        String detectedBuildpack = getEntityAttribute(resource, "detected_buildpack", String.class);
        Map stackResource = getEmbeddedResource(resource, "stack");
        CloudStack stack = mapStackResource(stackResource);
        Integer healthCheckTimeout = getEntityAttribute(resource, "health_check_timeout", Integer.class);
        Staging staging = new Staging(command, buildpack, stack.getName(), healthCheckTimeout, detectedBuildpack);
        app.setStaging(staging);

        Map spaceResource = getEmbeddedResource(resource, "space");
        CloudSpace space = mapSpaceResource(spaceResource);
        app.setSpace(space);

        Map envMap = getEntityAttribute(resource, "environment_json", Map.class);
        if (envMap.size() > 0) {
            app.setEnv(envMap);
        }
        app.setMemory(getEntityAttribute(resource, "memory", Integer.class));
        app.setDiskQuota(getEntityAttribute(resource, "disk_quota", Integer.class));
        List> serviceBindings = getEntityAttribute(resource, "service_bindings", List.class);
        List serviceList = new ArrayList();
        for (Map binding : serviceBindings) {
            Map service = getEntityAttribute(binding, "service_instance", Map.class);
            String serviceName = getNameOfResource(service);
            if (serviceName != null) {
                serviceList.add(serviceName);
            }
        }
        app.setServices(serviceList);
        return app;
    }

    private CloudSecurityGroup mapApplicationSecurityGroupResource(Map resource) {
        return new CloudSecurityGroup(getMeta(resource),
                getNameOfResource(resource),
                getSecurityGroupRules(resource),
                getEntityAttribute(resource, "running_default", Boolean.class),
                getEntityAttribute(resource, "staging_default", Boolean.class));
    }

    private CloudDomain mapDomainResource(Map resource) {
        @SuppressWarnings("unchecked")
        Map ownerResource = getEntityAttribute(resource, "owning_organization", Map.class);
        CloudOrganization owner;
        if (ownerResource == null) {
            owner = new CloudOrganization(CloudEntity.Meta.defaultMeta(), "none");
        } else {
            owner = mapOrganizationResource(ownerResource);
        }
        return new CloudDomain(getMeta(resource), getNameOfResource(resource), owner);
    }

    private CloudEvent mapEventResource(Map resource) {
        CloudEvent event = new CloudEvent(
                getMeta(resource),
                getNameOfResource(resource));
        event.setType(getEntityAttribute(resource, "type", String.class));
        event.setActor(getEntityAttribute(resource, "actor", String.class));
        event.setActorType(getEntityAttribute(resource, "actor_type", String.class));
        event.setActorName(getEntityAttribute(resource, "actor_name", String.class));
        event.setActee(getEntityAttribute(resource, "actee", String.class));
        event.setActeeType(getEntityAttribute(resource, "actee_type", String.class));
        event.setActeeName(getEntityAttribute(resource, "actee_name", String.class));
        Date timestamp = parseDate(getEntityAttribute(resource, "timestamp", String.class));
        event.setTimestamp(timestamp);

        return event;
    }

    private CloudJob mapJobResource(Map resource) {
        String status = getEntityAttribute(resource, "status", String.class);
        Map errorDetailsResource = (Map) resource.get("error_details");
        CloudJob.ErrorDetails errorDetails = null;
        if (errorDetailsResource != null) {
            Long code = getEntityAttribute(errorDetailsResource, "code", Long.class);
            String description = getEntityAttribute(errorDetailsResource, "description", String.class);
            String errorCode = getEntityAttribute(errorDetailsResource, "error_code", String.class);
            errorDetails = new CloudJob.ErrorDetails(code, description, errorCode);
        }

        return new CloudJob(getMeta(resource), CloudJob.Status.getEnum(status), errorDetails);
    }

    private CloudOrganization mapOrganizationResource(Map resource) {
        Boolean billingEnabled = getEntityAttribute(resource, "billing_enabled", Boolean.class);
        Map quotaDefinition = getEmbeddedResource(resource, "quota_definition");
        CloudQuota quota = null;
        if (quotaDefinition != null) {
            quota = mapQuotaResource(quotaDefinition);
        }
        return new CloudOrganization(getMeta(resource), getNameOfResource(resource), quota, billingEnabled);
    }

    private CloudQuota mapQuotaResource(Map resource) {
        Boolean nonBasicServicesAllowed = getEntityAttribute(resource, "non_basic_services_allowed", Boolean.class);
        int totalServices = getEntityAttribute(resource, "total_services", Integer.class);
        int totalRoutes = getEntityAttribute(resource, "total_routes", Integer.class);
        long memoryLimit = getEntityAttribute(resource, "memory_limit", Long.class);

        return new CloudQuota(getMeta(resource), getNameOfResource(resource),
                nonBasicServicesAllowed, totalServices, totalRoutes,
                memoryLimit);
    }

    private CloudRoute mapRouteResource(Map resource) {
        @SuppressWarnings("unchecked")
        List apps = getEntityAttribute(resource, "apps", List.class);
        String host = getEntityAttribute(resource, "host", String.class);
        CloudDomain domain = mapDomainResource(getEmbeddedResource(resource, "domain"));
        return new CloudRoute(getMeta(resource), host, domain, apps.size());
    }

    @SuppressWarnings("unchecked")
    private CloudServiceBinding mapServiceBinding(Map resource) {
        CloudServiceBinding binding = new CloudServiceBinding(getMeta(resource),
                getNameOfResource(resource));

        binding.setAppGuid(UUID.fromString(getEntityAttribute(resource, "app_guid", String.class)));
        binding.setSyslogDrainUrl(getEntityAttribute(resource, "syslog_drain_url", String.class));
        binding.setCredentials(getEntityAttribute(resource, "credentials", Map.class));
        binding.setBindingOptions(getEntityAttribute(resource, "binding_options", Map.class));

        return binding;
    }

    private CloudServiceBroker mapServiceBrokerResource(Map resource) {
        return new CloudServiceBroker(getMeta(resource),
                getEntityAttribute(resource, "name", String.class),
                getEntityAttribute(resource, "broker_url", String.class),
                getEntityAttribute(resource, "auth_username", String.class));
    }

    @SuppressWarnings("unchecked")
    private CloudServiceInstance mapServiceInstanceResource(Map resource) {
        CloudServiceInstance serviceInstance = new CloudServiceInstance(getMeta(resource), getNameOfResource(resource));

        serviceInstance.setType(getEntityAttribute(resource, "type", String.class));
        serviceInstance.setDashboardUrl(getEntityAttribute(resource, "dashboard_url", String.class));
        serviceInstance.setCredentials(getEntityAttribute(resource, "credentials", Map.class));

        Map servicePlanResource = getEmbeddedResource(resource, "service_plan");
        serviceInstance.setServicePlan(mapServicePlanResource(servicePlanResource));

        CloudService service = mapServiceResource(resource);
        serviceInstance.setService(service);

        List> bindingsResource = getEmbeddedResourceList(getEntity(resource), "service_bindings");
        List bindings = new ArrayList<>(bindingsResource.size());
        for (Map bindingResource : bindingsResource) {
            bindings.add(mapServiceBinding(bindingResource));
        }
        serviceInstance.setBindings(bindings);

        return serviceInstance;
    }

    private CloudServiceOffering mapServiceOfferingResource(Map resource) {
        CloudServiceOffering cloudServiceOffering = new CloudServiceOffering(
                getMeta(resource),
                getEntityAttribute(resource, "label", String.class),
                getEntityAttribute(resource, "provider", String.class),
                getEntityAttribute(resource, "version", String.class),
                getEntityAttribute(resource, "description", String.class),
                getEntityAttribute(resource, "active", Boolean.class),
                getEntityAttribute(resource, "bindable", Boolean.class),
                getEntityAttribute(resource, "url", String.class),
                getEntityAttribute(resource, "info_url", String.class),
                getEntityAttribute(resource, "unique_id", String.class),
                getEntityAttribute(resource, "extra", String.class),
                getEntityAttribute(resource, "documentation_url", String.class));
        List> servicePlanList = getEmbeddedResourceList(getEntity(resource), "service_plans");
        if (servicePlanList != null) {
            for (Map servicePlanResource : servicePlanList) {
                CloudServicePlan servicePlan = mapServicePlanResource(servicePlanResource);
                servicePlan.setServiceOffering(cloudServiceOffering);
                cloudServiceOffering.addCloudServicePlan(servicePlan);
            }
        }
        return cloudServiceOffering;
    }

    private CloudServicePlan mapServicePlanResource(Map servicePlanResource) {
        Boolean publicPlan = getEntityAttribute(servicePlanResource, "public", Boolean.class);

        return new CloudServicePlan(
                getMeta(servicePlanResource),
                getEntityAttribute(servicePlanResource, "name", String.class),
                getEntityAttribute(servicePlanResource, "description", String.class),
                getEntityAttribute(servicePlanResource, "free", Boolean.class),
                publicPlan == null ? true : publicPlan,
                getEntityAttribute(servicePlanResource, "extra", String.class),
                getEntityAttribute(servicePlanResource, "unique_id", String.class));
    }

    private CloudService mapServiceResource(Map resource) {
        CloudService cloudService = new CloudService(getMeta(resource), getNameOfResource(resource));
        Map servicePlanResource = getEmbeddedResource(resource, "service_plan");
        if (servicePlanResource != null) {
            cloudService.setPlan(getEntityAttribute(servicePlanResource, "name", String.class));

            Map serviceResource = getEmbeddedResource(servicePlanResource, "service");
            if (serviceResource != null) {
                cloudService.setLabel(getEntityAttribute(serviceResource, "label", String.class));
                cloudService.setProvider(getEntityAttribute(serviceResource, "provider", String.class));
                cloudService.setVersion(getEntityAttribute(serviceResource, "version", String.class));
            }
        }
        return cloudService;
    }

    private CloudSpace mapSpaceResource(Map resource) {
        Map organizationMap = getEmbeddedResource(resource, "organization");
        CloudOrganization organization = null;
        if (organizationMap != null) {
            organization = mapOrganizationResource(organizationMap);
        }
        return new CloudSpace(getMeta(resource), getNameOfResource(resource), organization);
    }

    private CloudStack mapStackResource(Map resource) {
        return new CloudStack(getMeta(resource),
                getNameOfResource(resource),
                getEntityAttribute(resource, "description", String.class));
    }

    private CloudUser mapUserResource(Map resource) {
        boolean isActiveUser = getEntityAttribute(resource, "active", Boolean.class);
        boolean isAdminUser = getEntityAttribute(resource, "admin", Boolean.class);
        String defaultSpaceGuid = getEntityAttribute(resource, "default_space_guid", String.class);
        String username = getEntityAttribute(resource, "username", String.class);

        return new CloudUser(getMeta(resource), username, isAdminUser, isActiveUser, defaultSpaceGuid);
    }
}
File
CloudEntityResourceMapper.java
Developer's decision
Manual
Kind of conflict
For statement
If statement
Method declaration
Method invocation
Return statement
Variable
Chunk
Conflicting content
			memoryLimit);
	}

<<<<<<< HEAD
	private CloudDomain mapDomainResource(Map resource) {
		@SuppressWarnings("unchecked")
		Map ownerResource = getEntityAttribute(resource, "owning_organization", Map.class);
		CloudOrganization owner;
		if (ownerResource == null) {
			owner = new CloudOrganization(CloudEntity.Meta.defaultMeta(), "none");
		} else {
			owner = mapOrganizationResource(ownerResource);
		}
		return new CloudDomain(getMeta(resource), getNameOfResource(resource), owner);
	}

	private CloudRoute mapRouteResource(Map resource) {
		@SuppressWarnings("unchecked")
		List apps = getEntityAttribute(resource, "apps", List.class);
		String host = getEntityAttribute(resource, "host", String.class);
		CloudDomain domain = mapDomainResource(getEmbeddedResource(resource, "domain"));
		return new CloudRoute(getMeta(resource), host, domain, apps.size());
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private CloudApplication mapApplicationResource(Map resource) {
		CloudApplication app = new CloudApplication(
				getMeta(resource),
				getNameOfResource(resource));
		app.setInstances(getEntityAttribute(resource, "instances", Integer.class));
		app.setServices(new ArrayList());
		app.setState(CloudApplication.AppState.valueOf(getEntityAttribute(resource, "state", String.class)));
		//TODO: debug
		app.setDebug(null);

		Integer runningInstancesAttribute = getEntityAttribute(resource, "running_instances", Integer.class);
		if (runningInstancesAttribute != null) {
			app.setRunningInstances(runningInstancesAttribute);
		}
		String command = getEntityAttribute(resource, "command", String.class);
		String buildpack = getEntityAttribute(resource, "buildpack", String.class);
		String detectedBuildpack = getEntityAttribute(resource, "detected_buildpack", String.class);

		Map stackResource = getEmbeddedResource(resource, "stack");
		CloudStack stack = mapStackResource(stackResource);
		Integer healthCheckTimeout = getEntityAttribute(resource, "health_check_timeout", Integer.class);
		Staging staging = new Staging(command, buildpack, stack.getName(), healthCheckTimeout, detectedBuildpack);
		app.setStaging(staging);

		Map spaceResource = getEmbeddedResource(resource, "space");
		CloudSpace space = mapSpaceResource(spaceResource);
		app.setSpace(space);

		Map envMap = getEntityAttribute(resource, "environment_json", Map.class);
		if (envMap.size() > 0) {
			app.setEnv(envMap);
		}
		app.setMemory(getEntityAttribute(resource, "memory", Integer.class));
		app.setDiskQuota(getEntityAttribute(resource, "disk_quota", Integer.class));
		List> serviceBindings = getEntityAttribute(resource, "service_bindings", List.class);
		List serviceList = new ArrayList();
		for (Map binding : serviceBindings) {
			Map service = getEntityAttribute(binding, "service_instance", Map.class);
			String serviceName = getNameOfResource(service);
			if (serviceName != null) {
				serviceList.add(serviceName);
			}
		}
		app.setServices(serviceList);
		return app;
	}

	private CloudEvent mapEventResource(Map resource) {
		CloudEvent event = new CloudEvent(
			getMeta(resource),
			getNameOfResource(resource));
		event.setType(getEntityAttribute(resource, "type", String.class));
		event.setActor(getEntityAttribute(resource, "actor", String.class));
		event.setActorType(getEntityAttribute(resource, "actor_type", String.class));
		event.setActorName(getEntityAttribute(resource, "actor_name", String.class));
		event.setActee(getEntityAttribute(resource, "actee", String.class));
		event.setActeeType(getEntityAttribute(resource, "actee_type", String.class));
		event.setActeeName(getEntityAttribute(resource, "actee_name", String.class));
		Date timestamp = parseDate(getEntityAttribute(resource, "timestamp", String.class));
		event.setTimestamp(timestamp);

		return event;
	}

	private CloudService mapServiceResource(Map resource) {
		CloudService cloudService = new CloudService(getMeta(resource), getNameOfResource(resource));
		Map servicePlanResource = getEmbeddedResource(resource, "service_plan");
		if (servicePlanResource != null) {
			cloudService.setPlan(getEntityAttribute(servicePlanResource, "name", String.class));

			Map serviceResource = getEmbeddedResource(servicePlanResource, "service");
			if (serviceResource != null) {
				cloudService.setLabel(getEntityAttribute(serviceResource, "label", String.class));
				cloudService.setProvider(getEntityAttribute(serviceResource, "provider", String.class));
				cloudService.setVersion(getEntityAttribute(serviceResource, "version", String.class));
			}
		}
		return cloudService;
	}

	@SuppressWarnings("unchecked")
	private CloudServiceInstance mapServiceInstanceResource(Map resource) {
		CloudServiceInstance serviceInstance = new CloudServiceInstance(getMeta(resource), getNameOfResource(resource));

		serviceInstance.setType(getEntityAttribute(resource, "type", String.class));
		serviceInstance.setDashboardUrl(getEntityAttribute(resource, "dashboard_url", String.class));
		serviceInstance.setCredentials(getEntityAttribute(resource, "credentials", Map.class));

		Map servicePlanResource = getEmbeddedResource(resource, "service_plan");
		serviceInstance.setServicePlan(mapServicePlanResource(servicePlanResource));

		CloudService service = mapServiceResource(resource);
		serviceInstance.setService(service);

		List> bindingsResource = getEmbeddedResourceList(getEntity(resource), "service_bindings");
		List bindings = new ArrayList<>(bindingsResource.size());
		for (Map bindingResource : bindingsResource) {
			bindings.add(mapServiceBinding(bindingResource));
		}
		serviceInstance.setBindings(bindings);

		return serviceInstance;
	}
	@SuppressWarnings("unchecked")
	private CloudServiceBinding mapServiceBinding(Map resource) {
		CloudServiceBinding binding = new CloudServiceBinding(getMeta(resource),
			getNameOfResource(resource));

		binding.setAppGuid(UUID.fromString(getEntityAttribute(resource, "app_guid", String.class)));
		binding.setSyslogDrainUrl(getEntityAttribute(resource, "syslog_drain_url", String.class));
		binding.setCredentials(getEntityAttribute(resource, "credentials", Map.class));
		binding.setBindingOptions(getEntityAttribute(resource, "binding_options", Map.class));

		return binding;
	}

	private CloudServiceOffering mapServiceOfferingResource(Map resource) {
		CloudServiceOffering cloudServiceOffering = new CloudServiceOffering(
				getMeta(resource),
				getEntityAttribute(resource, "label", String.class),
				getEntityAttribute(resource, "provider", String.class),
				getEntityAttribute(resource, "version", String.class),
				getEntityAttribute(resource, "description", String.class),
				getEntityAttribute(resource, "active", Boolean.class),
				getEntityAttribute(resource, "bindable", Boolean.class),
				getEntityAttribute(resource, "url", String.class),
				getEntityAttribute(resource, "info_url", String.class),
				getEntityAttribute(resource, "unique_id", String.class),
				getEntityAttribute(resource, "extra", String.class),
				getEntityAttribute(resource, "documentation_url", String.class));
		List> servicePlanList = getEmbeddedResourceList(getEntity(resource), "service_plans");
		if (servicePlanList != null) {
			for (Map servicePlanResource : servicePlanList) {
				CloudServicePlan servicePlan = mapServicePlanResource(servicePlanResource);
				servicePlan.setServiceOffering(cloudServiceOffering);
				cloudServiceOffering.addCloudServicePlan(servicePlan);
			}
		}
		return cloudServiceOffering;
	}

	private CloudServicePlan mapServicePlanResource(Map servicePlanResource) {
		Boolean publicPlan = getEntityAttribute(servicePlanResource, "public", Boolean.class);

		return new CloudServicePlan(
				getMeta(servicePlanResource),
				getEntityAttribute(servicePlanResource, "name", String.class),
				getEntityAttribute(servicePlanResource, "description", String.class),
				getEntityAttribute(servicePlanResource, "free", Boolean.class),
				publicPlan == null ? true : publicPlan,
				getEntityAttribute(servicePlanResource, "extra", String.class),
				getEntityAttribute(servicePlanResource, "unique_id", String.class));
	}

	private CloudServiceBroker mapServiceBrokerResource(Map resource) {
		return new CloudServiceBroker(getMeta(resource),
			getEntityAttribute(resource, "name", String.class),
			getEntityAttribute(resource, "broker_url", String.class),
			getEntityAttribute(resource, "auth_username", String.class));
	}

	private CloudStack mapStackResource(Map resource) {
		return new CloudStack(getMeta(resource),
				getNameOfResource(resource),
				getEntityAttribute(resource, "description", String.class));
	}

	private CloudSecurityGroup mapApplicationSecurityGroupResource(Map resource) {
		return new CloudSecurityGroup(getMeta(resource),
				getNameOfResource(resource),
				getSecurityGroupRules(resource),
				getEntityAttribute(resource, "running_default", Boolean.class),
				getEntityAttribute(resource, "staging_default", Boolean.class));
	}
	
	@SuppressWarnings("unchecked")
	private List getSecurityGroupRules(Map resource){
		List rules = new ArrayList();
		List> jsonRules = getEntityAttribute(resource, "rules", List.class);
		for(Map jsonRule : jsonRules){
			rules.add(new SecurityGroupRule(
					(String) jsonRule.get("protocol"), 
					(String) jsonRule.get("ports"), 
					(String) jsonRule.get("destination"), 
					(Boolean) jsonRule.get("log"), 
					(Integer) jsonRule.get("type"), 
					(Integer) jsonRule.get("code")));
		}
		return rules;
	}

	private CloudJob mapJobResource(Map resource) {
		String status = getEntityAttribute(resource, "status", String.class);
		Map errorDetailsResource = (Map) resource.get("error_details");
		CloudJob.ErrorDetails errorDetails = null;
		if (errorDetailsResource != null) {
			Long code = getEntityAttribute(errorDetailsResource, "code", Long.class);
			String description = getEntityAttribute(errorDetailsResource, "description", String.class);
			String errorCode = getEntityAttribute(errorDetailsResource, "error_code", String.class);
			errorDetails = new CloudJob.ErrorDetails(code, description, errorCode);
		}

		return new CloudJob(getMeta(resource), CloudJob.Status.getEnum(status), errorDetails);
	}

	@SuppressWarnings("unchecked")
	public static CloudEntity.Meta getMeta(Map resource) {
		Map metadata = (Map) resource.get("metadata");
		UUID guid;
		try {
			guid = UUID.fromString(String.valueOf(metadata.get("guid")));
		} catch (IllegalArgumentException e) {
			guid = null;
		}
		Date createdDate = parseDate(String.valueOf(metadata.get("created_at")));
		Date updatedDate = parseDate(String.valueOf(metadata.get("updated_at")));
		String url = String.valueOf(metadata.get("url"));
		return new CloudEntity.Meta(guid, createdDate, updatedDate, url);
	}

	private static Date parseDate(String dateString) {
		if (dateString != null) {
			try {
				// if the time zone part of the dateString contains a colon (e.g. 2013-09-19T21:56:36+00:00)
				// then remove it before parsing
				String isoDateString = dateString.replaceFirst(":(?=[0-9]{2}$)", "").replaceFirst("Z$", "+0000");
				return dateFormatter.parse(isoDateString);
			} catch (Exception ignore) {}
		}
		return null;
	}
=======
    private CloudRoute mapRouteResource(Map resource) {
        @SuppressWarnings("unchecked")
        List apps = getEntityAttribute(resource, "apps", List.class);
        String host = getEntityAttribute(resource, "host", String.class);
        CloudDomain domain = mapDomainResource(getEmbeddedResource(resource, "domain"));
        return new CloudRoute(getMeta(resource), host, domain, apps.size());
    }

    private CloudServiceBroker mapServiceBrokerResource(Map resource) {
        return new CloudServiceBroker(getMeta(resource),
                getEntityAttribute(resource, "name", String.class),
                getEntityAttribute(resource, "broker_url", String.class),
                getEntityAttribute(resource, "auth_username", String.class));
    }

    private CloudService mapServiceInstanceResource(Map resource) {
        CloudService cloudService = new CloudService(
                getMeta(resource),
                getNameOfResource(resource));
        Map servicePlanResource = getEmbeddedResource(resource, "service_plan");
        if (servicePlanResource != null) {
            cloudService.setPlan(getEntityAttribute(servicePlanResource, "name", String.class));
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

            Map serviceResource = getEmbeddedResource(servicePlanResource, "service");
            if (serviceResource != null) {
Solution content
    private CloudRoute mapRouteResource(Map resource) {
        @SuppressWarnings("unchecked")
        List apps = getEntityAttribute(resource, "apps", List.class);
        String host = getEntityAttribute(resource, "host", String.class);
        CloudDomain domain = mapDomainResource(getEmbeddedResource(resource, "domain"));
        return new CloudRoute(getMeta(resource), host, domain, apps.size());
    }

    @SuppressWarnings("unchecked")
    private CloudServiceBinding mapServiceBinding(Map resource) {
        CloudServiceBinding binding = new CloudServiceBinding(getMeta(resource),
                getNameOfResource(resource));

        binding.setAppGuid(UUID.fromString(getEntityAttribute(resource, "app_guid", String.class)));
        binding.setSyslogDrainUrl(getEntityAttribute(resource, "syslog_drain_url", String.class));
        binding.setCredentials(getEntityAttribute(resource, "credentials", Map.class));
        binding.setBindingOptions(getEntityAttribute(resource, "binding_options", Map.class));

        return binding;
    }

    private CloudServiceBroker mapServiceBrokerResource(Map resource) {
        return new CloudServiceBroker(getMeta(resource),
                getEntityAttribute(resource, "name", String.class),
                getEntityAttribute(resource, "broker_url", String.class),
                getEntityAttribute(resource, "auth_username", String.class));
    }

    @SuppressWarnings("unchecked")
    private CloudServiceInstance mapServiceInstanceResource(Map resource) {
        CloudServiceInstance serviceInstance = new CloudServiceInstance(getMeta(resource), getNameOfResource(resource));

        serviceInstance.setType(getEntityAttribute(resource, "type", String.class));
        serviceInstance.setDashboardUrl(getEntityAttribute(resource, "dashboard_url", String.class));
        serviceInstance.setCredentials(getEntityAttribute(resource, "credentials", Map.class));

        Map servicePlanResource = getEmbeddedResource(resource, "service_plan");
        serviceInstance.setServicePlan(mapServicePlanResource(servicePlanResource));
File
CloudEntityResourceMapper.java
Developer's decision
Combination
Kind of conflict
Annotation
If statement
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
        return cloudService;
    }

<<<<<<< HEAD
	@SuppressWarnings("unchecked")
	public static  T getEntityAttribute(Map resource, String attributeName, Class targetClass) {
		if (resource == null) {
			return null;
		}
		Map entity = (Map) resource.get("entity");
		Object attributeValue = entity.get(attributeName);
		if (attributeValue == null) {
			return null;
		}
		if (targetClass == String.class) {
			return (T) String.valueOf(attributeValue);
		}
		if (targetClass == Long.class) {
			return (T) Long.valueOf(String.valueOf(attributeValue));
		}
		if (targetClass == Integer.class || targetClass == Boolean.class || targetClass == Map.class || targetClass == List.class) {
			return (T) attributeValue;
		}
		if (targetClass == UUID.class && attributeValue instanceof String) {
			return (T) UUID.fromString((String)attributeValue);
		}
		throw new IllegalArgumentException(
				"Error during mapping - unsupported class for attribute mapping " + targetClass.getName());
	}
=======
    private CloudServiceOffering mapServiceResource(Map resource) {
        CloudServiceOffering cloudServiceOffering = new CloudServiceOffering(
                getMeta(resource),
                getEntityAttribute(resource, "label", String.class),
                getEntityAttribute(resource, "provider", String.class),
                getEntityAttribute(resource, "version", String.class),
                getEntityAttribute(resource, "description", String.class),
                getEntityAttribute(resource, "active", Boolean.class),
                getEntityAttribute(resource, "bindable", Boolean.class),
                getEntityAttribute(resource, "url", String.class),
                getEntityAttribute(resource, "info_url", String.class),
                getEntityAttribute(resource, "unique_id", String.class),
                getEntityAttribute(resource, "extra", String.class),
                getEntityAttribute(resource, "documentation_url", String.class));
        List> servicePlanList = getEmbeddedResourceList(getEntity(resource), "service_plans");
        if (servicePlanList != null) {
            for (Map servicePlanResource : servicePlanList) {
                Boolean publicPlan = getEntityAttribute(servicePlanResource, "public", Boolean.class);
                CloudServicePlan servicePlan =
                        new CloudServicePlan(
                                getMeta(servicePlanResource),
                                getEntityAttribute(servicePlanResource, "name", String.class),
                                getEntityAttribute(servicePlanResource, "description", String.class),
                                getEntityAttribute(servicePlanResource, "free", Boolean.class),
                                publicPlan == null ? true : publicPlan,
                                getEntityAttribute(servicePlanResource, "extra", String.class),
                                getEntityAttribute(servicePlanResource, "unique_id", String.class),
                                cloudServiceOffering);
                cloudServiceOffering.addCloudServicePlan(servicePlan);
            }
        }
        return cloudServiceOffering;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    private CloudSpace mapSpaceResource(Map resource) {
        Map organizationMap = getEmbeddedResource(resource, "organization");
Solution content
    }

    private CloudServiceOffering mapServiceOfferingResource(Map resource) {
        CloudServiceOffering cloudServiceOffering = new CloudServiceOffering(
                getMeta(resource),
                getEntityAttribute(resource, "label", String.class),
                getEntityAttribute(resource, "provider", String.class),
                getEntityAttribute(resource, "version", String.class),
                getEntityAttribute(resource, "description", String.class),
                getEntityAttribute(resource, "active", Boolean.class),
                getEntityAttribute(resource, "bindable", Boolean.class),
                getEntityAttribute(resource, "url", String.class),
                getEntityAttribute(resource, "info_url", String.class),
                getEntityAttribute(resource, "unique_id", String.class),
                getEntityAttribute(resource, "extra", String.class),
                getEntityAttribute(resource, "documentation_url", String.class));
        List> servicePlanList = getEmbeddedResourceList(getEntity(resource), "service_plans");
        if (servicePlanList != null) {
            for (Map servicePlanResource : servicePlanList) {
                CloudServicePlan servicePlan = mapServicePlanResource(servicePlanResource);
                servicePlan.setServiceOffering(cloudServiceOffering);
                cloudServiceOffering.addCloudServicePlan(servicePlan);
            }
        }
        return cloudServiceOffering;
    }

    private CloudServicePlan mapServicePlanResource(Map servicePlanResource) {
        Boolean publicPlan = getEntityAttribute(servicePlanResource, "public", Boolean.class);

        return new CloudServicePlan(
                getMeta(servicePlanResource),
                getEntityAttribute(servicePlanResource, "name", String.class),
                getEntityAttribute(servicePlanResource, "description", String.class),
                getEntityAttribute(servicePlanResource, "free", Boolean.class),
                publicPlan == null ? true : publicPlan,
                getEntityAttribute(servicePlanResource, "extra", String.class),
                getEntityAttribute(servicePlanResource, "unique_id", String.class));
    }

    private CloudService mapServiceResource(Map resource) {
        CloudService cloudService = new CloudService(getMeta(resource), getNameOfResource(resource));
        Map servicePlanResource = getEmbeddedResource(resource, "service_plan");
        if (servicePlanResource != null) {
            cloudService.setPlan(getEntityAttribute(servicePlanResource, "name", String.class));

            Map serviceResource = getEmbeddedResource(servicePlanResource, "service");
            if (serviceResource != null) {
                cloudService.setLabel(getEntityAttribute(serviceResource, "label", String.class));
                cloudService.setProvider(getEntityAttribute(serviceResource, "provider", String.class));
                cloudService.setVersion(getEntityAttribute(serviceResource, "version", String.class));
            }
        }
        return cloudService;
    }

    private CloudSpace mapSpaceResource(Map resource) {
        Map organizationMap = getEmbeddedResource(resource, "organization");
File
CloudEntityResourceMapper.java
Developer's decision
Manual
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
package org.cloudfoundry.client.lib.util;

<<<<<<< HEAD
import static org.apache.http.conn.ssl.SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;

import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

=======
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
Solution content
package org.cloudfoundry.client.lib.util;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
File
RestUtil.java
Developer's decision
Version 2
Kind of conflict
Import
Chunk
Conflicting content
        try {
 */
public class RestUtil {

<<<<<<< HEAD
	public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
		RestTemplate restTemplate = new LoggingRestTemplate();
		restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts));
		restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler());
		restTemplate.setMessageConverters(getHttpMessageConverters());

		return restTemplate;
	}

	public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
		HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();

		if (trustSelfSignedCerts) {
			httpClientBuilder.setSslcontext(buildSslContext());
			httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		}

		if (httpProxyConfiguration != null) {
			HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
			httpClientBuilder.setProxy(proxy);

			if (httpProxyConfiguration.isAuthRequired()) {
				BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
				credentialsProvider.setCredentials(
						new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()),
						new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(), httpProxyConfiguration.getPassword()));
				httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
			}

			HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBuilder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBuilder.build();
		HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

		return requestFactory;
	}

	public OauthClient createOauthClient(URL authorizationUrl, HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
		return new OauthClient(authorizationUrl, createRestTemplate(httpProxyConfiguration, trustSelfSignedCerts));
	}

	private javax.net.ssl.SSLContext buildSslContext()  {
		try {
			return new SSLContextBuilder().useSSL().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		} catch (GeneralSecurityException gse) {
			throw new RuntimeException("An error occurred setting up the SSLContext", gse);
		}
	}

	private List> getHttpMessageConverters() {
		List> messageConverters = new ArrayList>();
		messageConverters.add(new ByteArrayHttpMessageConverter());
		messageConverters.add(new StringHttpMessageConverter());
		messageConverters.add(new ResourceHttpMessageConverter());
		messageConverters.add(new UploadApplicationPayloadHttpMessageConverter());
		messageConverters.add(getFormHttpMessageConverter());
		messageConverters.add(new MappingJackson2HttpMessageConverter());
		messageConverters.add(new LoggregatorHttpMessageConverter());
		return messageConverters;
	}

	private FormHttpMessageConverter getFormHttpMessageConverter() {
		FormHttpMessageConverter formPartsMessageConverter = new CloudFoundryFormHttpMessageConverter();
		formPartsMessageConverter.setPartConverters(getFormPartsMessageConverters());
		return formPartsMessageConverter;
	}

	private List> getFormPartsMessageConverters() {
		List> partConverters = new ArrayList>();
		StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
		stringConverter.setSupportedMediaTypes(Collections.singletonList(JsonUtil.JSON_MEDIA_TYPE));
		stringConverter.setWriteAcceptCharset(false);
		partConverters.add(stringConverter);
		partConverters.add(new ResourceHttpMessageConverter());
		partConverters.add(new UploadApplicationPayloadHttpMessageConverter());
		return partConverters;
	}
=======
    public OauthClient createOauthClient(URL authorizationUrl, HttpProxyConfiguration httpProxyConfiguration, boolean
            trustSelfSignedCerts) {
        return new OauthClient(authorizationUrl, createRestTemplate(httpProxyConfiguration, trustSelfSignedCerts));
    }

    public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean
            trustSelfSignedCerts) {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        DefaultHttpClient httpClient = (DefaultHttpClient) requestFactory.getHttpClient();

        if (trustSelfSignedCerts) {
            registerSslSocketFactory(httpClient);
        }

        if (httpProxyConfiguration != null) {
            if (httpProxyConfiguration.isAuthRequired()) {
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()),
                        new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(), httpProxyConfiguration
                                .getPassword()));
            }

            HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }

        return requestFactory;
    }

    public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean
            trustSelfSignedCerts) {
        RestTemplate restTemplate = new LoggingRestTemplate();
        restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts));
        restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler());
        restTemplate.setMessageConverters(getHttpMessageConverters());

        return restTemplate;
    }

    private FormHttpMessageConverter getFormHttpMessageConverter() {
        FormHttpMessageConverter formPartsMessageConverter = new CloudFoundryFormHttpMessageConverter();
        formPartsMessageConverter.setPartConverters(getFormPartsMessageConverters());
        return formPartsMessageConverter;
    }

    private List> getFormPartsMessageConverters() {
        List> partConverters = new ArrayList>();
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setSupportedMediaTypes(Collections.singletonList(JsonUtil.JSON_MEDIA_TYPE));
        stringConverter.setWriteAcceptCharset(false);
        partConverters.add(stringConverter);
        partConverters.add(new ResourceHttpMessageConverter());
        partConverters.add(new UploadApplicationPayloadHttpMessageConverter());
        return partConverters;
    }

    private List> getHttpMessageConverters() {
        List> messageConverters = new ArrayList>();
        messageConverters.add(new ByteArrayHttpMessageConverter());
        messageConverters.add(new StringHttpMessageConverter());
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new UploadApplicationPayloadHttpMessageConverter());
        messageConverters.add(getFormHttpMessageConverter());
        messageConverters.add(new MappingJacksonHttpMessageConverter());
        messageConverters.add(new LoggregatorHttpMessageConverter());
        return messageConverters;
    }

    private void registerSslSocketFactory(HttpClient httpClient) {
            SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                    STRICT_HOSTNAME_VERIFIER);
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
        } catch (GeneralSecurityException gse) {
            throw new RuntimeException("An error occurred setting up the SSLSocketFactory", gse);
        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
 */
public class RestUtil {

    public OauthClient createOauthClient(URL authorizationUrl, HttpProxyConfiguration httpProxyConfiguration, boolean
            trustSelfSignedCerts) {
        return new OauthClient(authorizationUrl, createRestTemplate(httpProxyConfiguration, trustSelfSignedCerts));
    }

    public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean
            trustSelfSignedCerts) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();

        if (trustSelfSignedCerts) {
            httpClientBuilder.setSslcontext(buildSslContext());
            httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        }

        if (httpProxyConfiguration != null) {
            HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
            httpClientBuilder.setProxy(proxy);

            if (httpProxyConfiguration.isAuthRequired()) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(
                        new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()),
                        new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(), httpProxyConfiguration
                                .getPassword()));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            httpClientBuilder.setRoutePlanner(routePlanner);
        }

        HttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

        return requestFactory;
    }

    public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean
            trustSelfSignedCerts) {
        RestTemplate restTemplate = new LoggingRestTemplate();
        restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts));
        restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler());
        restTemplate.setMessageConverters(getHttpMessageConverters());

        return restTemplate;
    }

    private javax.net.ssl.SSLContext buildSslContext() {
        try {
            return new SSLContextBuilder().useSSL().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
        } catch (GeneralSecurityException gse) {
            throw new RuntimeException("An error occurred setting up the SSLContext", gse);
        }
    }

    private FormHttpMessageConverter getFormHttpMessageConverter() {
        FormHttpMessageConverter formPartsMessageConverter = new CloudFoundryFormHttpMessageConverter();
        formPartsMessageConverter.setPartConverters(getFormPartsMessageConverters());
        return formPartsMessageConverter;
    }

    private List> getFormPartsMessageConverters() {
        List> partConverters = new ArrayList>();
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setSupportedMediaTypes(Collections.singletonList(JsonUtil.JSON_MEDIA_TYPE));
        stringConverter.setWriteAcceptCharset(false);
        partConverters.add(stringConverter);
        partConverters.add(new ResourceHttpMessageConverter());
        partConverters.add(new UploadApplicationPayloadHttpMessageConverter());
        return partConverters;
    }

    private List> getHttpMessageConverters() {
        List> messageConverters = new ArrayList>();
        messageConverters.add(new ByteArrayHttpMessageConverter());
        messageConverters.add(new StringHttpMessageConverter());
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new UploadApplicationPayloadHttpMessageConverter());
        messageConverters.add(getFormHttpMessageConverter());
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new LoggregatorHttpMessageConverter());
        return messageConverters;
    }
}
File
RestUtil.java
Developer's decision
Combination
Kind of conflict
Method declaration
Chunk
Conflicting content
package org.cloudfoundry.client.lib;

<<<<<<< HEAD
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

=======
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
import org.apache.commons.io.IOUtils;
import org.cloudfoundry.client.lib.domain.ApplicationLog;
import org.cloudfoundry.client.lib.domain.ApplicationStats;
Solution content
package org.cloudfoundry.client.lib;

import org.apache.commons.io.IOUtils;
import org.cloudfoundry.client.lib.domain.ApplicationLog;
import org.cloudfoundry.client.lib.domain.ApplicationStats;
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Import
Chunk
Conflicting content
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
<<<<<<< HEAD
=======

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

/**
 * Note that this integration tests rely on other methods working correctly, so these tests aren't independent unit
Solution content
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;

/**
 * Note that this integration tests rely on other methods working correctly, so these tests aren't independent unit
File
CloudFoundryClientTest.java
Developer's decision
Manual
Kind of conflict
Import
Chunk
Conflicting content
@RunWith(BMUnitRunner.class)
@BMScript(value = "trace", dir = "target/test-classes")
public class CloudFoundryClientTest {
<<<<<<< HEAD
	private CloudFoundryOperations connectedClient;
=======
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    public static final int STARTUP_TIMEOUT = Integer.getInteger("ccng.startup.timeout", 60000);
Solution content
@RunWith(BMUnitRunner.class)
@BMScript(value = "trace", dir = "target/test-classes")
public class CloudFoundryClientTest {

    public static final int STARTUP_TIMEOUT = Integer.getInteger("ccng.startup.timeout", 60000);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Attribute
Chunk
Conflicting content
    private static final String CCNG_API_PROXY_HOST = System.getProperty("http.proxyHost", null);

<<<<<<< HEAD
	private static final int CCNG_API_PROXY_PORT = Integer.getInteger("http.proxyPort", 80);

	private static final String CCNG_API_PROXY_USER = System.getProperty("http.proxyUsername", null);
=======
    private static final String CCNG_API_PROXY_PASSWD = System.getProperty("http.proxyPassword", null);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    private static final int CCNG_API_PROXY_PORT = Integer.getInteger("http.proxyPort", 80);
Solution content
    private static final String CCNG_API_PROXY_HOST = System.getProperty("http.proxyHost", null);

    private static final String CCNG_API_PROXY_PASSWD = System.getProperty("http.proxyPassword", null);

    private static final int CCNG_API_PROXY_PORT = Integer.getInteger("http.proxyPort", 80);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Attribute
Method invocation
Chunk
Conflicting content
    private static final boolean SILENT_TEST_TIMINGS = Boolean.getBoolean("silent.testTimings");

<<<<<<< HEAD
	private static final int FIVE_MINUTES = 300 * 1000;

	private static final String CCNG_QUOTA_NAME_TEST = System.getProperty("ccng.quota", "test_quota");

	private static final String CCNG_SECURITY_GROUP_NAME_TEST = System.getProperty("ccng.securityGroup", "test_security_group");

	private static boolean tearDownComplete = false;
=======
    private static final boolean SKIP_INJVM_PROXY = Boolean.getBoolean("http.skipInJvmProxy");

    private static final String TEST_DOMAIN = System.getProperty("vcap.test.domain", defaultNamespace
            (CCNG_USER_EMAIL) + ".com");
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    private static final String TEST_NAMESPACE = System.getProperty("vcap.test.namespace", defaultNamespace
            (CCNG_USER_EMAIL));
Solution content
    private static final boolean SILENT_TEST_TIMINGS = Boolean.getBoolean("silent.testTimings");

    private static final boolean SKIP_INJVM_PROXY = Boolean.getBoolean("http.skipInJvmProxy");

    private static final String TEST_DOMAIN = System.getProperty("vcap.test.domain", defaultNamespace
            (CCNG_USER_EMAIL) + ".com");

    private static final String TEST_NAMESPACE = System.getProperty("vcap.test.namespace", defaultNamespace
            (CCNG_USER_EMAIL));
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Attribute
Method invocation
Chunk
Conflicting content
    @Rule
    public ExpectedException thrown = ExpectedException.none();

<<<<<<< HEAD
	@After
	public void tearDown() throws Exception {
		// Clean after ourselves so that there are no leftover apps, services, domains, and routes
		if (connectedClient != null) { //may happen if setUp() fails
			connectedClient.deleteAllApplications();
			connectedClient.deleteAllServices();
			clearTestDomainAndRoutes();
			deleteAnyOrphanedTestSecurityGroups();
		}
		tearDownComplete = true;
	}
=======
    @Rule
    public TestRule watcher = new TestWatcher() {
        private long startTime;
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        @Override
        protected void finished(Description description) {
Solution content
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Rule
    public TestRule watcher = new TestWatcher() {
        private long startTime;

        @Override
        protected void finished(Description description) {
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Attribute
Method declaration
Method invocation
Chunk
Conflicting content
		}
        }
    };

<<<<<<< HEAD
	/**
	 * Self tests that the assert mechanisms with jetty and byteman are properly working. If debugging is needed
	 * consider enabling one or more of the following system properties
	 * -Dorg.jboss.byteman.verbose=true
	 * -Dorg.jboss.byteman.debug=true
	 * -Dorg.jboss.byteman.rule.debug=true
	 * -Dorg.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog
	 * -Dorg.eclipse.jetty.LEVEL=INFO
	 * -Dorg.eclipse.jetty.server.LEVEL=INFO
	 * -Dorg.eclipse.jetty.server.handler.ConnectHandler=DEBUG
	 * Documentation on byteman at http://downloads.jboss.org/byteman/2.1.3/ProgrammersGuideSinglePage.2.1.3.1.html
	 */
	@Test
	public void checkByteManrulesAndInJvmProxyAssertMechanisms() {
		if (SKIP_INJVM_PROXY) {
			return; //inJvm Proxy test skipped.
		}
		assertTrue(SocketDestHelper.isSocketRestrictionFlagActive());

		RestUtil restUtil = new RestUtil();
		RestTemplate restTemplateNoProxy = restUtil.createRestTemplate(null, CCNG_API_SSL);

		// When called directly without a proxy, expect an exception to be thrown due to byteman rules
		assertNetworkCallFails(restTemplateNoProxy, new HttpComponentsClientHttpRequestFactory());
		// Repeat that with different request factory used in the code as this exercises different byteman rules
		assertNetworkCallFails(restTemplateNoProxy, new SimpleClientHttpRequestFactory());
		// And with the actual one used by RestUtil, without a proxy configured
		assertNetworkCallFails(restTemplateNoProxy, restUtil.createRequestFactory(null, CCNG_API_SSL));

		// Test with the in-JVM proxy configured
		HttpProxyConfiguration localProxy = new HttpProxyConfiguration("127.0.0.1", inJvmProxyPort);
		RestTemplate restTemplate = restUtil.createRestTemplate(localProxy, CCNG_API_SSL);

		restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, null);

		// then executes fine, and the jetty proxy indeed received one request
		assertEquals("expected network calls to make it through the inJvmProxy.", 1, nbInJvmProxyRcvReqs.get());
		nbInJvmProxyRcvReqs.set(0); //reset for next test

		assertTrue(SocketDestHelper.isActivated());
		assertFalse("expected some installed rules, got:" + SocketDestHelper.getInstalledRules(), SocketDestHelper.getInstalledRules().isEmpty());
   }

	private void assertNetworkCallFails(RestTemplate restTemplate, ClientHttpRequestFactory requestFactory) {
		restTemplate.setRequestFactory(requestFactory);
		try {
			HttpStatus status = restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, new ResponseExtractor() {
				public HttpStatus extractData(ClientHttpResponse response) throws IOException {
					return response.getStatusCode();
				}
			});
			Assert.fail("Expected byteman rules to detect direct socket connections, status is:" + status);
		} catch (Exception e) {
			//good, byteman rejected it as expected
			//e.printStackTrace();
		assertEquals("Not expecting Jetty to receive requests since we asked direct connections", 0, nbInJvmProxyRcvReqs.get());
	}
=======
    private CloudFoundryClient connectedClient;
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    @AfterClass
    public static void afterClass() throws Exception {
Solution content
        }
    };

    private CloudFoundryOperations connectedClient;

    @AfterClass
    public static void afterClass() throws Exception {
File
CloudFoundryClientTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Attribute
Comment
Method declaration
Chunk
Conflicting content
        assertNull(afterDelete);
    }

<<<<<<< HEAD
	//
	// Basic Event Tests
	//

	@Test
	public void eventsAvailable() throws Exception {
		List events = connectedClient.getEvents();
		assertEvents(events);
	}

	@Test
	public void appEventsAvailable() throws Exception {
		String appName = createSpringTravelApp("appEvents");
		List events = connectedClient.getApplicationEvents(appName);
		assertEvents(events);
		assertEventTimestamps(events);
	}

	private void assertEvents(List events) {
		assertNotNull(events);
		assertTrue(events.size() > 0);

		for (CloudEvent event : events) {
			assertNotNull(event.getActee());
			assertNotNull(event.getActeeType());
			assertNotNull(event.getActeeName());
			assertNotNull(event.getActor());
			assertNotNull(event.getActorType());
			assertNotNull(event.getActorName());
		}
	}

	private void assertEventTimestamps(List events) {
		for (CloudEvent event : events) {
			if (event.getTimestamp() != null) {
				assertTimeWithinRange("Event time should be very recent", event.getTimestamp().getTime(), FIVE_MINUTES);
			}
		}
	}

	//
	// Basic Application tests
	//

	@Test
	public void createApplication() {
		String appName = namespacedAppName("travel_test-0");
		List uris = Collections.singletonList(computeAppUrl(appName));
		Staging staging =  new Staging();
		connectedClient.createApplication(appName, staging, DEFAULT_MEMORY, uris, null);
		CloudApplication app = connectedClient.getApplication(appName);
		assertNotNull(app);
		assertEquals(appName, app.getName());

      	assertNotNull(app.getMeta().getGuid());

		final Calendar now = Calendar.getInstance();
		now.setTime(new Date());
		final Calendar createdDate = Calendar.getInstance();
		createdDate.setTime(app.getMeta().getCreated());

		assertEquals(now.get(Calendar.DATE), createdDate.get(Calendar.DATE));
	}
=======
    @Test
    public void accessRandomApplicationUrl() throws Exception {
        String appName = UUID.randomUUID().toString();
        CloudApplication app = createAndUploadAndStartSimpleSpringApp(appName);
        connectedClient.startApplication(appName);
        assertEquals(1, app.getInstances());
        for (int i = 0; i < 100 && app.getRunningInstances() < 1; i++) {
            Thread.sleep(1000);
            app = connectedClient.getApplication(appName);
        }
        assertEquals(1, app.getRunningInstances());
        RestUtil restUtil = new RestUtil();
        RestTemplate rest = restUtil.createRestTemplate(httpProxyConfiguration, false);
        String results = rest.getForObject("http://" + app.getUris().get(0), String.class);
        assertTrue(results.contains("Hello world!"));
    }

    @Test
    public void addAndDeleteDomain() {
        connectedClient.addDomain(TEST_DOMAIN);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        assertDomainInList(connectedClient.getPrivateDomains());
        assertDomainInList(connectedClient.getDomainsForOrg());
Solution content
        assertNull(afterDelete);
    }

    @Test
    public void accessRandomApplicationUrl() throws Exception {
        String appName = UUID.randomUUID().toString();
        CloudApplication app = createAndUploadAndStartSimpleSpringApp(appName);
        connectedClient.startApplication(appName);
        assertEquals(1, app.getInstances());
        for (int i = 0; i < 100 && app.getRunningInstances() < 1; i++) {
            Thread.sleep(1000);
            app = connectedClient.getApplication(appName);
        }
        assertEquals(1, app.getRunningInstances());
        RestUtil restUtil = new RestUtil();
        RestTemplate rest = restUtil.createRestTemplate(httpProxyConfiguration, false);
        String results = rest.getForObject("http://" + app.getUris().get(0), String.class);
        assertTrue(results.contains("Hello world!"));
    }

    @Test
    public void addAndDeleteDomain() {
        connectedClient.addDomain(TEST_DOMAIN);

        assertDomainInList(connectedClient.getPrivateDomains());
        assertDomainInList(connectedClient.getDomainsForOrg());
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Comment
Method declaration
Method invocation
Method signature
Chunk
Conflicting content
        assertDomainNotInList(connectedClient.getSharedDomains());

<<<<<<< HEAD
		assertEquals(buildpackUrl, app.getStaging().getBuildpackUrl());
		assertNull(app.getStaging().getDetectedBuildpack());
	}

	@Test
	public void createApplicationWithDetectedBuildpack() throws Exception {
		String appName = createSpringTravelApp("detectedBuildpack");

		File file = SampleProjects.springTravel();
		connectedClient.uploadApplication(appName, file.getCanonicalPath());
		connectedClient.startApplication(appName);

		ensureApplicationRunning(appName);

		CloudApplication app = connectedClient.getApplication(appName);
		Staging staging = app.getStaging();
		assertNotNull(staging.getDetectedBuildpack());
	}
=======
        connectedClient.deleteDomain(TEST_DOMAIN);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        assertDomainNotInList(connectedClient.getPrivateDomains());
        assertDomainNotInList(connectedClient.getDomainsForOrg());
Solution content
        assertDomainNotInList(connectedClient.getSharedDomains());

        connectedClient.deleteDomain(TEST_DOMAIN);

        assertDomainNotInList(connectedClient.getPrivateDomains());
        assertDomainNotInList(connectedClient.getDomainsForOrg());
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Method declaration
Method invocation
Chunk
Conflicting content
        connectedClient.bindService(appName, serviceName);

<<<<<<< HEAD
		connectedClient.addDomain(TEST_DOMAIN);
		List uris = Collections.singletonList(TEST_DOMAIN);
=======
        app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertEquals(1, app.getServices().size());
        assertEquals(serviceName, app.getServices().get(0));
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        connectedClient.unbindService(appName, serviceName);
Solution content
        connectedClient.bindService(appName, serviceName);

        app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertEquals(1, app.getServices().size());
        assertEquals(serviceName, app.getServices().get(0));

        connectedClient.unbindService(appName, serviceName);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Method invocation
Variable
Chunk
Conflicting content
        assertTrue(app.getServices().isEmpty());
    }

<<<<<<< HEAD
	@Test
	public void getApplicationByName() {
		final String serviceName = "test_database";
		String appName = createSpringTravelApp("1", Collections.singletonList(serviceName));
		CloudApplication app = connectedClient.getApplication(appName);
		assertNotNull(app);
		assertEquals(appName, app.getName());

		assertEquals(1, app.getServices().size());
		assertEquals(serviceName, app.getServices().get(0));
		assertEquals(CCNG_USER_SPACE, app.getSpace().getName());

		assertEquals(1, app.getInstances());
		assertEquals(DEFAULT_MEMORY, app.getMemory());
		assertEquals(DEFAULT_DISK, app.getDiskQuota());
		assertNull(app.getStaging().getCommand());
		assertNull(app.getStaging().getBuildpackUrl());
		assertNull(app.getStaging().getHealthCheckTimeout());
	}
=======
    //
    // Basic Application tests
    //

    /**
     * Self tests that the assert mechanisms with jetty and byteman are properly working. If debugging is needed
     * consider enabling one or more of the following system properties -Dorg.jboss.byteman.verbose=true
     * -Dorg.jboss.byteman.debug=true -Dorg.jboss.byteman.rule.debug=true -Dorg.eclipse.jetty.util.log.class=org
     * .eclipse.jetty.util.log.StdErrLog
     * -Dorg.eclipse.jetty.LEVEL=INFO -Dorg.eclipse.jetty.server.LEVEL=INFO -Dorg.eclipse.jetty.server.handler
     * .ConnectHandler=DEBUG
     * Documentation on byteman at http://downloads.jboss.org/byteman/2.1.3/ProgrammersGuideSinglePage.2.1.3.1.html
     */
    @Test
    public void checkByteManrulesAndInJvmProxyAssertMechanisms() {
        if (SKIP_INJVM_PROXY) {
            return; //inJvm Proxy test skipped.
        }
        assertTrue(SocketDestHelper.isSocketRestrictionFlagActive());

        RestTemplate restTemplate = new RestTemplate();

        // When called directly without a proxy, expect an exception to be thrown due to byteman rules
        assertNetworkCallFails(restTemplate, new HttpComponentsClientHttpRequestFactory());
        // Repeat that with different request factory used in the code as this exercises different byteman rules
        assertNetworkCallFails(restTemplate, new SimpleClientHttpRequestFactory());
        // And with the actual one used by RestUtil, without a proxy configured
        assertNetworkCallFails(restTemplate, new RestUtil().createRequestFactory(null, false));

        // Test with the in-JVM proxy configured
        HttpProxyConfiguration localProxy = new HttpProxyConfiguration("127.0.0.1", inJvmProxyPort);
        ClientHttpRequestFactory requestFactory = new RestUtil().createRequestFactory(localProxy, CCNG_API_SSL);

        restTemplate.setRequestFactory(requestFactory);
        restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, null);

        // then executes fine, and the jetty proxy indeed received one request
        assertEquals("expected network calls to make it through the inJvmProxy.", 1, nbInJvmProxyRcvReqs.get());
        nbInJvmProxyRcvReqs.set(0); //reset for next test

        assertTrue(SocketDestHelper.isActivated());
        assertFalse("expected some installed rules, got:" + SocketDestHelper.getInstalledRules(), SocketDestHelper
                .getInstalledRules().isEmpty());
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    @Test
    public void createAndReCreateApplication() {
Solution content
        assertTrue(app.getServices().isEmpty());
    }

    @Test
    public void bindingAndUnbindingSecurityGroupToDefaultRunningSet() throws FileNotFoundException {
        assumeTrue(CCNG_USER_IS_ADMIN);

        // Given
        assertFalse(containsSecurityGroupNamed(connectedClient.getRunningSecurityGroups(),
                CCNG_SECURITY_GROUP_NAME_TEST));
        connectedClient.createSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File
                ("src/test/resources/security-groups/test-rules-2.json")));

        // When
        connectedClient.bindRunningSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

        // Then
        assertTrue(containsSecurityGroupNamed(connectedClient.getRunningSecurityGroups(),
                CCNG_SECURITY_GROUP_NAME_TEST));

        // When
        connectedClient.unbindRunningSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

        // Then
        assertFalse(containsSecurityGroupNamed(connectedClient.getRunningSecurityGroups(),
                CCNG_SECURITY_GROUP_NAME_TEST));

        // Cleanup
        connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
    }

    @Test
    public void bindingAndUnbindingSecurityGroupToDefaultStagingSet() throws FileNotFoundException {
        assumeTrue(CCNG_USER_IS_ADMIN);

        // Given
        assertFalse(containsSecurityGroupNamed(connectedClient.getStagingSecurityGroups(),
                CCNG_SECURITY_GROUP_NAME_TEST));
        connectedClient.createSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File
                ("src/test/resources/security-groups/test-rules-2.json")));

        // When
        connectedClient.bindStagingSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

        // Then
        assertTrue(containsSecurityGroupNamed(connectedClient.getStagingSecurityGroups(),
                CCNG_SECURITY_GROUP_NAME_TEST));

        // When
        connectedClient.unbindStagingSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

        // Then
        assertFalse(containsSecurityGroupNamed(connectedClient.getStagingSecurityGroups(),
                CCNG_SECURITY_GROUP_NAME_TEST));

        // Cleanup
        connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
    }

    @Test
    public void bindingAndUnbindingSecurityGroupToSpaces() throws FileNotFoundException {
        assumeTrue(CCNG_USER_IS_ADMIN);

        // Given
        connectedClient.createSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File
                ("src/test/resources/security-groups/test-rules-2.json")));

        // When
        connectedClient.bindSecurityGroup(CCNG_USER_ORG, CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST);
        // Then
        assertTrue(isSpaceBoundToSecurityGroup(CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST));

        // When
        connectedClient.unbindSecurityGroup(CCNG_USER_ORG, CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST);
        //Then
        assertFalse(isSpaceBoundToSecurityGroup(CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST));

        // Cleanup
        connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
    }

    /**
     * Self tests that the assert mechanisms with jetty and byteman are properly working. If debugging is needed
     * consider enabling one or more of the following system properties -Dorg.jboss.byteman.verbose=true
     * -Dorg.jboss.byteman.debug=true -Dorg.jboss.byteman.rule.debug=true -Dorg.eclipse.jetty.util.log.class=org
     * .eclipse.jetty.util.log.StdErrLog -Dorg.eclipse.jetty.LEVEL=INFO -Dorg.eclipse.jetty.server.LEVEL=INFO
     * -Dorg.eclipse.jetty.server.handler .ConnectHandler=DEBUG Documentation on byteman at
     * http://downloads.jboss.org/byteman/2.1.3/ProgrammersGuideSinglePage.2.1.3.1.html
     */
    @Test
    public void checkByteManrulesAndInJvmProxyAssertMechanisms() {
        if (SKIP_INJVM_PROXY) {
            return; //inJvm Proxy test skipped.
        }
        assertTrue(SocketDestHelper.isSocketRestrictionFlagActive());

        RestUtil restUtil = new RestUtil();
        RestTemplate restTemplateNoProxy = restUtil.createRestTemplate(null, CCNG_API_SSL);

        // When called directly without a proxy, expect an exception to be thrown due to byteman rules
        assertNetworkCallFails(restTemplateNoProxy, new HttpComponentsClientHttpRequestFactory());
        // Repeat that with different request factory used in the code as this exercises different byteman rules
        assertNetworkCallFails(restTemplateNoProxy, new SimpleClientHttpRequestFactory());
        // And with the actual one used by RestUtil, without a proxy configured
        assertNetworkCallFails(restTemplateNoProxy, restUtil.createRequestFactory(null, CCNG_API_SSL));

        // Test with the in-JVM proxy configured
        HttpProxyConfiguration localProxy = new HttpProxyConfiguration("127.0.0.1", inJvmProxyPort);
        RestTemplate restTemplate = restUtil.createRestTemplate(localProxy, CCNG_API_SSL);

        restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, null);

        // then executes fine, and the jetty proxy indeed received one request
        assertEquals("expected network calls to make it through the inJvmProxy.", 1, nbInJvmProxyRcvReqs.get());
        nbInJvmProxyRcvReqs.set(0); //reset for next test

        assertTrue(SocketDestHelper.isActivated());
        assertFalse("expected some installed rules, got:" + SocketDestHelper.getInstalledRules(), SocketDestHelper
                .getInstalledRules().isEmpty());
    }

    @Test
    public void createAndReCreateApplication() {
File
CloudFoundryClientTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
Method declaration
Chunk
Conflicting content
        assertEquals(now.get(Calendar.DATE), createdDate.get(Calendar.DATE));
    }

<<<<<<< HEAD
	@Test
	public void getApplicationEnvironmentByGuid() {
		String appName = namespacedAppName("simple-app");
		List uris = Collections.singletonList(computeAppUrl(appName));
		Staging staging = new Staging();
		connectedClient.createApplication(appName, staging, DEFAULT_MEMORY, uris, null);
		connectedClient.updateApplicationEnv(appName, Collections.singletonMap("testKey", "testValue"));
		CloudApplication app = connectedClient.getApplication(appName);
		Map env = connectedClient.getApplicationEnvironment(app.getMeta().getGuid());
		assertAppEnvironment(env);
	}

	@Test
	public void getApplicationEnvironmentByName() {
		String appName = namespacedAppName("simple-app");
		List uris = Collections.singletonList(computeAppUrl(appName));
		Staging staging = new Staging();
		connectedClient.createApplication(appName, staging, DEFAULT_MEMORY, uris, null);
		connectedClient.updateApplicationEnv(appName, Collections.singletonMap("testKey", "testValue"));
		Map env = connectedClient.getApplicationEnvironment(appName);
		assertAppEnvironment(env);
   }

	private void assertAppEnvironment(Map env) {
		assertMapInEnv(env, "staging_env_json", true);
		assertMapInEnv(env, "running_env_json", true);
		assertMapInEnv(env, "environment_json", true, "testKey");
		assertMapInEnv(env, "system_env_json", true, "VCAP_SERVICES");
		// this value is not present in Pivotal CF < 1.4
		assertMapInEnv(env, "application_env_json", false, "VCAP_APPLICATION");
	}

	private void assertMapInEnv(Map env, String key, boolean alwaysPresent, String... expectedKeys) {
		Object value = env.get(key);

		if (value == null) {
			if (alwaysPresent) {
				fail("Expected key " + key + " was not found");
			} else {
				return;
			}
		}

		assertTrue(value.getClass().getName(), value instanceof Map);
		Map map = (Map) value;
		assertTrue(map.size() >= expectedKeys.length);

		for (String expectedKey : expectedKeys) {
			assertTrue(map.containsKey(expectedKey));
		}
	}

	@Test
	public void getApplications() {
		final String serviceName = "test_database";
		String appName = createSpringTravelApp("2", Collections.singletonList(serviceName));
		List apps = connectedClient.getApplications();
		assertEquals(1, apps.size());

		CloudApplication app = apps.get(0);
		assertEquals(appName, app.getName());
		assertNotNull(app.getMeta());
		assertNotNull(app.getMeta().getGuid());

		assertEquals(1, app.getServices().size());
		assertEquals(serviceName, app.getServices().get(0));

		createSpringTravelApp("3");
		apps = connectedClient.getApplications();
		assertEquals(2, apps.size());
	}
=======
    @Test
    public void createApplicationWithBuildPack() throws IOException {
        String buildpackUrl = "https://github.com/cloudfoundry/java-buildpack.git";
        String appName = namespacedAppName("buildpack");
        createSpringApplication(appName, buildpackUrl);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
Solution content
        assertEquals(now.get(Calendar.DATE), createdDate.get(Calendar.DATE));
    }

    @Test
    public void createApplicationWithBuildPack() throws IOException {
        String buildpackUrl = "https://github.com/cloudfoundry/java-buildpack.git";
        String appName = namespacedAppName("buildpack");
        createSpringApplication(appName, buildpackUrl);

        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
        connectedClient.addDomain(TEST_DOMAIN);
        List uris = Arrays.asList(TEST_DOMAIN);

<<<<<<< HEAD
	@Test
	public void setEnvironmentThroughList() throws IOException {
		String appName = createSpringTravelApp("env1");
		CloudApplication app = connectedClient.getApplication(appName);
		assertTrue(app.getEnv().isEmpty());

		connectedClient.updateApplicationEnv(appName, asList("foo=bar", "bar=baz"));
		app = connectedClient.getApplication(app.getName());
		assertEquals(arrayToHashSet("foo=bar", "bar=baz"), listToHashSet(app.getEnv()));

		connectedClient.updateApplicationEnv(appName, asList("foo=baz", "baz=bong"));
		app = connectedClient.getApplication(app.getName());
		assertEquals(arrayToHashSet("foo=baz", "baz=bong"), listToHashSet(app.getEnv()));

		connectedClient.updateApplicationEnv(appName, new ArrayList());
		app = connectedClient.getApplication(app.getName());
		assertTrue(app.getEnv().isEmpty());
	}
=======
        Staging staging = new Staging();
        connectedClient.createApplication(appName, staging, DEFAULT_MEMORY, uris, null);
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(appName, app.getName());
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        List actualUris = app.getUris();
        assertTrue(actualUris.size() == 1);
Solution content
        connectedClient.addDomain(TEST_DOMAIN);
        List uris = Collections.singletonList(TEST_DOMAIN);

        Staging staging = new Staging();
        connectedClient.createApplication(appName, staging, DEFAULT_MEMORY, uris, null);
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(appName, app.getName());

        List actualUris = app.getUris();
        assertTrue(actualUris.size() == 1);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Method declaration
Method invocation
Variable
Chunk
Conflicting content
        assertEquals(TEST_DOMAIN, actualUris.get(0));
    }

<<<<<<< HEAD
	@Test
	public void setEnvironmentThroughMap() throws IOException {
		String appName = createSpringTravelApp("env3");
		CloudApplication app = connectedClient.getApplication(appName);
		assertTrue(app.getEnv().isEmpty());
		Map env1 = new HashMap();
		env1.put("foo", "bar");
		env1.put("bar", "baz");
		connectedClient.updateApplicationEnv(appName, env1);
		app = connectedClient.getApplication(app.getName());
		assertEquals(env1, app.getEnvAsMap());
		assertEquals(arrayToHashSet("foo=bar", "bar=baz"), listToHashSet(app.getEnv()));

		Map env2 = new HashMap();
		env2.put("foo", "baz");
		env2.put("baz", "bong");
		connectedClient.updateApplicationEnv(appName, env2);
		app = connectedClient.getApplication(app.getName());

		// Test the unparsed list first
		assertEquals(arrayToHashSet("foo=baz", "baz=bong"), listToHashSet(app.getEnv()));

		assertEquals(env2, app.getEnvAsMap());

		connectedClient.updateApplicationEnv(appName, new HashMap());
		app = connectedClient.getApplication(app.getName());
		assertTrue(app.getEnv().isEmpty());
		assertTrue(app.getEnvAsMap().isEmpty());
	}

	@Test
	public void setEnvironmentThroughMapEqualsInValue() throws IOException {
		String appName = createSpringTravelApp("env4");
		CloudApplication app = connectedClient.getApplication(appName);
		assertTrue(app.getEnv().isEmpty());

		Map env1 = new HashMap();
		env1.put("key", "foo=bar,fu=baz");
		connectedClient.updateApplicationEnv(appName, env1);
		app = connectedClient.getApplication(app.getName());

		// Test the unparsed list first
		assertEquals(arrayToHashSet("key=foo=bar,fu=baz"), listToHashSet(app.getEnv()));

		assertEquals(env1, app.getEnvAsMap());

		connectedClient.updateApplicationEnv(appName, new HashMap());
		app = connectedClient.getApplication(app.getName());
		assertTrue(app.getEnv().isEmpty());
		assertTrue(app.getEnvAsMap().isEmpty());
	}

	private HashSet arrayToHashSet(String... array) {
		return listToHashSet(asList(array));
	}

	private HashSet listToHashSet(List list) {
		return new HashSet(list);
	}

	@Test
	public void updateApplicationDisk() throws IOException {
		String appName = createSpringTravelApp("updateDisk");
		connectedClient.updateApplicationDiskQuota(appName, 2048);
		CloudApplication app = connectedClient.getApplication(appName);
		assertEquals(2048, app.getDiskQuota());
	}
=======
    @Test
    public void createApplicationWithHealthCheckTimeout() throws IOException {
        String appName = namespacedAppName("health_check");
        createSpringApplication(appName, null, 2);

        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STOPPED, app.getState());
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        assertEquals(2, app.getStaging().getHealthCheckTimeout().intValue());
    }
Solution content
        assertEquals(TEST_DOMAIN, actualUris.get(0));
    }

    @Test
    public void createApplicationWithHealthCheckTimeout() throws IOException {
        String appName = namespacedAppName("health_check");
        createSpringApplication(appName, null, 2);

        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STOPPED, app.getState());

        assertEquals(2, app.getStaging().getHealthCheckTimeout().intValue());
    }
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
            assertTrue(instanceStats.getFdsQuota() > 0);
            assertTrue(instanceStats.getUptime() > 0);

<<<<<<< HEAD
	@Test
	public void uploadAppWithNonUnsubscribingCallback() throws IOException {
		String appName = namespacedAppName("upload-non-unsubscribing-callback");
		createSpringApplication(appName);
		File file = SampleProjects.springTravel();
		NonUnsubscribingUploadStatusCallback callback = new NonUnsubscribingUploadStatusCallback();
		connectedClient.uploadApplication(appName, file, callback);
		CloudApplication env = connectedClient.getApplication(appName);
		assertEquals(CloudApplication.AppState.STOPPED, env.getState());
		assertTrue(callback.progressCount >= 1); // must have taken at least 10 seconds
	}
=======
            InstanceStats.Usage usage = instanceStats.getUsage();
            assertNotNull(usage);
            assertTrue(usage.getDisk() > 0);
            assertTrue(usage.getMem() > 0);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

            assertTimeWithinRange("Usage time should be very recent", usage.getTime().getTime(), FIVE_MINUTES);
        }
Solution content
            assertTrue(instanceStats.getFdsQuota() > 0);
            assertTrue(instanceStats.getUptime() > 0);

            InstanceStats.Usage usage = instanceStats.getUsage();
            assertNotNull(usage);
            assertTrue(usage.getDisk() > 0);
            assertTrue(usage.getMem() > 0);

            assertTimeWithinRange("Usage time should be very recent", usage.getTime().getTime(), FIVE_MINUTES);
        }
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Method declaration
Method invocation
Variable
Chunk
Conflicting content
    }


<<<<<<< HEAD
		connectedClient.createApplication(appName, new Staging(),
              DEFAULT_MEMORY, uris, serviceNames);
		connectedClient.uploadApplication(appName, war.getCanonicalPath());
=======
    //
    // Advanced Application tests
    //
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    @Test
    public void getApplications() {
Solution content
    }

    @Test
    public void getApplications() {
File
CloudFoundryClientTest.java
Developer's decision
None
Kind of conflict
Comment
Method invocation
Chunk
Conflicting content
        }
    }

<<<<<<< HEAD
	@Test
	public void getLogs() throws Exception {
		String appName = namespacedAppName("simple_logs");
		createAndUploadAndStartSimpleSpringApp(appName);
		boolean pass = getInstanceInfosWithTimeout(appName, 1, true);
		assertTrue("Couldn't get the right application state", pass);

		Thread.sleep(10000); // let's have some time to get some logs generated
		Map logs = connectedClient.getLogs(appName);
		assertNotNull(logs);
		assertTrue(logs.size() > 0);
	}

	@Test
	public void streamLogs() throws Exception {
		// disable proxy validation for this test, since Loggregator websockets
		// connectivity does not currently support proxies
		new SocketDestHelper().setAllowedOnCurrentThread();

		String appName = namespacedAppName("simple_logs");
		CloudApplication app = createAndUploadAndStartSimpleSpringApp(appName);
		boolean pass = getInstanceInfosWithTimeout(appName, 1, true);
		assertTrue("Couldn't get the right application state", pass);

		List logs = doGetRecentLogs(appName);

		for (int index = 0; index < logs.size() - 1; index++) {
			int comparison = logs.get(index).getTimestamp().compareTo(logs.get(index + 1).getTimestamp());
			assertTrue("Logs are not properly sorted", comparison <= 0);
		}

		AccumulatingApplicationLogListener testListener = new AccumulatingApplicationLogListener();
		connectedClient.streamLogs(appName, testListener);
		String appUri = "http://" + app.getUris().get(0);
		RestTemplate appTemplate = new RestTemplate();
		int attempt = 0;
		do {
			// no need to sleep, visiting the app uri should be sufficient
			try {
				appTemplate.getForObject(appUri, String.class);
			} catch (HttpClientErrorException ex) {
				// ignore
			}
			if (testListener.logs.size() > 0) {
				break;
			}
			Thread.sleep(1000);
		} while (attempt++ < 30);
		assertTrue("Failed to stream normal log", testListener.logs.size() > 0);
	}
=======
    @Test
    public void getCreateDeleteService() throws MalformedURLException {
        String serviceName = "mysql-test";
        createMySqlService(serviceName);

        CloudService service = connectedClient.getService(serviceName);
        assertNotNull(service);
        assertEquals(serviceName, service.getName());
        assertTimeWithinRange("Creation time should be very recent",
                service.getMeta().getCreated().getTime(), FIVE_MINUTES);

        connectedClient.deleteService(serviceName);
        List services = connectedClient.getServices();
        assertNotNull(services);
        assertEquals(0, services.size());
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    @Test
    public void getDomains() {
Solution content
        }
    }

    @Test
    public void getCreateDeleteService() throws MalformedURLException {
        String serviceName = "mysql-test";
        createMySqlService(serviceName);

        CloudService service = connectedClient.getService(serviceName);
        assertNotNull(service);
        assertEquals(serviceName, service.getName());
        assertTimeWithinRange("Creation time should be very recent",
                service.getMeta().getCreated().getTime(), FIVE_MINUTES);

        connectedClient.deleteService(serviceName);

        List services = connectedClient.getServices();
        assertNotNull(services);
        assertEquals(0, services.size());
    }

    @Test
    public void getCurrentOrganizationUsersAndEnsureCurrentUserIsAMember() {
        String orgName = CCNG_USER_ORG;
        Map orgUsers = connectedClient.getOrganizationUsers(orgName);
        assertNotNull(orgUsers);
        assertTrue("Org " + orgName + " should at least contain 1 user", orgUsers.size() > 0);
        String username = CCNG_USER_EMAIL;
        assertTrue("Organization user list should contain current user", orgUsers.containsKey(username));
    }

    @Test
    public void getDomains() {
File
CloudFoundryClientTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
        assertTrue(log1.size() > log2.size());
    }

<<<<<<< HEAD
	@Test
	public void getCreateDeleteService() throws MalformedURLException {
		String serviceName = "mysql-test";
		createMySqlService(serviceName);

		CloudService service = connectedClient.getService(serviceName);
		assertNotNull(service);
		assertEquals(serviceName, service.getName());
		assertTimeWithinRange("Creation time should be very recent",
              service.getMeta().getCreated().getTime(), FIVE_MINUTES);

		connectedClient.deleteService(serviceName);

		List services = connectedClient.getServices();
		assertNotNull(services);
		assertEquals(0, services.size());
	}
=======
    @Test
    public void getService() {
        String serviceName = "mysql-test";
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        CloudService expectedService = createMySqlService(serviceName);
        CloudService service = connectedClient.getService(serviceName);
Solution content
        assertTrue(log1.size() > log2.size());
    }

    @Test
    public void getService() {
        String serviceName = "mysql-test";

        CloudService expectedService = createMySqlService(serviceName);
        CloudService service = connectedClient.getService(serviceName);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Method declaration
Method signature
Variable
Chunk
Conflicting content
        assertEquals("warreng", broker.getUsername());
        assertNull(broker.getPassword());

<<<<<<< HEAD
	@Test
	public void getServiceInstance() {
		String serviceName = "mysql-instance-test";
		String appName = createSpringTravelApp("service-instance-app", Collections.singletonList(serviceName));

		CloudApplication application = connectedClient.getApplication(appName);

		CloudServiceInstance serviceInstance = connectedClient.getServiceInstance(serviceName);
		assertNotNull(serviceInstance);
		assertEquals(serviceName, serviceInstance.getName());
		assertNotNull(serviceInstance.getDashboardUrl());
		assertNotNull(serviceInstance.getType());
		assertNotNull(serviceInstance.getCredentials());

		CloudService service = serviceInstance.getService();
		assertNotNull(service);
		assertEquals(MYSQL_SERVICE_LABEL, service.getLabel());
		assertEquals(MYSQL_SERVICE_PLAN, service.getPlan());

		CloudServicePlan servicePlan = serviceInstance.getServicePlan();
		assertNotNull(servicePlan);
		assertEquals(MYSQL_SERVICE_PLAN, servicePlan.getName());

		List bindings = serviceInstance.getBindings();
		assertNotNull(bindings);
		assertEquals(1, bindings.size());
		CloudServiceBinding binding = bindings.get(0);
		assertEquals(application.getMeta().getGuid(), binding.getAppGuid());
		assertNotNull(binding.getCredentials());
		assertTrue(binding.getCredentials().size() > 0);
		assertNotNull(binding.getBindingOptions());
		assertEquals(0, binding.getBindingOptions().size());
		assertNull(binding.getSyslogDrainUrl());
	}

	//
	// Application and Services tests
	//
=======
        newBroker = new CloudServiceBroker(CloudEntity.Meta.defaultMeta(), "haash-broker", "http://haash-broker.cf" +
                ".deepsouthcloud.com", "warreng", "snoopdogg");
        connectedClient.updateServiceBroker(newBroker);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        connectedClient.updateServicePlanVisibilityForBroker("haash-broker", true);
        connectedClient.updateServicePlanVisibilityForBroker("haash-broker", false);
Solution content
        assertEquals("warreng", broker.getUsername());
        assertNull(broker.getPassword());

        newBroker = new CloudServiceBroker(CloudEntity.Meta.defaultMeta(), "haash-broker", "http://haash-broker.cf" +
                ".deepsouthcloud.com", "warreng", "snoopdogg");
        connectedClient.updateServiceBroker(newBroker);

        connectedClient.updateServicePlanVisibilityForBroker("haash-broker", true);
        connectedClient.updateServicePlanVisibilityForBroker("haash-broker", false);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Comment
Method declaration
Method invocation
Variable
Chunk
Conflicting content
		}
        connectedClient.deleteQuota(CCNG_QUOTA_NAME_TEST);
    }

<<<<<<< HEAD
	@Test
	public void createGetAndDeleteSpaceOnCurrentOrg() throws Exception {
		String spaceName = "dummy space";
		CloudSpace newSpace = connectedClient.getSpace(spaceName);
		assertNull("Space '" + spaceName + "' should not exist before creation", newSpace);
		connectedClient.createSpace(spaceName);
		newSpace = connectedClient.getSpace(spaceName);
		assertNotNull("newSpace should not be null", newSpace);
		assertEquals(spaceName, newSpace.getName());
		boolean foundSpaceInCurrentOrg = false;
		for (CloudSpace aSpace : connectedClient.getSpaces()) {
			if (spaceName.equals(aSpace.getName())){
				foundSpaceInCurrentOrg = true;
			}
		assertTrue(foundSpaceInCurrentOrg);
		connectedClient.deleteSpace(spaceName);
		CloudSpace deletedSpace = connectedClient.getSpace(spaceName);
		assertNull("Space '" + spaceName + "' should not exist after deletion", deletedSpace);

	}

	@Test
	public void getCurrentOrganizationUsersAndEnsureCurrentUserIsAMember(){
		String orgName = CCNG_USER_ORG;
		Map orgUsers=connectedClient.getOrganizationUsers(orgName);
		assertNotNull(orgUsers);
		assertTrue("Org " + orgName + " should at least contain 1 user", orgUsers.size() > 0);
		String username=CCNG_USER_EMAIL;
		assertTrue("Organization user list should contain current user",orgUsers.containsKey(username));
	}

	@Test
	public void assignDefaultUserRolesInSpace() {
		String spaceName = "assignDefaultUserRolesInSpace";
		connectedClient.createSpace(spaceName);

		List spaceManagers = connectedClient.getSpaceManagers(spaceName);
		assertEquals("Space should have no manager when created", 0, spaceManagers.size());
		connectedClient.associateManagerWithSpace(spaceName);
		spaceManagers = connectedClient.getSpaceManagers(spaceName);
		assertEquals("Space should have one manager", 1, spaceManagers.size());

		List spaceDevelopers = connectedClient.getSpaceDevelopers(spaceName);
		assertEquals("Space should have no developer when created", 0, spaceDevelopers.size());
		connectedClient.associateDeveloperWithSpace(spaceName);
		spaceDevelopers = connectedClient.getSpaceDevelopers(spaceName);
		assertEquals("Space should have one developer", 1, spaceDevelopers.size());

		List spaceAuditors = connectedClient.getSpaceAuditors(spaceName);
		assertEquals("Space should have no auditor when created", 0, spaceAuditors.size());
		connectedClient.associateAuditorWithSpace(spaceName);
		spaceAuditors = connectedClient.getSpaceAuditors(spaceName);
		assertEquals("Space should have one auditor ", 1, spaceAuditors.size());

		connectedClient.deleteSpace(spaceName);
		CloudSpace deletedSpace = connectedClient.getSpace(spaceName);
		assertNull("Space '" + spaceName + "' should not exist after deletion", deletedSpace);
	}

	@Test
	public void assignAllUserRolesInSpaceWithOrgToCurrentUser() {
		String orgName = CCNG_USER_ORG;
		String spaceName = "assignAllUserRolesInSpaceWithOrgToCurrentUser";
		connectedClient.createSpace(spaceName);

		Map orgUsers = connectedClient.getOrganizationUsers(orgName);
		String username=CCNG_USER_EMAIL;
		CloudUser user = orgUsers.get(username);
		assertNotNull("Retrieved user should not be null",user);
		String userGuid = user.getMeta().getGuid().toString();

		List spaceManagers = connectedClient.getSpaceManagers(orgName, spaceName);
		assertEquals("Space should have no manager when created", 0, spaceManagers.size());
		connectedClient.associateManagerWithSpace(orgName, spaceName, userGuid);
		spaceManagers = connectedClient.getSpaceManagers(orgName, spaceName);
		assertEquals("Space should have one manager", 1, spaceManagers.size());

		List spaceDevelopers = connectedClient.getSpaceDevelopers(orgName, spaceName);
		assertEquals("Space should have no developer when created", 0, spaceDevelopers.size());
		connectedClient.associateDeveloperWithSpace(orgName, spaceName, userGuid);
		spaceDevelopers = connectedClient.getSpaceDevelopers(orgName, spaceName);
		assertEquals("Space should have one developer", 1, spaceDevelopers.size());

		List spaceAuditors = connectedClient.getSpaceAuditors(orgName, spaceName);
		assertEquals("Space should have no auditor when created", 0, spaceAuditors.size());
		connectedClient.associateAuditorWithSpace(orgName, spaceName, userGuid);
		spaceAuditors = connectedClient.getSpaceAuditors(orgName, spaceName);
		assertEquals("Space should have one auditor ", 1, spaceAuditors.size());

		connectedClient.deleteSpace(spaceName);
		CloudSpace deletedSpace = connectedClient.getSpace(spaceName);
		assertNull("Space '" + spaceName + "' should not exist after deletion", deletedSpace);
	}
=======
    @Before
    public void setUp() throws Exception {
        URL cloudControllerUrl;

        cloudControllerUrl = new URL(CCNG_API_URL);
        connectedClient = new CloudFoundryClient(new CloudCredentials(CCNG_USER_EMAIL, CCNG_USER_PASS),
                cloudControllerUrl, CCNG_USER_ORG, CCNG_USER_SPACE, httpProxyConfiguration, CCNG_API_SSL);
        connectedClient.login();
        defaultDomainName = connectedClient.getDefaultDomain().getName();

        // Optimization to avoid redoing the work already done is tearDown()
        if (!tearDownComplete) {
            tearDown();
        }
        tearDownComplete = false;
        connectedClient.addDomain(TEST_DOMAIN);

        // connectedClient.registerRestLogListener(new RestLogger("CF_REST"));
        if (nbInJvmProxyRcvReqs != null) {
            nbInJvmProxyRcvReqs.set(0); //reset calls made in setup to leave a clean state for tests to assert
        }

        if (!SKIP_INJVM_PROXY) {
            new SocketDestHelper().setForbiddenOnCurrentThread();
        }
    }

	/*@Test
    public void getServiceBroker() {
		assumeTrue(CCNG_USER_IS_ADMIN);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

		CloudServiceBroker broker = connectedClient.getServiceBroker("haash-broker");
		assertNotNull(broker);
Solution content
        connectedClient.deleteQuota(CCNG_QUOTA_NAME_TEST);
    }

    @Before
    public void setUp() throws Exception {
        URL cloudControllerUrl;

        cloudControllerUrl = new URL(CCNG_API_URL);
        connectedClient = new CloudFoundryClient(new CloudCredentials(CCNG_USER_EMAIL, CCNG_USER_PASS),
                cloudControllerUrl, CCNG_USER_ORG, CCNG_USER_SPACE, httpProxyConfiguration, CCNG_API_SSL);
        connectedClient.login();
        defaultDomainName = connectedClient.getDefaultDomain().getName();

        // Optimization to avoid redoing the work already done is tearDown()
        if (!tearDownComplete) {
            tearDown();
        }
        tearDownComplete = false;
        connectedClient.addDomain(TEST_DOMAIN);

        // connectedClient.registerRestLogListener(new RestLogger("CF_REST"));
        if (nbInJvmProxyRcvReqs != null) {
            nbInJvmProxyRcvReqs.set(0); //reset calls made in setup to leave a clean state for tests to assert
        }

        if (!SKIP_INJVM_PROXY) {
            new SocketDestHelper().setForbiddenOnCurrentThread();
        }
    }

    //
    // Application and Services tests
    //

    @Test
    public void spacesAvailable() throws Exception {
        List spaces = connectedClient.getSpaces();
        assertNotNull(spaces);
        assertTrue(spaces.size() > 0);
    }

    @Test
    public void startExplodedApplication() throws IOException {
        String appName = namespacedAppName("exploded_app");
        createAndUploadExplodedSpringTestApp(appName);
        connectedClient.startApplication(appName);
        CloudApplication app = connectedClient.getApplication(appName);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());
    }

    @Test
    public void startStopApplication() throws IOException {
        String appName = createSpringTravelApp("upload-start-stop");
        CloudApplication app = uploadSpringTravelApp(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STOPPED, app.getState());

        String url = computeAppUrlNoProtocol(appName);
        assertEquals(url, app.getUris().get(0));

        StartingInfo info = connectedClient.startApplication(appName);
        app = connectedClient.getApplication(appName);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());
        assertNotNull(info);
        assertNotNull(info.getStagingFile());

        connectedClient.stopApplication(appName);
        app = connectedClient.getApplication(appName);
        assertEquals(CloudApplication.AppState.STOPPED, app.getState());
    }

    @Test
    public void streamLogs() throws Exception {
        // disable proxy validation for this test, since Loggregator websockets
        // connectivity does not currently support proxies
        new SocketDestHelper().setAllowedOnCurrentThread();

        String appName = namespacedAppName("simple_logs");
        CloudApplication app = createAndUploadAndStartSimpleSpringApp(appName);
        boolean pass = getInstanceInfosWithTimeout(appName, 1, true);
        assertTrue("Couldn't get the right application state", pass);

        List logs = doGetRecentLogs(appName);

        for (int index = 0; index < logs.size() - 1; index++) {
            int comparison = logs.get(index).getTimestamp().compareTo(logs.get(index + 1).getTimestamp());
            assertTrue("Logs are not properly sorted", comparison <= 0);
        }

        AccumulatingApplicationLogListener testListener = new AccumulatingApplicationLogListener();
        connectedClient.streamLogs(appName, testListener);
        String appUri = "http://" + app.getUris().get(0);
        RestTemplate appTemplate = new RestTemplate();
        int attempt = 0;
        do {
            // no need to sleep, visiting the app uri should be sufficient
            try {
                appTemplate.getForObject(appUri, String.class);
            } catch (HttpClientErrorException ex) {
                // ignore
            }
            if (testListener.logs.size() > 0) {
                break;
            }
            Thread.sleep(1000);
        } while (attempt++ < 30);
        assertTrue("Failed to stream normal log", testListener.logs.size() > 0);
    }

    @After
    public void tearDown() throws Exception {
        // Clean after ourselves so that there are no leftover apps, services, domains, and routes
        if (connectedClient != null) { //may happen if setUp() fails
            connectedClient.deleteAllApplications();
            connectedClient.deleteAllServices();
            clearTestDomainAndRoutes();
            deleteAnyOrphanedTestSecurityGroups();
        }
        tearDownComplete = true;
    }

    @Test
    public void updateApplicationDisk() throws IOException {
        String appName = createSpringTravelApp("updateDisk");
        connectedClient.updateApplicationDiskQuota(appName, 2048);
        CloudApplication app = connectedClient.getApplication(appName);
        assertEquals(2048, app.getDiskQuota());
    }

    @Test
    public void updateApplicationInstances() throws Exception {
        String appName = createSpringTravelApp("updateInstances");
        CloudApplication app = connectedClient.getApplication(appName);

        assertEquals(1, app.getInstances());

        connectedClient.updateApplicationInstances(appName, 3);
        app = connectedClient.getApplication(appName);
        assertEquals(3, app.getInstances());

        connectedClient.updateApplicationInstances(appName, 1);
        app = connectedClient.getApplication(appName);
        assertEquals(1, app.getInstances());
    }

    @Test
    public void updateApplicationMemory() throws IOException {
        String appName = createSpringTravelApp("updateMemory");
        connectedClient.updateApplicationMemory(appName, 256);
        CloudApplication app = connectedClient.getApplication(appName);
        assertEquals(256, app.getMemory());
    }

    @Test
    public void updateApplicationService() throws IOException {
        String serviceName = "test_database";
        createMySqlService(serviceName);
        String appName = createSpringTravelApp("7");

        connectedClient.updateApplicationServices(appName, Collections.singletonList(serviceName));
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertTrue(app.getServices().size() > 0);
        assertEquals(serviceName, app.getServices().get(0));

        List emptyList = Collections.emptyList();
        connectedClient.updateApplicationServices(appName, emptyList);
        app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertEquals(emptyList, app.getServices());
    }

    @Test
    public void updateApplicationUris() throws IOException {
        String appName = namespacedAppName("updateUris");
        CloudApplication app = createAndUploadAndStartSimpleSpringApp(appName);

        List originalUris = app.getUris();
        assertEquals(Collections.singletonList(computeAppUrlNoProtocol(appName)), originalUris);

        List uris = new ArrayList(app.getUris());
        uris.add(computeAppUrlNoProtocol(namespacedAppName("url2")));
        connectedClient.updateApplicationUris(appName, uris);
        app = connectedClient.getApplication(appName);
        List newUris = app.getUris();
        assertNotNull(newUris);
        assertEquals(uris.size(), newUris.size());
        for (String uri : uris) {
            assertTrue(newUris.contains(uri));
        }
        connectedClient.updateApplicationUris(appName, originalUris);
        app = connectedClient.getApplication(appName);
        assertEquals(originalUris, app.getUris());
    }

    @Test
    public void updatePassword() throws MalformedURLException {
        // Not working currently
        assumeTrue(false);

        String newPassword = "newPass123";
        connectedClient.updatePassword(newPassword);
        CloudFoundryClient clientWithChangedPassword =
                new CloudFoundryClient(new CloudCredentials(CCNG_USER_EMAIL, newPassword), new URL(CCNG_API_URL),
                        httpProxyConfiguration);
        clientWithChangedPassword.login();

        // Revert
        connectedClient.updatePassword(CCNG_USER_PASS);
        connectedClient.login();
    }

    @Test
    public void updateStandaloneApplicationCommand() throws IOException {
        String appName = namespacedAppName("standalone-ruby");
        List uris = new ArrayList();
        List services = new ArrayList();
        createStandaloneRubyTestApp(appName, uris, services);
        connectedClient.startApplication(appName);
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());
        assertEquals(uris, app.getUris());
        assertEquals("ruby simple.rb", app.getStaging().getCommand());
        connectedClient.stopApplication(appName);

        Staging newStaging = new Staging("ruby simple.rb test", "https://github" +
                ".com/cloudfoundry/heroku-buildpack-ruby");
        connectedClient.updateApplicationStaging(appName, newStaging);
        app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(uris, app.getUris());
        assertEquals("ruby simple.rb test", app.getStaging().getCommand());
        assertEquals("https://github.com/cloudfoundry/heroku-buildpack-ruby", app.getStaging().getBuildpackUrl());
    }

    @Test
    public void uploadAppFromInputStream() throws IOException {
        String appName = namespacedAppName("upload-from-input-stream");
        createSpringApplication(appName);
        File file = SampleProjects.springTravel();
        FileInputStream inputStream = new FileInputStream(file);
        connectedClient.uploadApplication(appName, appName, inputStream);
        connectedClient.startApplication(appName);
        CloudApplication env = connectedClient.getApplication(appName);
        assertEquals(CloudApplication.AppState.STARTED, env.getState());
    }

    @Test
    public void uploadAppWithNonAsciiFileName() throws IOException {
        String appName = namespacedAppName("non-ascii");
        List uris = new ArrayList();
        uris.add(computeAppUrl(appName));

        File war = SampleProjects.nonAsciFileName();
        List serviceNames = new ArrayList();

        connectedClient.createApplication(appName, new Staging(),
                DEFAULT_MEMORY, uris, serviceNames);
        connectedClient.uploadApplication(appName, war.getCanonicalPath());

        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STOPPED, app.getState());

        connectedClient.startApplication(appName);

        app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());

        connectedClient.deleteApplication(appName);
    }

    @Test
    public void uploadAppWithNonUnsubscribingCallback() throws IOException {
        String appName = namespacedAppName("upload-non-unsubscribing-callback");
        createSpringApplication(appName);
        File file = SampleProjects.springTravel();
        NonUnsubscribingUploadStatusCallback callback = new NonUnsubscribingUploadStatusCallback();
        connectedClient.uploadApplication(appName, file, callback);
        CloudApplication env = connectedClient.getApplication(appName);
        assertEquals(CloudApplication.AppState.STOPPED, env.getState());
        assertTrue(callback.progressCount >= 1); // must have taken at least 10 seconds
    }

    @Test
    public void uploadAppWithUnsubscribingCallback() throws IOException {
        String appName = namespacedAppName("upload-unsubscribing-callback");
        createSpringApplication(appName);
        File file = SampleProjects.springTravel();
        UnsubscribingUploadStatusCallback callback = new UnsubscribingUploadStatusCallback();
        connectedClient.uploadApplication(appName, file, callback);
        CloudApplication env = connectedClient.getApplication(appName);
        assertEquals(CloudApplication.AppState.STOPPED, env.getState());
        assertTrue(callback.progressCount == 1);
    }

    //
    // Configuration/Metadata tests
    //

    @Test
    public void uploadSinatraApp() throws IOException {
        String appName = namespacedAppName("env");
        ClassPathResource cpr = new ClassPathResource("apps/env/");
        File explodedDir = cpr.getFile();
        Staging staging = new Staging();
        createAndUploadExplodedTestApp(appName, explodedDir, staging);
        connectedClient.startApplication(appName);
        CloudApplication env = connectedClient.getApplication(appName);
        assertEquals(CloudApplication.AppState.STARTED, env.getState());
    }

    @Test
    public void uploadStandaloneApplication() throws IOException {
        String appName = namespacedAppName("standalone-ruby");
        List uris = new ArrayList();
        List services = new ArrayList();
        createStandaloneRubyTestApp(appName, uris, services);
        connectedClient.startApplication(appName);
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());
        assertEquals(uris, app.getUris());
    }

    @Test
    public void uploadStandaloneApplicationWithURLs() throws IOException {
        String appName = namespacedAppName("standalone-node");
        List uris = new ArrayList();
        uris.add(computeAppUrl(appName));
        List services = new ArrayList();
        Staging staging = new Staging("node app.js", null);
        File file = SampleProjects.standaloneNode();
        connectedClient.createApplication(appName, staging, 64, uris, services);
        connectedClient.uploadApplication(appName, file.getCanonicalPath());
        connectedClient.startApplication(appName);
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());
        assertEquals(Collections.singletonList(computeAppUrlNoProtocol(appName)), app.getUris());
    }

    private HashSet arrayToHashSet(String... array) {
        return listToHashSet(asList(array));
    }

    private void assertAppEnvironment(Map env) {
        assertMapInEnv(env, "staging_env_json", true);
        assertMapInEnv(env, "running_env_json", true);
        assertMapInEnv(env, "environment_json", true, "testKey");
        assertMapInEnv(env, "system_env_json", true, "VCAP_SERVICES");
        // this value is not present in Pivotal CF < 1.4
        assertMapInEnv(env, "application_env_json", false, "VCAP_APPLICATION");
    }

    private void assertDomainInList(List domains) {
        assertTrue(domains.size() >= 1);
        assertNotNull(getDomainNamed(TEST_DOMAIN, domains));
    }

    private void assertDomainNotInList(List domains) {
        assertNull(getDomainNamed(TEST_DOMAIN, domains));
    }

    private void assertEventTimestamps(List events) {
        for (CloudEvent event : events) {
            if (event.getTimestamp() != null) {
                assertTimeWithinRange("Event time should be very recent", event.getTimestamp().getTime(), FIVE_MINUTES);
            }
        }

    }

    private void assertEvents(List events) {
        assertNotNull(events);
        assertTrue(events.size() > 0);

        for (CloudEvent event : events) {
            assertNotNull(event.getActee());
            assertNotNull(event.getActeeType());
            assertNotNull(event.getActeeName());
            assertNotNull(event.getActor());
            assertNotNull(event.getActorType());
            assertNotNull(event.getActorName());
        }
    }

    private void assertMapInEnv(Map env, String key, boolean alwaysPresent, String... expectedKeys) {
        Object value = env.get(key);

        if (value == null) {
            if (alwaysPresent) {
                fail("Expected key " + key + " was not found");
            } else {
                return;
            }
        }

        assertTrue(value.getClass().getName(), value instanceof Map);
        Map map = (Map) value;
        assertTrue(map.size() >= expectedKeys.length);

        for (String expectedKey : expectedKeys) {
            assertTrue(map.containsKey(expectedKey));
        }
    }

    private void assertNetworkCallFails(RestTemplate restTemplate, ClientHttpRequestFactory requestFactory) {
        restTemplate.setRequestFactory(requestFactory);
        try {
            HttpStatus status = restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, new
                    ResponseExtractor() {
                        public HttpStatus extractData(ClientHttpResponse response) throws IOException {
                            return response.getStatusCode();
                        }
                    });
            Assert.fail("Expected byteman rules to detect direct socket connections, status is:" + status);
        } catch (Exception e) {
            //good, byteman rejected it as expected
            //e.printStackTrace();
        }
        assertEquals("Not expecting Jetty to receive requests since we asked direct connections", 0,
                nbInJvmProxyRcvReqs.get());
    }

    private void assertRulesMatchTestData(CloudSecurityGroup securityGroup) {
        // This asserts against the test data defined in the crudSecurityGroups method
        // Rule ordering is preserved so we can depend on it here
        SecurityGroupRule rule = securityGroup.getRules().get(0);
        assertThat(rule.getProtocol(), is("tcp"));
        assertThat(rule.getPorts(), is("80, 443"));
        assertThat(rule.getDestination(), is("205.158.11.29"));
        assertNull(rule.getLog());
        assertNull(rule.getType());
        assertNull(rule.getCode());

        rule = securityGroup.getRules().get(1);
        assertThat(rule.getProtocol(), is("all"));
        assertNull(rule.getPorts());
        assertThat(rule.getDestination(), is("0.0.0.0-255.255.255.255"));
        assertNull(rule.getLog());
        assertNull(rule.getType());
        assertNull(rule.getCode());

        rule = securityGroup.getRules().get(2);
        assertThat(rule.getProtocol(), is("icmp"));
        assertNull(rule.getPorts());
        assertThat(rule.getDestination(), is("0.0.0.0/0"));
        assertTrue(rule.getLog());
        assertThat(rule.getType(), is(0));
        assertThat(rule.getCode(), is(1));
    }

    private void assertRulesMatchThoseInJsonFile1(CloudSecurityGroup securityGroup) {
        // Rule ordering is preserved so we can depend on it here

        SecurityGroupRule rule = securityGroup.getRules().get(0);
        assertThat(rule.getProtocol(), is("icmp"));
        assertNull(rule.getPorts());
        assertThat(rule.getDestination(), is("0.0.0.0/0"));
        assertNull(rule.getLog());
        assertThat(rule.getType(), is(0));
        assertThat(rule.getCode(), is(1));
        rule = securityGroup.getRules().get(1);
        assertThat(rule.getProtocol(), is("tcp"));
        assertThat(rule.getPorts(), is("2048-3000"));
        assertThat(rule.getDestination(), is("1.0.0.0/0"));
        assertTrue(rule.getLog());
        assertNull(rule.getType());
        assertNull(rule.getCode());

        rule = securityGroup.getRules().get(2);
        assertThat(rule.getProtocol(), is("udp"));
        assertThat(rule.getPorts(), is("53, 5353"));
        assertThat(rule.getDestination(), is("2.0.0.0/0"));
        assertNull(rule.getLog());
        assertNull(rule.getType());
        assertNull(rule.getCode());

        rule = securityGroup.getRules().get(3);
        assertThat(rule.getProtocol(), is("all"));
        assertNull(rule.getPorts());
        assertThat(rule.getDestination(), is("3.0.0.0/0"));
        assertNull(rule.getLog());
        assertNull(rule.getType());
        assertNull(rule.getCode());
    }

    private void assertServiceMatching(CloudService expectedService, List services) {
        for (CloudService service : services) {
            if (service.getName().equals(expectedService.getName())) {
                assertServicesEqual(expectedService, service);
                return;
            }
        }
        fail("No service found matching " + expectedService.getName());
    }

    private void assertServicesEqual(CloudService expectedService, CloudService service) {
        assertEquals(expectedService.getName(), service.getName());
        assertEquals(expectedService.getLabel(), service.getLabel());
        assertEquals(expectedService.getPlan(), service.getPlan());
        assertEquals(expectedService.isUserProvided(), service.isUserProvided());
    }

    private void assertTimeWithinRange(String message, long actual, int timeTolerance) {
        // Allow more time deviations due to local clock being out of sync with cloud
        assertTrue(message,
                Math.abs(System.currentTimeMillis() - actual) < timeTolerance);
    }

    private void clearTestDomainAndRoutes() {
        CloudDomain domain = getDomainNamed(TEST_DOMAIN, connectedClient.getDomains());
        if (domain != null) {
            List routes = connectedClient.getRoutes(domain.getName());
            for (CloudRoute route : routes) {
                connectedClient.deleteRoute(route.getHost(), route.getDomain().getName());
            }
            connectedClient.deleteDomain(domain.getName());
        }
    }

    private String computeAppUrl(String appName) {
        return appName + "." + defaultDomainName;
    }

    private String computeAppUrlNoProtocol(String appName) {
        return computeAppUrl(appName);
    }

    private boolean containsSecurityGroupNamed(List groups, String groupName) {
        for (CloudSecurityGroup group : groups) {
            if (groupName.equalsIgnoreCase(group.getName())) {
                return true;
            }
        }
        return false;
    }

    private CloudApplication createAndUploadAndStartSampleServiceBrokerApp(String appName) throws IOException {
        createSpringApplication(appName);
        File jar = SampleProjects.sampleServiceBrokerApp();
        connectedClient.uploadApplication(appName, jar.getCanonicalPath());
        connectedClient.startApplication(appName);
        return connectedClient.getApplication(appName);
    }

    private CloudApplication createAndUploadAndStartSimpleSpringApp(String appName) throws IOException {
        createAndUploadSimpleSpringApp(appName);
        connectedClient.startApplication(appName);
        return connectedClient.getApplication(appName);
    }

    private CloudApplication createAndUploadExplodedSpringTestApp(String appName)
            throws IOException {
        File explodedDir = SampleProjects.springTravelUnpacked(temporaryFolder);
        assertTrue("Expected exploded test app at " + explodedDir.getCanonicalPath(), explodedDir.exists());
        createTestApp(appName, null, new Staging());
        connectedClient.uploadApplication(appName, explodedDir.getCanonicalPath());
        return connectedClient.getApplication(appName);
    }

    //
    // Shared test methods
    //

    private CloudApplication createAndUploadExplodedTestApp(String appName, File explodedDir, Staging staging)
            throws IOException {
        assertTrue("Expected exploded test app at " + explodedDir.getCanonicalPath(), explodedDir.exists());
        createTestApp(appName, null, staging);
        connectedClient.uploadApplication(appName, explodedDir.getCanonicalPath());
        return connectedClient.getApplication(appName);
    }

    private CloudApplication createAndUploadSimpleSpringApp(String appName) throws IOException {
        createSpringApplication(appName);
        File war = SampleProjects.simpleSpringApp();
        connectedClient.uploadApplication(appName, war.getCanonicalPath());
        return connectedClient.getApplication(appName);
    }

    private CloudApplication createAndUploadSimpleTestApp(String name) throws IOException {
        createAndUploadSimpleSpringApp(name);
        return connectedClient.getApplication(name);
    }

    //
    // Helper methods
    //

    private CloudService createMySqlService(String serviceName) {
        CloudService service = new CloudService(CloudEntity.Meta.defaultMeta(), serviceName);
        service.setLabel(MYSQL_SERVICE_LABEL);
        service.setPlan(MYSQL_SERVICE_PLAN);

        connectedClient.createService(service);

        return service;
    }

    private CloudService createMySqlServiceWithVersionAndProvider(String serviceName) {
        CloudServiceOffering databaseServiceOffering = getCloudServiceOffering(MYSQL_SERVICE_LABEL);

        CloudService service = new CloudService(CloudEntity.Meta.defaultMeta(), serviceName);
        service.setProvider(databaseServiceOffering.getProvider());
        service.setLabel(databaseServiceOffering.getLabel());
        service.setVersion(databaseServiceOffering.getVersion());
        service.setPlan(MYSQL_SERVICE_PLAN);

        connectedClient.createService(service);

        return service;
    }

    private void createSpringApplication(String appName) {
        createTestApp(appName, null, new Staging());
    }

    //
    // helper methods
    //

    private void createSpringApplication(String appName, List serviceNames) {
        createTestApp(appName, serviceNames, new Staging());
    }

    private void createSpringApplication(String appName, String buildpackUrl) {
        createTestApp(appName, null, new Staging(null, buildpackUrl));
    }

    private void createSpringApplication(String appName, String stack, Integer healthCheckTimeout) {
        createTestApp(appName, null, new Staging(null, null, stack, healthCheckTimeout));
    }

    private String createSpringTravelApp(String suffix) {
        return createSpringTravelApp(suffix, null);
    }

    private String createSpringTravelApp(String suffix, List serviceNames) {
        String appName = namespacedAppName("travel_test-" + suffix);
        createSpringApplication(appName, serviceNames);
        return appName;
    }

    private void createStandaloneRubyTestApp(String appName, List uris, List services) throws
            IOException {
        Staging staging = new Staging("ruby simple.rb", null);
        File file = SampleProjects.standaloneRuby();
        connectedClient.createApplication(appName, staging, 128, uris, services);
        connectedClient.uploadApplication(appName, file.getCanonicalPath());
    }

    private void createTestApp(String appName, List serviceNames, Staging staging) {
        List uris = new ArrayList();
        uris.add(computeAppUrl(appName));
        if (serviceNames != null) {
            for (String serviceName : serviceNames) {
                createMySqlService(serviceName);
            }
        }
        connectedClient.createApplication(appName, staging,
                DEFAULT_MEMORY,
                uris, serviceNames);
    }

    private CloudService createUserProvidedService(String serviceName) {
        CloudService service = new CloudService(CloudEntity.Meta.defaultMeta(), serviceName);

        Map credentials = new HashMap();
        credentials.put("host", "example.com");
        credentials.put("port", 1234);
        credentials.put("user", "me");

        connectedClient.createUserProvidedService(service, credentials);

        return service;
    }

    /**
     * Try to clean up any security group test data left behind in the case of assertions failing and test security
     * groups not being deleted as part of test logic.
     */
    private void deleteAnyOrphanedTestSecurityGroups() {
        try {
            CloudSecurityGroup securityGroup = connectedClient.getSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
            if (securityGroup != null) {
                connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
            }
        } catch (Exception e) {
            // Nothing we can do at this point except protect other teardown logic from not running
        }
    }

    private void doGetFile(CloudFoundryOperations client, String appName) throws Exception {
        String appDir = "app";
        String fileName = appDir + "/WEB-INF/web.xml";
        String emptyPropertiesFileName = appDir + "/WEB-INF/classes/empty.properties";

        // File is often not available immediately after starting an app... so allow up to 60 seconds wait
        for (int i = 0; i < 60; i++) {
            try {
                client.getFile(appName, 0, fileName);
                break;
            } catch (HttpServerErrorException ex) {
                Thread.sleep(1000);
            }
        }

        // Test downloading full file
        String fileContent = client.getFile(appName, 0, fileName);
        assertNotNull(fileContent);
        assertTrue(fileContent.length() > 5);

        // Test downloading range of file with start and end position
        int end = fileContent.length() - 3;
        int start = end / 2;
        String fileContent2 = client.getFile(appName, 0, fileName, start, end);
        assertEquals(fileContent.substring(start, end), fileContent2);

        // Test downloading range of file with just start position
        String fileContent3 = client.getFile(appName, 0, fileName, start);
        assertEquals(fileContent.substring(start), fileContent3);

        // Test downloading range of file with start position and end position exceeding the length
        int positionPastEndPosition = fileContent.length() + 999;
        String fileContent4 = client.getFile(appName, 0, fileName, start, positionPastEndPosition);
        assertEquals(fileContent.substring(start), fileContent4);

        // Test downloading end portion of file with length
        int length = fileContent.length() / 2;
        String fileContent5 = client.getFileTail(appName, 0, fileName, length);
        assertEquals(fileContent.substring(fileContent.length() - length), fileContent5);

        // Test downloading one byte of file with start and end position
        String fileContent6 = client.getFile(appName, 0, fileName, start, start + 1);
        assertEquals(fileContent.substring(start, start + 1), fileContent6);
        assertEquals(1, fileContent6.length());

        // Test downloading range of file with invalid start position
        int invalidStartPosition = fileContent.length() + 999;
        try {
            client.getFile(appName, 0, fileName, invalidStartPosition);
            fail("should have thrown exception");
        } catch (CloudFoundryException e) {
            assertTrue(e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE));
        }

        // Test downloading empty file
        String fileContent7 = client.getFile(appName, 0, emptyPropertiesFileName);
        assertNull(fileContent7);

        // Test downloading with invalid parameters - should all throw exceptions
        try {
            client.getFile(appName, 0, fileName, -2);
            fail("should have thrown exception");
        } catch (IllegalArgumentException e) {
            assertTrue(e.getMessage().contains("start position"));
        }
        try {
            client.getFile(appName, 0, fileName, 10, -2);
            fail("should have thrown exception");
        } catch (IllegalArgumentException e) {
            assertTrue(e.getMessage().contains("end position"));
        }
        try {
            client.getFile(appName, 0, fileName, 29, 28);
            fail("should have thrown exception");
        } catch (IllegalArgumentException e) {
            assertTrue(e.getMessage().contains("end position"));
        }
        try {
            client.getFile(appName, 0, fileName, 29, 28);
            fail("should have thrown exception");
        } catch (IllegalArgumentException e) {
            assertTrue(e.getMessage().contains("29"));
        }
        try {
            client.getFileTail(appName, 0, fileName, 0);
            fail("should have thrown exception");
        } catch (IllegalArgumentException e) {
            assertTrue(e.getMessage().contains("length"));
        }
    }

    private List doGetRecentLogs(String appName) throws InterruptedException {
        int attempt = 0;
        do {
            List logs = connectedClient.getRecentLogs(appName);

            if (logs.size() > 0) {
                return logs;
            }
            Thread.sleep(1000);
        } while (attempt++ < 20);
        fail("Failed to see recent logs");
        return null;
    }

    private void doOpenFile(CloudFoundryOperations client, String appName) throws Exception {
        String appDir = "app";
        String fileName = appDir + "/WEB-INF/web.xml";
        String emptyPropertiesFileName = appDir + "/WEB-INF/classes/empty.properties";

        // File is often not available immediately after starting an app... so
        // allow up to 60 seconds wait
        for (int i = 0; i < 60; i++) {
            try {
                client.getFile(appName, 0, fileName);
                break;
            } catch (HttpServerErrorException ex) {
                Thread.sleep(1000);
            }
        }
        // Test open file

        client.openFile(appName, 0, fileName, new ClientHttpResponseCallback() {

            public void onClientHttpResponse(ClientHttpResponse clientHttpResponse) throws IOException {
                InputStream in = clientHttpResponse.getBody();
                assertNotNull(in);
                byte[] fileContents = IOUtils.toByteArray(in);
                assertTrue(fileContents.length > 5);
            }
        });

        client.openFile(appName, 0, emptyPropertiesFileName, new ClientHttpResponseCallback() {

            public void onClientHttpResponse(ClientHttpResponse clientHttpResponse) throws IOException {
                InputStream in = clientHttpResponse.getBody();
                assertNotNull(in);
                byte[] fileContents = IOUtils.toByteArray(in);
                assertTrue(fileContents.length == 0);
            }
        });

    }

    private boolean ensureApplicationRunning(String appName) {
        InstancesInfo instances;
        boolean pass = false;
        for (int i = 0; i < 50; i++) {
            try {
                instances = getInstancesWithTimeout(connectedClient, appName);
                assertNotNull(instances);

                List infos = instances.getInstances();
                assertEquals(1, infos.size());

                int passCount = 0;
                for (InstanceInfo info : infos) {
                    if (InstanceState.RUNNING.equals(info.getState())) {
                        passCount++;
                    }
                }
                if (passCount == infos.size()) {
                    pass = true;
                    break;
                }
            } catch (CloudFoundryException ex) {
                // ignore (we may get this when staging is still ongoing)
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // ignore
            }
        }
        return pass;
    }

    private CloudServiceOffering getCloudServiceOffering(String label) {
        List serviceOfferings = connectedClient.getServiceOfferings();
        for (CloudServiceOffering so : serviceOfferings) {
            if (so.getLabel().equals(label)) {
                return so;
            }
        }
        throw new IllegalStateException("No CloudServiceOffering found with label " + label + ".");
    }

    private CloudDomain getDomainNamed(String domainName, List domains) {
        for (CloudDomain domain : domains) {
            if (domain.getName().equals(domainName)) {
                return domain;
            }
        }
        return null;
    }

    private boolean getInstanceInfosWithTimeout(String appName, int count, boolean shouldBeRunning) {
        if (count > 1) {
            connectedClient.updateApplicationInstances(appName, count);
            CloudApplication app = connectedClient.getApplication(appName);
            assertEquals(count, app.getInstances());
        }

        InstancesInfo instances;
        boolean pass = false;
        for (int i = 0; i < 50; i++) {
            try {
                instances = getInstancesWithTimeout(connectedClient, appName);
                assertNotNull(instances);

                List infos = instances.getInstances();
                assertEquals(count, infos.size());

                int passCount = 0;
                for (InstanceInfo info : infos) {
                    if (shouldBeRunning) {
                        if (InstanceState.RUNNING.equals(info.getState()) ||
                                InstanceState.STARTING.equals(info.getState())) {
                            passCount++;
                        }
                    } else {
                        if (InstanceState.CRASHED.equals(info.getState()) ||
                                InstanceState.FLAPPING.equals(info.getState())) {
                            passCount++;
                        }
                    }
                }
                if (passCount == infos.size()) {
                    pass = true;
                    break;
                }
            } catch (CloudFoundryException ex) {
                // ignore (we may get this when staging is still ongoing)
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // ignore
            }
        }
        return pass;
    }

    private InstancesInfo getInstancesWithTimeout(CloudFoundryOperations client, String appName) {
        long start = System.currentTimeMillis();
        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                // ignore
            }

            final InstancesInfo applicationInstances = client.getApplicationInstances(appName);
            if (applicationInstances != null) {
                return applicationInstances;
            }

            if (System.currentTimeMillis() - start > STARTUP_TIMEOUT) {
                fail("Timed out waiting for startup");
                break; // for the compiler
            }
        }

        return null; // for the compiler
    }

    private CloudRoute getRouteWithHost(String hostName, List routes) {
        for (CloudRoute route : routes) {
            if (route.getHost().equals(hostName)) {
                return route;
            }
        }
        return null;
    }

    private boolean isSpaceBoundToSecurityGroup(String spaceName, String securityGroupName) {
        List boundSpaces = connectedClient.getSpacesBoundToSecurityGroup(securityGroupName);
        for (CloudSpace space : boundSpaces) {
            if (spaceName.equals(space.getName())) {
                return true;
            }
        }
        return false;
    }

    private HashSet listToHashSet(List list) {
        return new HashSet(list);
    }

    private String namespacedAppName(String basename) {
        return TEST_NAMESPACE + "-" + basename;
    }

    private String randomSecurityGroupName() {
        return UUID.randomUUID().toString();
    }

    private CloudApplication uploadSpringTravelApp(String appName) throws IOException {
        File file = SampleProjects.springTravel();
        connectedClient.uploadApplication(appName, file.getCanonicalPath());
        return connectedClient.getApplication(appName);
    }

    private void validateClientAccess(CloudControllerClient client) {
        List offerings = client.getServiceOfferings();
        assertNotNull(offerings);
        assertTrue(offerings.size() >= 2);
    }

    private void waitForStatsAvailable(String appName, int instanceCount) throws InterruptedException {
        // TODO: Make this pattern reusable
        ApplicationStats stats = connectedClient.getApplicationStats(appName);
        for (int retries = 0; retries < 10 && stats.getRecords().size() < instanceCount; retries++) {
            Thread.sleep(1000);
            stats = connectedClient.getApplicationStats(appName);
        }

        InstanceStats firstInstance = stats.getRecords().get(0);
        assertEquals("0", firstInstance.getId());
        for (int retries = 0; retries < 50 && firstInstance.getUsage() == null; retries++) {
            Thread.sleep(1000);
            stats = connectedClient.getApplicationStats(appName);
            firstInstance = stats.getRecords().get(0);
        }
    }

    private static abstract class NoOpUploadStatusCallback implements UploadStatusCallback {

        public void onCheckResources() {
        }

        public void onMatchedFileNames(Set matchedFileNames) {
        }

        public void onProcessMatchedResources(int length) {
        }
    }

    private static class NonUnsubscribingUploadStatusCallback extends NoOpUploadStatusCallback {

        public int progressCount = 0;

        public boolean onProgress(String status) {
            progressCount++;
            return false;
        }
    }

    private static class UnsubscribingUploadStatusCallback extends NoOpUploadStatusCallback {

        public int progressCount = 0;

        public boolean onProgress(String status) {
            progressCount++;
            // unsubscribe after the first report
            return progressCount == 1;
        }
    }

    private class AccumulatingApplicationLogListener implements ApplicationLogListener {

        private List logs = new ArrayList();

        public void onComplete() {
        }

        public void onError(Throwable exception) {
            fail(exception.getMessage());
        }

        public void onMessage(ApplicationLog log) {
            logs.add(log);
        }

    }
}
File
CloudFoundryClientTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
Method declaration
Chunk
Conflicting content
        assertTrue("Failed to stream normal log", testListener.logs.size() > 0);
    }

<<<<<<< HEAD
	@Test
	public void deleteOrphanedRoutes() {
		connectedClient.addDomain(TEST_DOMAIN);
		connectedClient.addRoute("unbound_route", TEST_DOMAIN);

		List routes = connectedClient.getRoutes(TEST_DOMAIN);
		CloudRoute unboundRoute = getRouteWithHost("unbound_route", routes);
		assertNotNull(unboundRoute);
		assertEquals(0, unboundRoute.getAppsUsingRoute());

		List deletedRoutes = connectedClient.deleteOrphanedRoutes();
		assertNull(getRouteWithHost("unbound_route", connectedClient.getRoutes(TEST_DOMAIN)));

		assertTrue(deletedRoutes.size() > 0);
		boolean found = false;
		for (CloudRoute route : deletedRoutes) {
			if (route.getHost().equals("unbound_route")) {
				found = true;
			}
		}
		assertTrue(found);
	}
	
	@Test
	public void appsWithRoutesAreCounted() throws IOException {
		String appName = namespacedAppName("my_route3");
		CloudApplication app = createAndUploadSimpleTestApp(appName);
		List uris = app.getUris();
		uris.add("my_route3." + TEST_DOMAIN);
		connectedClient.addDomain(TEST_DOMAIN);
		connectedClient.updateApplicationUris(appName, uris);

		List routes = connectedClient.getRoutes(TEST_DOMAIN);
		assertNotNull(getRouteWithHost("my_route3", routes));
		assertEquals(1, getRouteWithHost("my_route3", routes).getAppsUsingRoute());
		assertTrue(getRouteWithHost("my_route3", routes).inUse());

		List defaultDomainRoutes = connectedClient.getRoutes(defaultDomainName);
		assertNotNull(getRouteWithHost(appName, defaultDomainRoutes));
		assertEquals(1, getRouteWithHost(appName, defaultDomainRoutes).getAppsUsingRoute());
		assertTrue(getRouteWithHost(appName, defaultDomainRoutes).inUse());
	}

	//
	// Configuration/Metadata tests
	//
=======
    //
    // Application and Services tests
    //

    @After
    public void tearDown() throws Exception {
        // Clean after ourselves so that there are no leftover apps, services, domains, and routes
        if (connectedClient != null) { //may happen if setUp() fails
            connectedClient.deleteAllApplications();
            connectedClient.deleteAllServices();
            clearTestDomainAndRoutes();
        }
        tearDownComplete = true;
    }

    @Test
    public void updateApplicationDisk() throws IOException {
        String appName = createSpringTravelApp("updateDisk");
        connectedClient.updateApplicationDiskQuota(appName, 2048);
        CloudApplication app = connectedClient.getApplication(appName);
        assertEquals(2048, app.getDiskQuota());
    }

    @Test
    public void updateApplicationInstances() throws Exception {
        String appName = createSpringTravelApp("updateInstances");
        CloudApplication app = connectedClient.getApplication(appName);

        assertEquals(1, app.getInstances());
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        connectedClient.updateApplicationInstances(appName, 3);
        app = connectedClient.getApplication(appName);
Solution content
        assertTrue("Failed to stream normal log", testListener.logs.size() > 0);
    }

    @After
    public void tearDown() throws Exception {
        // Clean after ourselves so that there are no leftover apps, services, domains, and routes
        if (connectedClient != null) { //may happen if setUp() fails
            connectedClient.deleteAllApplications();
            connectedClient.deleteAllServices();
            clearTestDomainAndRoutes();
            deleteAnyOrphanedTestSecurityGroups();
        }
        tearDownComplete = true;
    }

    @Test
    public void updateApplicationDisk() throws IOException {
        String appName = createSpringTravelApp("updateDisk");
        connectedClient.updateApplicationDiskQuota(appName, 2048);
        CloudApplication app = connectedClient.getApplication(appName);
        assertEquals(2048, app.getDiskQuota());
    }

    @Test
    public void updateApplicationInstances() throws Exception {
        String appName = createSpringTravelApp("updateInstances");
        CloudApplication app = connectedClient.getApplication(appName);

        assertEquals(1, app.getInstances());

        connectedClient.updateApplicationInstances(appName, 3);
        app = connectedClient.getApplication(appName);
File
CloudFoundryClientTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Comment
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
        assertEquals(256, app.getMemory());
    }

<<<<<<< HEAD
	@Test
	public void refreshTokenOnExpiration() throws Exception {
		URL cloudControllerUrl = new URL(CCNG_API_URL);
		CloudCredentials credentials = new CloudCredentials(CCNG_USER_EMAIL, CCNG_USER_PASS);

		CloudControllerClientFactory factory =
			new CloudControllerClientFactory(httpProxyConfiguration, CCNG_API_SSL);
		CloudControllerClient client = factory.newCloudController(cloudControllerUrl, credentials, CCNG_USER_ORG, CCNG_USER_SPACE);

		client.login();

		validateClientAccess(client);

		OauthClient oauthClient = factory.getOauthClient();
		OAuth2AccessToken token = oauthClient.getToken();
		if (token instanceof DefaultOAuth2AccessToken) {
			// set the token expiration to "now", forcing the access token to be refreshed
			((DefaultOAuth2AccessToken) token).setExpiration(new Date());
			validateClientAccess(client);
		} else {
			fail("Error forcing expiration of access token");
		}
	}

	private void validateClientAccess(CloudControllerClient client) {
		List offerings = client.getServiceOfferings();
		assertNotNull(offerings);
		assertTrue(offerings.size() >= 2);
	}

	@Test
	public void getRestLog() throws IOException {
		final List log1 = new ArrayList();
		final List log2 = new ArrayList();
		connectedClient.registerRestLogListener(new RestLogCallback() {
			public void onNewLogEntry(RestLogEntry logEntry) {
				log1.add(logEntry);
			}
		});
		RestLogCallback callback2 = new RestLogCallback() {
			public void onNewLogEntry(RestLogEntry logEntry) {
				log2.add(logEntry);
			}
		};
		connectedClient.registerRestLogListener(callback2);
		getApplications();
		connectedClient.deleteAllApplications();
		connectedClient.deleteAllServices();
		assertTrue(log1.size() > 0);
		assertEquals(log1, log2);
		connectedClient.unRegisterRestLogListener(callback2);
		getApplications();
		connectedClient.deleteAllApplications();
		assertTrue(log1.size() > log2.size());
	}
=======
    @Test
    public void updateApplicationService() throws IOException {
        String serviceName = "test_database";
        createMySqlService(serviceName);
        String appName = createSpringTravelApp("7");

        connectedClient.updateApplicationServices(appName, Collections.singletonList(serviceName));
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertTrue(app.getServices().size() > 0);
        assertEquals(serviceName, app.getServices().get(0));

        List emptyList = Collections.emptyList();
        connectedClient.updateApplicationServices(appName, emptyList);
        app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertEquals(emptyList, app.getServices());
    }

    @Test
    public void updateApplicationUris() throws IOException {
        String appName = namespacedAppName("updateUris");
        CloudApplication app = createAndUploadAndStartSimpleSpringApp(appName);

        List originalUris = app.getUris();
        assertEquals(Collections.singletonList(computeAppUrlNoProtocol(appName)), originalUris);

        List uris = new ArrayList(app.getUris());
        uris.add(computeAppUrlNoProtocol(namespacedAppName("url2")));
        connectedClient.updateApplicationUris(appName, uris);
        app = connectedClient.getApplication(appName);
        List newUris = app.getUris();
        assertNotNull(newUris);
        assertEquals(uris.size(), newUris.size());
        for (String uri : uris) {
            assertTrue(newUris.contains(uri));
        }
        connectedClient.updateApplicationUris(appName, originalUris);
        app = connectedClient.getApplication(appName);
        assertEquals(originalUris, app.getUris());
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    @Test
    public void updatePassword() throws MalformedURLException {
Solution content
        assertEquals(256, app.getMemory());
    }

    @Test
    public void updateApplicationService() throws IOException {
        String serviceName = "test_database";
        createMySqlService(serviceName);
        String appName = createSpringTravelApp("7");

        connectedClient.updateApplicationServices(appName, Collections.singletonList(serviceName));
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertTrue(app.getServices().size() > 0);
        assertEquals(serviceName, app.getServices().get(0));

        List emptyList = Collections.emptyList();
        connectedClient.updateApplicationServices(appName, emptyList);
        app = connectedClient.getApplication(appName);
        assertNotNull(app.getServices());
        assertEquals(emptyList, app.getServices());
    }

    @Test
    public void updateApplicationUris() throws IOException {
        String appName = namespacedAppName("updateUris");
        CloudApplication app = createAndUploadAndStartSimpleSpringApp(appName);

        List originalUris = app.getUris();
        assertEquals(Collections.singletonList(computeAppUrlNoProtocol(appName)), originalUris);

        List uris = new ArrayList(app.getUris());
        uris.add(computeAppUrlNoProtocol(namespacedAppName("url2")));
        connectedClient.updateApplicationUris(appName, uris);
        app = connectedClient.getApplication(appName);
        List newUris = app.getUris();
        assertNotNull(newUris);
        assertEquals(uris.size(), newUris.size());
        for (String uri : uris) {
            assertTrue(newUris.contains(uri));
        }
        connectedClient.updateApplicationUris(appName, originalUris);
        app = connectedClient.getApplication(appName);
        assertEquals(originalUris, app.getUris());
    }

    @Test
    public void updatePassword() throws MalformedURLException {
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
    }


<<<<<<< HEAD
	@Test
	public void crudSecurityGroups() throws Exception {
		assumeTrue(CCNG_USER_IS_ADMIN);

		List rules = new ArrayList();
		SecurityGroupRule rule = new SecurityGroupRule("tcp", "80, 443", "205.158.11.29");
		rules.add(rule);
		rule = new SecurityGroupRule("all", null, "0.0.0.0-255.255.255.255");
		rules.add(rule);
		rule = new SecurityGroupRule("icmp", null, "0.0.0.0/0", true, 0, 1);
		rules.add(rule);
		CloudSecurityGroup securityGroup = new CloudSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, rules);

		// Create
		connectedClient.createSecurityGroup(securityGroup);

		// Verify created
		securityGroup = connectedClient.getSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
		assertNotNull(securityGroup);
		assertThat(securityGroup.getRules().size(), is(3));
		assertRulesMatchTestData(securityGroup);

		// Update group
		rules = new ArrayList();
		rule = new SecurityGroupRule("all", null, "0.0.0.0-255.255.255.255");
		rules.add(rule);
		securityGroup = new CloudSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, rules);
		connectedClient.updateSecurityGroup(securityGroup);

		// Verify update
		securityGroup = connectedClient.getSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
		assertThat(securityGroup.getRules().size(), is(1));

		// Delete group
		connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
		// Verify deleted
		securityGroup = connectedClient.getSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
		assertNull(securityGroup);
	}

	private void assertRulesMatchTestData(CloudSecurityGroup securityGroup) {
		// This asserts against the test data defined in the crudSecurityGroups method
		// Rule ordering is preserved so we can depend on it here
		SecurityGroupRule rule = securityGroup.getRules().get(0);
		assertThat(rule.getProtocol(), is("tcp"));
		assertThat(rule.getPorts(), is("80, 443"));
		assertThat(rule.getDestination(), is("205.158.11.29"));
		assertNull(rule.getLog());
		assertNull(rule.getType());
		assertNull(rule.getCode());

		rule = securityGroup.getRules().get(1);
		assertThat(rule.getProtocol(), is("all"));
		assertNull(rule.getPorts());
		assertThat(rule.getDestination(), is("0.0.0.0-255.255.255.255"));
		assertNull(rule.getLog());
		assertNull(rule.getType());
		assertNull(rule.getCode());

		rule = securityGroup.getRules().get(2);
		assertThat(rule.getProtocol(), is("icmp"));
		assertNull(rule.getPorts());
		assertThat(rule.getDestination(), is("0.0.0.0/0"));
		assertTrue(rule.getLog());
		assertThat(rule.getType(), is(0));
		assertThat(rule.getCode(), is(1));
	}

	@Test
	public void securityGroupsCanBeCreatedAndUpdatedFromJsonFiles() throws FileNotFoundException{
		assumeTrue(CCNG_USER_IS_ADMIN);

		// Create
		connectedClient.createSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File("src/test/resources/security-groups/test-rules-1.json")));

		// Verify created
		CloudSecurityGroup securityGroup = connectedClient.getSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
		assertNotNull(securityGroup);
		assertThat(securityGroup.getRules().size(), is(4));
		assertRulesMatchThoseInJsonFile1(securityGroup);

		// Update group
		connectedClient.updateSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File("src/test/resources/security-groups/test-rules-2.json")));

		// Verify update
		securityGroup = connectedClient.getSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
		assertThat(securityGroup.getRules().size(), is(1));

		// Clean up after ourselves
		connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
	}

	private void assertRulesMatchThoseInJsonFile1(CloudSecurityGroup securityGroup) {
		// Rule ordering is preserved so we can depend on it here

		SecurityGroupRule rule = securityGroup.getRules().get(0);
		assertThat(rule.getProtocol(), is("icmp"));
		assertNull(rule.getPorts());
		assertThat(rule.getDestination(), is("0.0.0.0/0"));
		assertNull(rule.getLog());
		assertThat(rule.getType(), is(0));
		assertThat(rule.getCode(), is(1));

		rule = securityGroup.getRules().get(1);
		assertThat(rule.getProtocol(), is("tcp"));
		assertThat(rule.getPorts(), is("2048-3000"));
		assertThat(rule.getDestination(), is("1.0.0.0/0"));
		assertTrue(rule.getLog());
		assertNull(rule.getType());
		assertNull(rule.getCode());

		rule = securityGroup.getRules().get(2);
		assertThat(rule.getProtocol(), is("udp"));
		assertThat(rule.getPorts(), is("53, 5353"));
		assertThat(rule.getDestination(), is("2.0.0.0/0"));
		assertNull(rule.getLog());
		assertNull(rule.getType());
		assertNull(rule.getCode());

		rule = securityGroup.getRules().get(3);
		assertThat(rule.getProtocol(), is("all"));
		assertNull(rule.getPorts());
		assertThat(rule.getDestination(), is("3.0.0.0/0"));
		assertNull(rule.getLog());
		assertNull(rule.getType());
		assertNull(rule.getCode());
	}

	@Test(expected=IllegalArgumentException.class)
	public void attemptingToDeleteANonExistentSecurityGroupThrowsAnIllegalArgumentException(){
		assumeTrue(CCNG_USER_IS_ADMIN);

		connectedClient.deleteSecurityGroup(randomSecurityGroupName());
	}

	@Test(expected=IllegalArgumentException.class)
	public void attemptingToUpdateANonExistentSecurityGroupThrowsAnIllegalArgumentException() throws FileNotFoundException{
		assumeTrue(CCNG_USER_IS_ADMIN);

		connectedClient.updateSecurityGroup(randomSecurityGroupName(), new FileInputStream(new File("src/test/resources/security-groups/test-rules-2.json")));
	}

	private String randomSecurityGroupName() {
		return UUID.randomUUID().toString();
	}

	@Test
	public void bindingAndUnbindingSecurityGroupToDefaultStagingSet() throws FileNotFoundException{
		assumeTrue(CCNG_USER_IS_ADMIN);

		// Given
		assertFalse(containsSecurityGroupNamed(connectedClient.getStagingSecurityGroups(), CCNG_SECURITY_GROUP_NAME_TEST));
		connectedClient.createSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File("src/test/resources/security-groups/test-rules-2.json")));

		// When
		connectedClient.bindStagingSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

		// Then
		assertTrue(containsSecurityGroupNamed(connectedClient.getStagingSecurityGroups(), CCNG_SECURITY_GROUP_NAME_TEST));

		// When
		connectedClient.unbindStagingSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

		// Then
		assertFalse(containsSecurityGroupNamed(connectedClient.getStagingSecurityGroups(), CCNG_SECURITY_GROUP_NAME_TEST));

		// Cleanup
		connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
	}

	@Test
	public void bindingAndUnbindingSecurityGroupToDefaultRunningSet() throws FileNotFoundException{
		assumeTrue(CCNG_USER_IS_ADMIN);

		// Given
		assertFalse(containsSecurityGroupNamed(connectedClient.getRunningSecurityGroups(), CCNG_SECURITY_GROUP_NAME_TEST));
		connectedClient.createSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File("src/test/resources/security-groups/test-rules-2.json")));

		// When
		connectedClient.bindRunningSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

		// Then
		assertTrue(containsSecurityGroupNamed(connectedClient.getRunningSecurityGroups(), CCNG_SECURITY_GROUP_NAME_TEST));

		// When
		connectedClient.unbindRunningSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);

		// Then
		assertFalse(containsSecurityGroupNamed(connectedClient.getRunningSecurityGroups(), CCNG_SECURITY_GROUP_NAME_TEST));

		// Cleanup
		connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
	}

	@Test
	public void bindingAndUnbindingSecurityGroupToSpaces() throws FileNotFoundException{
		assumeTrue(CCNG_USER_IS_ADMIN);

		// Given
		connectedClient.createSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST, new FileInputStream(new File("src/test/resources/security-groups/test-rules-2.json")));

		// When
		connectedClient.bindSecurityGroup(CCNG_USER_ORG, CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST);
		// Then
		assertTrue(isSpaceBoundToSecurityGroup(CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST));

		// When
		connectedClient.unbindSecurityGroup(CCNG_USER_ORG, CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST);
		//Then
		assertFalse(isSpaceBoundToSecurityGroup(CCNG_USER_SPACE, CCNG_SECURITY_GROUP_NAME_TEST));

		// Cleanup
		connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
	}

	private boolean isSpaceBoundToSecurityGroup(String spaceName, String securityGroupName) {
		List boundSpaces = connectedClient.getSpacesBoundToSecurityGroup(securityGroupName);
		for(CloudSpace space: boundSpaces){
			if(spaceName.equals(space.getName())){
				return true;
			}
		}
		return false;
	}

	private boolean containsSecurityGroupNamed(List groups, String groupName) {
		for(CloudSecurityGroup group: groups){
			if(groupName.equalsIgnoreCase(group.getName())){
				return true;
			}
		}
		return false;
	}

	/**
	 * Try to clean up any security group test data left behind in the case of assertions failing and
	 * test security groups not being deleted as part of test logic.
	 */
	private void deleteAnyOrphanedTestSecurityGroups(){
		try{
			CloudSecurityGroup securityGroup = connectedClient.getSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
			if(securityGroup != null){
				connectedClient.deleteSecurityGroup(CCNG_SECURITY_GROUP_NAME_TEST);
			}
		} catch(Exception e){
			// Nothing we can do at this point except protect other teardown logic from not running
		}
	}

	//
	// Shared test methods
	//

	private boolean getInstanceInfosWithTimeout(String appName, int count, boolean shouldBeRunning) {
		if (count > 1) {
			connectedClient.updateApplicationInstances(appName, count);
			CloudApplication app = connectedClient.getApplication(appName);
			assertEquals(count, app.getInstances());
		}

		InstancesInfo instances;
		boolean pass = false;
		for (int i = 0; i < 50; i++) {
			try {
				instances = getInstancesWithTimeout(connectedClient, appName);
				assertNotNull(instances);

				List infos = instances.getInstances();
				assertEquals(count, infos.size());

				int passCount = 0;
				for (InstanceInfo info : infos) {
					if (shouldBeRunning) {
						if (InstanceState.RUNNING.equals(info.getState()) ||
								InstanceState.STARTING.equals(info.getState())) {
							passCount++;
						}
					} else {
						if (InstanceState.CRASHED.equals(info.getState()) ||
								InstanceState.FLAPPING.equals(info.getState())) {
							passCount++;
						}
					}
				}
				if (passCount == infos.size()) {
					pass = true;
					break;
				}
			} catch (CloudFoundryException ex) {
				// ignore (we may get this when staging is still ongoing)
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// ignore
			}
		}
		return pass;
	}

	private void doOpenFile(CloudFoundryOperations client, String appName) throws Exception {
		String appDir = "app";
		String fileName = appDir + "/WEB-INF/web.xml";
		String emptyPropertiesFileName = appDir + "/WEB-INF/classes/empty.properties";

		// File is often not available immediately after starting an app... so
		// allow up to 60 seconds wait
		for (int i = 0; i < 60; i++) {
			try {
				client.getFile(appName, 0, fileName);
				break;
			} catch (HttpServerErrorException ex) {
				Thread.sleep(1000);
			}
		}
		// Test open file

		client.openFile(appName, 0, fileName, new ClientHttpResponseCallback() {

			public void onClientHttpResponse(ClientHttpResponse clientHttpResponse) throws IOException {
				InputStream in = clientHttpResponse.getBody();
				assertNotNull(in);
				byte[] fileContents = IOUtils.toByteArray(in);
				assertTrue(fileContents.length > 5);
			}
		});

		client.openFile(appName, 0, emptyPropertiesFileName, new ClientHttpResponseCallback() {

			public void onClientHttpResponse(ClientHttpResponse clientHttpResponse) throws IOException {
				InputStream in = clientHttpResponse.getBody();
				assertNotNull(in);
				byte[] fileContents = IOUtils.toByteArray(in);
				assertTrue(fileContents.length == 0);
			}
		});
=======
    //
    // Configuration/Metadata tests
    //

    @Test
    public void uploadStandaloneApplication() throws IOException {
        String appName = namespacedAppName("standalone-ruby");
        List uris = new ArrayList();
        List services = new ArrayList();
        createStandaloneRubyTestApp(appName, uris, services);
        connectedClient.startApplication(appName);
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());
        assertEquals(uris, app.getUris());
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    @Test
    public void uploadStandaloneApplicationWithURLs() throws IOException {
Solution content
    }

    @Test
    public void uploadStandaloneApplication() throws IOException {
        String appName = namespacedAppName("standalone-ruby");
        List uris = new ArrayList();
        List services = new ArrayList();
        createStandaloneRubyTestApp(appName, uris, services);
        connectedClient.startApplication(appName);
        CloudApplication app = connectedClient.getApplication(appName);
        assertNotNull(app);
        assertEquals(CloudApplication.AppState.STARTED, app.getState());
        assertEquals(uris, app.getUris());
    }

    @Test
    public void uploadStandaloneApplicationWithURLs() throws IOException {
File
CloudFoundryClientTest.java
Developer's decision
Combination
Kind of conflict
Annotation
Comment
For statement
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
        assertEquals(Collections.singletonList(computeAppUrlNoProtocol(appName)), app.getUris());
    }

<<<<<<< HEAD
	private void doGetFile(CloudFoundryOperations client, String appName) throws Exception {
		String appDir = "app";
		String fileName = appDir + "/WEB-INF/web.xml";
		String emptyPropertiesFileName = appDir + "/WEB-INF/classes/empty.properties";

		// File is often not available immediately after starting an app... so allow up to 60 seconds wait
		for (int i = 0; i < 60; i++) {
			try {
				client.getFile(appName, 0, fileName);
				break;
			} catch (HttpServerErrorException ex) {
				Thread.sleep(1000);
			}
		}

		// Test downloading full file
		String fileContent = client.getFile(appName, 0, fileName);
		assertNotNull(fileContent);
		assertTrue(fileContent.length() > 5);

		// Test downloading range of file with start and end position
		int end = fileContent.length() - 3;
		int start = end/2;
		String fileContent2 = client.getFile(appName, 0, fileName, start, end);
		assertEquals(fileContent.substring(start, end), fileContent2);

		// Test downloading range of file with just start position
		String fileContent3 = client.getFile(appName, 0, fileName, start);
		assertEquals(fileContent.substring(start), fileContent3);

		// Test downloading range of file with start position and end position exceeding the length
		int positionPastEndPosition = fileContent.length() + 999;
		String fileContent4 = client.getFile(appName, 0, fileName, start, positionPastEndPosition);
		assertEquals(fileContent.substring(start), fileContent4);

		// Test downloading end portion of file with length
		int length = fileContent.length() / 2;
		String fileContent5 = client.getFileTail(appName, 0, fileName, length);
		assertEquals(fileContent.substring(fileContent.length() - length), fileContent5);

		// Test downloading one byte of file with start and end position
		String fileContent6 = client.getFile(appName, 0, fileName, start, start + 1);
		assertEquals(fileContent.substring(start, start + 1), fileContent6);
		assertEquals(1, fileContent6.length());

		// Test downloading range of file with invalid start position
		int invalidStartPosition = fileContent.length() + 999;
		try {
			client.getFile(appName, 0, fileName, invalidStartPosition);
			fail("should have thrown exception");
		} catch (CloudFoundryException e) {
			assertTrue(e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE));
		}

		// Test downloading empty file
		String fileContent7 = client.getFile(appName, 0, emptyPropertiesFileName);
		assertNull(fileContent7);

		// Test downloading with invalid parameters - should all throw exceptions
		try {
			client.getFile(appName, 0, fileName, -2);
			fail("should have thrown exception");
		} catch (IllegalArgumentException e) {
			assertTrue(e.getMessage().contains("start position"));
		}
		try {
			client.getFile(appName, 0, fileName, 10, -2);
			fail("should have thrown exception");
		} catch (IllegalArgumentException e) {
			assertTrue(e.getMessage().contains("end position"));
		}
		try {
			client.getFile(appName, 0, fileName, 29, 28);
			fail("should have thrown exception");
		} catch (IllegalArgumentException e) {
			assertTrue(e.getMessage().contains("end position"));
		}
		try {
			client.getFile(appName, 0, fileName, 29, 28);
			fail("should have thrown exception");
		} catch (IllegalArgumentException e) {
			assertTrue(e.getMessage().contains("29"));
		}
		try {
			client.getFileTail(appName, 0, fileName, 0);
			fail("should have thrown exception");
		} catch (IllegalArgumentException e) {
			assertTrue(e.getMessage().contains("length"));
		}
	}
=======
    private void assertDomainInList(List domains) {
        assertTrue(domains.size() >= 1);
        assertNotNull(getDomainNamed(TEST_DOMAIN, domains));
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    private void assertDomainNotInList(List domains) {
        assertNull(getDomainNamed(TEST_DOMAIN, domains));
Solution content
        assertEquals(Collections.singletonList(computeAppUrlNoProtocol(appName)), app.getUris());
    }

    private HashSet arrayToHashSet(String... array) {
        return listToHashSet(asList(array));
    }

    private void assertAppEnvironment(Map env) {
        assertMapInEnv(env, "staging_env_json", true);
        assertMapInEnv(env, "running_env_json", true);
        assertMapInEnv(env, "environment_json", true, "testKey");
        assertMapInEnv(env, "system_env_json", true, "VCAP_SERVICES");
        // this value is not present in Pivotal CF < 1.4
        assertMapInEnv(env, "application_env_json", false, "VCAP_APPLICATION");
    }

    private void assertDomainInList(List domains) {
        assertTrue(domains.size() >= 1);
        assertNotNull(getDomainNamed(TEST_DOMAIN, domains));
    }

    private void assertDomainNotInList(List domains) {
        assertNull(getDomainNamed(TEST_DOMAIN, domains));
File
CloudFoundryClientTest.java
Developer's decision
Manual
Kind of conflict
Method declaration
Chunk
Conflicting content
        service.setLabel(MYSQL_SERVICE_LABEL);
        service.setPlan(MYSQL_SERVICE_PLAN);

<<<<<<< HEAD
	private void createTestApp(String appName, List serviceNames, Staging staging) {
		List uris = new ArrayList();
		uris.add(computeAppUrl(appName));
		if (serviceNames != null) {
			for (String serviceName : serviceNames) {
				createMySqlService(serviceName);
			}
		}
		connectedClient.createApplication(appName, staging,
              			DEFAULT_MEMORY,
              			uris, serviceNames);
	}
=======
        connectedClient.createService(service);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        return service;
    }
Solution content
        service.setLabel(MYSQL_SERVICE_LABEL);
        service.setPlan(MYSQL_SERVICE_PLAN);

        connectedClient.createService(service);

        return service;
    }
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Method declaration
Method invocation
Chunk
Conflicting content
<<<<<<< HEAD
        connectedClient.uploadApplication(appName, file.getCanonicalPath());
    }

	private InstancesInfo getInstancesWithTimeout(CloudFoundryOperations client, String appName) {
		long start = System.currentTimeMillis();
		while (true) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e1) {
				// ignore
			}

			final InstancesInfo applicationInstances = client.getApplicationInstances(appName);
			if (applicationInstances != null) {
				return applicationInstances;
			}

			if (System.currentTimeMillis() - start > STARTUP_TIMEOUT) {
				fail("Timed out waiting for startup");
				break; // for the compiler
			}
		}

		return null; // for the compiler
	}
=======
    private void createTestApp(String appName, List serviceNames, Staging staging) {
        List uris = new ArrayList();
        uris.add(computeAppUrl(appName));
        if (serviceNames != null) {
            for (String serviceName : serviceNames) {
                createMySqlService(serviceName);
            }
        }
        connectedClient.createApplication(appName, staging,
                DEFAULT_MEMORY,
                uris, serviceNames);
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    private CloudService createUserProvidedService(String serviceName) {
        CloudService service = new CloudService(CloudEntity.Meta.defaultMeta(), serviceName);
Solution content
        connectedClient.uploadApplication(appName, file.getCanonicalPath());
    }

    private void createTestApp(String appName, List serviceNames, Staging staging) {
        List uris = new ArrayList();
        uris.add(computeAppUrl(appName));
        if (serviceNames != null) {
            for (String serviceName : serviceNames) {
                createMySqlService(serviceName);
            }
        }
        connectedClient.createApplication(appName, staging,
                DEFAULT_MEMORY,
                uris, serviceNames);
    }

    private CloudService createUserProvidedService(String serviceName) {
        CloudService service = new CloudService(CloudEntity.Meta.defaultMeta(), serviceName);
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Method declaration
Chunk
Conflicting content
        }
    }

<<<<<<< HEAD
	private void assertTimeWithinRange(String message, long actual, int timeTolerance) {
		// Allow more time deviations due to local clock being out of sync with cloud
		assertTrue(message,
						Math.abs(System.currentTimeMillis() - actual) < timeTolerance);
	}
=======
    private List doGetRecentLogs(String appName) throws InterruptedException {
        int attempt = 0;
        do {
            List logs = connectedClient.getRecentLogs(appName);

            if (logs.size() > 0) {
                return logs;
            }
            Thread.sleep(1000);
        } while (attempt++ < 20);
        fail("Failed to see recent logs");
        return null;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    private void doOpenFile(CloudFoundryClient client, String appName) throws Exception {
        String appDir = "app";
Solution content
        }
    }

    private List doGetRecentLogs(String appName) throws InterruptedException {
        int attempt = 0;
        do {
            List logs = connectedClient.getRecentLogs(appName);

            if (logs.size() > 0) {
                return logs;
            }
            Thread.sleep(1000);
        } while (attempt++ < 20);
        fail("Failed to see recent logs");
        return null;
    }

    private void doOpenFile(CloudFoundryOperations client, String appName) throws Exception {
        String appDir = "app";
File
CloudFoundryClientTest.java
Developer's decision
Version 2
Kind of conflict
Method declaration
Chunk
Conflicting content
import static org.hamcrest.core.IsNull.nullValue;

public class CloudApplicationTest {
<<<<<<< HEAD
	@Test
	public void getEnvAsMap() {
		Map attributes = new HashMap();
		attributes.put("env", Arrays.asList("ENV1=VAL1", "ENV2=", "ENV3"));
		attributes.put("instances", 1);
		attributes.put("name", "Test1");
		attributes.put("state", CloudApplication.AppState.STOPPED.name());

		CloudApplication cloudApplication = new CloudApplication(attributes);

		Map envMap = cloudApplication.getEnvAsMap();
		assertThat(envMap.size(), is(3));
		assertThat(envMap.get("ENV1"), is("VAL1"));
		assertThat(envMap.get("ENV2"), is(nullValue()));
		assertThat(envMap.get("ENV3"), is(nullValue()));
	}

	@Test
	public void setEnvWithNonString() {
		// creating as an un-typed map to mimic Jackson behavior
		Map envMap = new HashMap();
		envMap.put("key1", "value1");
		envMap.put("key2", 3);
		envMap.put("key3", true);

		Map attributes = new HashMap();
		attributes.put("instances", 1);
		attributes.put("name", "Test1");
		attributes.put("state", CloudApplication.AppState.STOPPED.name());

		CloudApplication cloudApplication = new CloudApplication(attributes);

		cloudApplication.setEnv(envMap);

		Map actual = cloudApplication.getEnvAsMap();
		assertThat(actual.get("key1"), is("value1"));
		assertThat(actual.get("key2"), is("3"));
		assertThat(actual.get("key3"), is("true"));
	}
=======

    @Test
    public void testGetEnvAsMap() {
        Map attributes = new HashMap();
        attributes.put("env", Arrays.asList("ENV1=VAL1", "ENV2=", "ENV3"));
        attributes.put("instances", 1);
        attributes.put("name", "Test1");
        attributes.put("state", CloudApplication.AppState.STOPPED.name());

        CloudApplication cloudApplication = new CloudApplication(attributes);

        Map envMap = cloudApplication.getEnvAsMap();
        assertThat(envMap.size(), is(3));
        assertThat(envMap.get("ENV1"), is("VAL1"));
        assertThat(envMap.get("ENV2"), is(nullValue()));
        assertThat(envMap.get("ENV3"), is(nullValue()));
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
import static org.hamcrest.core.IsNull.nullValue;

public class CloudApplicationTest {

    @Test
    public void getEnvAsMap() {
        Map attributes = new HashMap();
        attributes.put("env", Arrays.asList("ENV1=VAL1", "ENV2=", "ENV3"));
        attributes.put("instances", 1);
        attributes.put("name", "Test1");
        attributes.put("state", CloudApplication.AppState.STOPPED.name());

        CloudApplication cloudApplication = new CloudApplication(attributes);

        Map envMap = cloudApplication.getEnvAsMap();
        assertThat(envMap.size(), is(3));
        assertThat(envMap.get("ENV1"), is("VAL1"));
        assertThat(envMap.get("ENV2"), is(nullValue()));
        assertThat(envMap.get("ENV3"), is(nullValue()));
    }

    @Test
    public void setEnvWithNonString() {
        // creating as an un-typed map to mimic Jackson behavior
        Map envMap = new HashMap();
        envMap.put("key1", "value1");
        envMap.put("key2", 3);
        envMap.put("key3", true);

        Map attributes = new HashMap();
        attributes.put("instances", 1);
        attributes.put("name", "Test1");
        attributes.put("state", CloudApplication.AppState.STOPPED.name());

        CloudApplication cloudApplication = new CloudApplication(attributes);

        cloudApplication.setEnv(envMap);

        Map actual = cloudApplication.getEnvAsMap();
        assertThat(actual.get("key1"), is("value1"));
        assertThat(actual.get("key2"), is("3"));
        assertThat(actual.get("key3"), is("true"));
    }
}
File
CloudApplicationTest.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
public class CloudControllerClientImplTest {

    private static final String CCNG_API_URL = System.getProperty("ccng.target", "http://api.run.pivotal.io");
<<<<<<< HEAD
    private static final String CCNG_USER_EMAIL = System.getProperty("ccng.email", "java-authenticatedClient-test-user@vmware.com");
    private static final String CCNG_USER_PASS = System.getProperty("ccng.passwd");
    private static final String CCNG_USER_ORG = System.getProperty("ccng.org", "gopivotal.com");
    private static final String CCNG_USER_SPACE = System.getProperty("ccng.space", "test");

    @Mock
    private RestUtil restUtil;
    @Mock
    private RestTemplate restTemplate;
    @Mock
    private ClientHttpRequestFactory clientHttpRequestFactory;
    @Mock
    private OauthClient oauthClient;
    @Mock
    private LoggregatorClient loggregatorClient;

    private CloudControllerClientImpl controllerClient;

    /**
     * Failed attempt to instantiate CloudControllerClientImpl with existing constructors. Just here to illustrate the
     * need to move the initialize() method out of the constructor.
     */
    public void setUpWithNonEmptyConstructorWithoutLuck() throws Exception {
        restUtil = mock(RestUtil.class);
        when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class), false)).thenReturn(restTemplate);
        when(restUtil.createOauthClient(any(URL.class), any(HttpProxyConfiguration.class), false)).thenReturn(oauthClient);
        when(restTemplate.getRequestFactory()).thenReturn(clientHttpRequestFactory);

        restUtil.createRestTemplate(null, false);
        restUtil.createOauthClient(new URL(CCNG_API_URL), null, false);

        controllerClient = new CloudControllerClientImpl(new URL("http://api.dummyendpoint.com/login"),
                restTemplate, oauthClient, loggregatorClient,
                new CloudCredentials(CCNG_USER_EMAIL, CCNG_USER_PASS),
                CCNG_USER_ORG, CCNG_USER_SPACE);
    }

    @Before
    public void setUpWithEmptyConstructor() throws Exception {
        controllerClient = new CloudControllerClientImpl();
    }
=======

    private static final String CCNG_USER_EMAIL = System.getProperty("ccng.email",
            "java-authenticatedClient-test-user@vmware.com");

    private static final String CCNG_USER_ORG = System.getProperty("ccng.org", "gopivotal.com");

    private static final String CCNG_USER_PASS = System.getProperty("ccng.passwd");

    private static final String CCNG_USER_SPACE = System.getProperty("ccng.space", "test");

    @Mock
    private ClientHttpRequestFactory clientHttpRequestFactory;

    private CloudControllerClientImpl controllerClient;

    @Mock
    private LoggregatorClient loggregatorClient;

    @Mock
    private OauthClient oauthClient;

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private RestUtil restUtil;
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

    @Test
    public void extractUriInfo_selects_most_specific_subdomain() throws Exception {
Solution content
public class CloudControllerClientImplTest {

    private static final String CCNG_API_URL = System.getProperty("ccng.target", "http://api.run.pivotal.io");

    private static final String CCNG_USER_EMAIL = System.getProperty("ccng.email",
            "java-authenticatedClient-test-user@vmware.com");

    private static final String CCNG_USER_ORG = System.getProperty("ccng.org", "gopivotal.com");

    private static final String CCNG_USER_PASS = System.getProperty("ccng.passwd");

    private static final String CCNG_USER_SPACE = System.getProperty("ccng.space", "test");

    @Mock
    private ClientHttpRequestFactory clientHttpRequestFactory;

    private CloudControllerClientImpl controllerClient;

    @Mock
    private LoggregatorClient loggregatorClient;

    @Mock
    private OauthClient oauthClient;

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private RestUtil restUtil;

    @Test
    public void extractUriInfo_selects_most_specific_subdomain() throws Exception {
File
CloudControllerClientImplTest.java
Developer's decision
Version 2
Kind of conflict
Annotation
Attribute
Comment
Method declaration
Method invocation
Chunk
Conflicting content
    public void extractUriInfo_selects_most_specific_subdomain() throws Exception {
        //given
        String uri = "myhost.sub1.sub2.domain.com";
<<<<<<< HEAD
        Map domains = new LinkedHashMap(); //Since impl iterates key, need to control iteration order with a LinkedHashMap
=======
        Map domains = new LinkedHashMap(); //Since impl iterates key, need to control
        // iteration order with a LinkedHashMap
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
        domains.put("domain.com", UUID.randomUUID());
        domains.put("sub1.sub2.domain.com", UUID.randomUUID());
        Map uriInfo = new HashMap(2);
Solution content
    public void extractUriInfo_selects_most_specific_subdomain() throws Exception {
        //given
        String uri = "myhost.sub1.sub2.domain.com";
        Map domains = new LinkedHashMap(); //Since impl iterates key, need to control
        // iteration order with a LinkedHashMap
        domains.put("domain.com", UUID.randomUUID());
        domains.put("sub1.sub2.domain.com", UUID.randomUUID());
        Map uriInfo = new HashMap(2);
File
CloudControllerClientImplTest.java
Developer's decision
Version 2
Kind of conflict
Comment
Method invocation
Variable
Chunk
Conflicting content
        Assert.assertEquals("myhost", uriInfo.get("host"));
    }

<<<<<<< HEAD
    @Test
    public void extractUriInfo_with_port_and_user() {
        Map uriInfo = new HashMap<>(2);
        String uri = "http://bob:hq@bang.foo.bar.com:8181";
        Map domains = new HashMap<>();
        domains.put("foo.bar.com", UUID.randomUUID());
        domains.put("anotherdomain.com", UUID.randomUUID());

        controllerClient.extractUriInfo(domains, uri, uriInfo);

        Assert.assertEquals(domains.get("foo.bar.com"), domains.get(uriInfo.get("domainName")));
        Assert.assertEquals("bang", uriInfo.get("host"));
=======
    @Before
    public void setUpWithEmptyConstructor() throws Exception {
        controllerClient = new CloudControllerClientImpl();
    }

    /**
     * Failed attempt to instantiate CloudControllerClientImpl with existing constructors. Just here to illustrate the
     * need to move the initialize() method out of the constructor.
     */
    public void setUpWithNonEmptyConstructorWithoutLuck() throws Exception {
        restUtil = mock(RestUtil.class);
        when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class), false)).thenReturn(restTemplate);
        when(restUtil.createOauthClient(any(URL.class), any(HttpProxyConfiguration.class), false)).thenReturn
                (oauthClient);
        when(restTemplate.getRequestFactory()).thenReturn(clientHttpRequestFactory);

        restUtil.createRestTemplate(null, false);
        restUtil.createOauthClient(new URL(CCNG_API_URL), null, false);

        controllerClient = new CloudControllerClientImpl(new URL("http://api.dummyendpoint.com/login"),
                restTemplate, oauthClient, loggregatorClient,
                new CloudCredentials(CCNG_USER_EMAIL, CCNG_USER_PASS),
                CCNG_USER_ORG, CCNG_USER_SPACE);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
    }

}
Solution content
        Assert.assertEquals("myhost", uriInfo.get("host"));
    }

    @Test
    public void extractUriInfo_with_port_and_user() {
        Map uriInfo = new HashMap<>(2);
        String uri = "http://bob:hq@bang.foo.bar.com:8181";
        Map domains = new HashMap<>();
        domains.put("foo.bar.com", UUID.randomUUID());
        domains.put("anotherdomain.com", UUID.randomUUID());

        controllerClient.extractUriInfo(domains, uri, uriInfo);

        Assert.assertEquals(domains.get("foo.bar.com"), domains.get(uriInfo.get("domainName")));
        Assert.assertEquals("bang", uriInfo.get("host"));
    }

    @Before
    public void setUpWithEmptyConstructor() throws Exception {
        controllerClient = new CloudControllerClientImpl();
    }

    /**
     * Failed attempt to instantiate CloudControllerClientImpl with existing constructors. Just here to illustrate the
     * need to move the initialize() method out of the constructor.
     */
    public void setUpWithNonEmptyConstructorWithoutLuck() throws Exception {
        restUtil = mock(RestUtil.class);
        when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class), false)).thenReturn(restTemplate);
        when(restUtil.createOauthClient(any(URL.class), any(HttpProxyConfiguration.class), false)).thenReturn
                (oauthClient);
        when(restTemplate.getRequestFactory()).thenReturn(clientHttpRequestFactory);

        restUtil.createRestTemplate(null, false);
        restUtil.createOauthClient(new URL(CCNG_API_URL), null, false);

        controllerClient = new CloudControllerClientImpl(new URL("http://api.dummyendpoint.com/login"),
                restTemplate, oauthClient, loggregatorClient,
                new CloudCredentials(CCNG_USER_EMAIL, CCNG_USER_PASS),
                CCNG_USER_ORG, CCNG_USER_SPACE);
    }

}
File
CloudControllerClientImplTest.java
Developer's decision
Concatenation
Kind of conflict
Annotation
Attribute
Comment
Method declaration
Method invocation
Method signature
Chunk
Conflicting content
	 */
			try {
 */
@SuppressWarnings("UnusedDeclaration")
abstract class AbstractApplicationAwareCloudFoundryMojo extends AbstractCloudFoundryMojo {
<<<<<<< HEAD
	private static final int DEFAULT_APP_STARTUP_TIMEOUT = 5;

	/**
	 * @parameter expression="${cf.appname}"
	 */
	private String appname;

	/**
	 * @parameter expression="${cf.url}"
	 */
	private String url;

	/**
	 * @parameter
	 */
	private List urls;

	/**
	 * A string of the form groupId:artifactId:version:packaging[:classifier].
	 * @parameter expression = "${cf.artifact}" default-value="${project.groupId}:${project.artifactId}:${project.version}:${project.packaging}"
				Thread.sleep(1000);

    /**

	private String artifact;

	/**
	 * The path of one of the following:
	 *
	 * 
    *
  • War file to deploy
  • *
  • Zip or Jar file to deploy
  • *
  • Exploded War directory
  • *
  • Directory containing a stand-alone application to deploy
  • *
* * @parameter expression = "${cf.path}" */ private File path; /** * The start command to use for the application. * * @parameter expression = "${cf.command}" */ private String command; /** * The buildpack to use for the application. * * @parameter expression = "${cf.buildpack}" */ private String buildpack; /** * The stack to use for the application. * * @parameter expression = "${cf.stack}" */ private String stack; /** * The health check timeout to use for the application. * * @parameter expression = "${cf.healthCheckTimeout}" */ private Integer healthCheckTimeout; /** * The app startup timeout to use for the application. * * @parameter expression = "${cf.appStartupTimeout}" */ private Integer appStartupTimeout; /** * Set the disk quota for the application * * @parameter expression="${cf.diskQuota}" */ private Integer diskQuota; /** * Set the memory reservation for the application * * @parameter expression="${cf.memory}" */ private Integer memory; /** * Set the expected number of instances * * @parameter expression="${cf.instances}" */ private Integer instances; /** * list of services to use by the application; defined in the pom; cannot be specified on the command line * * @parameter */ private List services; /** * list of domains to use by the application. * * @parameter expression="${domains}" */ private List domains; /** * Environment variables * * @parameter */ private Map env; /** * Merge existing env vars when updating the application * * @parameter expression="${cf.mergeEnv}" */ private Boolean mergeEnv; /** * Do not auto-start the application * * @parameter expression="${cf.no-start}" */ private Boolean noStart; /** * @parameter default-value="${localRepository}" * @readonly * @required */ protected ArtifactRepository localRepository; /** * @parameter default-value="${project.remoteArtifactRepositories}" * @readonly * @required */ * protected java.util.List remoteRepositories; /** * @component */ private ArtifactFactory artifactFactory; /** * @component */ private ArtifactResolver artifactResolver; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * If the application name was specified via the command line ({@link SystemProperties}) * then use that property. Otherwise return the appname as injected via Maven or * if appname is Null return the artifactId instead. * * @return Returns the appName, will never return Null. */ public String getAppname() { final String property = getCommandlineProperty(SystemProperties.APP_NAME); if (property != null) { return property; } else if (this.appname == null) { return getArtifactId(); } else { return appname; } } /** * Environment properties can only be specified from the maven pom. *

Example: *

	 * <env>
	 *   <JAVA_OPTS>-XX:MaxPermSize=256m</JAVA_OPTS>
	 * </env>
	 * 
* @return Returns the environment, may be null. */ public Map getEnv() { return this.env; } /** * If true, merge the application's existing env vars with those set in the plugin configuration when updating * an application. If not set, this property defaults to false * * @return Never null */ public boolean isMergeEnv() { return getBooleanValue(SystemProperties.MERGE_ENV, this.mergeEnv, DefaultConstants.MERGE_ENV); } /** * If the URL was specified via the command line ({@link SystemProperties}) * then that property is used. Otherwise return the appname. * * @return Returns the Cloud Foundry application url. */ public String getUrl() { final String property = getCommandlineProperty(SystemProperties.URL); if (property != null) { return property; } else { return this.url; } } /** * Validate that the path denoting a directory or file does exists. * * @param path Must not be null */ protected void validatePath(File path) { Assert.notNull(path, "A path could not be found to deploy. Please specify a path or artifact GAV."); final String absolutePath = path.getAbsolutePath(); if (!path.exists()) { throw new IllegalStateException(String.format("The file or directory does not exist at '%s'.", absolutePath)); } if (path.isDirectory() && path.list().length == 0) { throw new IllegalStateException(String.format("No files found in directory '%s'.", absolutePath)); } } /** * Returns the diskQuota parameter. * * @return Returns the configured disk quota choice */ public Integer getDiskQuota() { return getIntegerValue(SystemProperties.DISK_QUOTA, this.diskQuota); } /** * Returns the memory-parameter. * * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * If the value is not defined, null is returned. Triggering an empty value * to be sent to the Cloud Controller where its default will be used. * * @return Returns the configured memory choice */ public Integer getMemory() { return getIntegerValue(SystemProperties.MEMORY, this.memory); } /** * Specifies the file or directory that shall be pushed to Cloud Foundry. * * This property defaults to the Maven property * "${project.build.directory}/${project.build.finalName}.war" * * * @return null if not found. */ public File getPath() throws MojoExecutionException { final String property = getCommandlineProperty(SystemProperties.PATH); if (property != null) { final File path = new File(property); validatePath(path); return path; } else if (this.path != null) { return this.path; } else { File resolvedArtifact = this.getArtifact(); if (resolvedArtifact != null) { return resolvedArtifact; } return null; } } /** * Provides the File to deploy based on the GAV set in the "artifact" property. * * @return Returns null of no artifact specified. */ private File getArtifact() throws MojoExecutionException { if (artifact != null) { Artifact resolvedArtifact = createArtifactFromGAV(); try { artifactResolver.resolve(resolvedArtifact, remoteRepositories, localRepository ); } catch (ArtifactNotFoundException ex) { throw new MojoExecutionException("Could not find deploy artifact ["+artifact+"]", ex); } catch (ArtifactResolutionException ex) { throw new MojoExecutionException("Could not resolve deploy artifact ["+artifact+"]", ex); } return resolvedArtifact.getFile(); } return null; } Artifact createArtifactFromGAV() throws MojoExecutionException { String[] tokens = StringUtils.split(artifact, ":"); if (tokens.length < 4 || tokens.length > 5) { throw new MojoExecutionException( "Invalid artifact, you must specify groupId:artifactId:version:packaging[:classifier] " + artifact); } String groupId = tokens[0]; String artifactId = tokens[1]; String version = tokens[2]; String packaging = null; if (tokens.length >= 4) { packaging = tokens[3]; } String classifier = null; if (tokens.length == 5) { classifier = tokens[4]; } return (classifier == null ? artifactFactory.createBuildArtifact( groupId, artifactId, version, packaging ) : artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, packaging, classifier)); } /** * Returns the start command to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the command or null */ public String getCommand() { return getStringValue(SystemProperties.COMMAND, this.command); } /** * Returns the buildpack to use, if set. Otherwise Null is returned. public boolean isNoStart() { * If the parameter is set via the command line (aka system property) then * that value is used; if not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the buildpack or null */ public String getBuildpack() { return getStringValue(SystemProperties.BUILDPACK, this.buildpack); } /** * Returns the stack to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the stack or null */ public String getStack() { return getStringValue(SystemProperties.STACK, this.stack); } /** * Returns the health check timeout to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the health check timeout or null */ public Integer getHealthCheckTimeout() { return getIntegerValue(SystemProperties.HEALTH_CHECK_TIMEOUT, this.healthCheckTimeout); } /** * Returns the app startup timeout to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the app startup timeout or null */ public Integer getAppStartupTimeout() { return getIntegerValue(SystemProperties.APP_STARTUP_TIMEOUT, this.appStartupTimeout); } /** * Returns the number of instances-parameter, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties} * * @return Returns the number of configured instance or null */ public Integer getInstances() { return getIntegerValue(SystemProperties.INSTANCES, this.instances); } /** * Returns the services names that shall be bound to the application. * * @return list of services defined in the pom; otherwise null */ public List getServices() { return this.services; } /** * Returns the custom domain names that shall be created and added to the application. * * @return Never null */ public List getCustomDomains() { return this.domains == null ? new ArrayList(0) : this.domains; } /** * Returns the list of urls that shall be associated with the application. * * @return the list of urls, or null if not specified */ public List getUrls() { return this.urls; } /** * If true, this property specifies that the application shall not automatically * started upon "push". If not set, this property defaults to false * * @return Never null */ return getBooleanValue(SystemProperties.NO_START, this.noStart, DefaultConstants.NO_START); } public void createServices() throws MojoExecutionException { List currentServices = getClient().getServices(); List currentServicesNames = new ArrayList(currentServices.size()); for (CloudService currentService : currentServices) { currentServicesNames.add(currentService.getName()); } if (getServices() != null) { for (CloudServiceWithUserProvided service : getServices()) { if (currentServicesNames.contains(service.getName())) { getLog().debug(String.format("Service '%s' already exists", service.getName())); } else { getLog().info(String.format("Creating Service '%s'", service.getName())); Assert.configurationServiceNotNull(service, null); try { if (service.getLabel().equals("user-provided")) { service.setLabel(null); client.createUserProvidedService(service, service.getUserProvidedCredentials(), service.getSyslogDrainUrl()); } else { client.createService(service); } } catch (CloudFoundryException e) { throw new MojoExecutionException(String.format("Not able to create service '%s'.", service.getName())); } } } } } /** * Executes the actual war deployment to Cloud Foundry. * * @param client The Cloud Foundry client to use * @param file The file or directory to upload * @param appName The name of the application this file upload is for */ protected void uploadApplication(CloudFoundryClient client, File file, String appName) { boolean isDirectory = file.isDirectory(); if (isDirectory) { getLog().debug(String.format("Deploying directory %s to %s.", file.getAbsolutePath(), appName)); } else { getLog().debug(String.format("Deploying file %s (%s Kb) to %s.", file.getAbsolutePath(), file.length() / 1024, appName)); } try { client.uploadApplication(appName, file); } catch (IOException e) { throw new IllegalStateException("Error while uploading application.", e); } } protected void showStagingStatus(StartingInfo startingInfo) { if (startingInfo != null) { responseErrorHandler.addExpectedStatus(HttpStatus.NOT_FOUND); int offset = 0; String staging = client.getStagingLogs(startingInfo, offset); while (staging != null) { getLog().info(staging); offset += staging.length(); staging = client.getStagingLogs(startingInfo, offset); } responseErrorHandler.clearExpectedStatus(); } } protected void showStartingStatus(CloudApplication app) { getLog().info(String.format("Checking status of application '%s'", getAppname())); responseErrorHandler.addExpectedStatus(HttpStatus.BAD_REQUEST); long appStartupExpiry = getAppStartupExpiry(); while (System.currentTimeMillis() < appStartupExpiry) { List instances = getApplicationInstances(app); if (instances != null) { int expectedInstances = getExpectedInstances(instances); int runningInstances = getRunningInstances(instances); int flappingInstances = getFlappingInstances(instances); showInstancesStatus(instances, runningInstances, expectedInstances); if (flappingInstances > 0) break; if (runningInstances == expectedInstances) break; } } catch (InterruptedException e) { // ignore } } responseErrorHandler.clearExpectedStatus(); } protected void showInstancesStatus(List instances, int runningInstances, int expectedInstances) { Map stateCounts = new HashMap(); for (InstanceInfo instance : instances) { final String state = instance.getState().toString(); final Integer stateCount = stateCounts.get(state); if (stateCount == null) { stateCounts.put(state, 1); } else { stateCounts.put(state, stateCount + 1); } } List stateStrings = new ArrayList(); for (Map.Entry stateCount : stateCounts.entrySet()) { stateStrings.add(String.format("%s %s", stateCount.getValue(), stateCount.getKey().toLowerCase())); } getLog().info(String.format(" %d of %d instances running (%s)", runningInstances, expectedInstances, CommonUtils.collectionToCommaDelimitedString(stateStrings))); } protected void showStartResults(CloudApplication app, List uris) throws MojoExecutionException { List instances = getApplicationInstances(app); int expectedInstances = getExpectedInstances(instances); int runningInstances = getRunningInstances(instances); int flappingInstances = getFlappingInstances(instances); if (flappingInstances > 0) { throw new MojoExecutionException("Application start unsuccessful"); } else if (runningInstances == 0) { throw new MojoExecutionException("Application start timed out"); } else if (runningInstances > 0) { if (uris.isEmpty()) { getLog().info(String.format("Application '%s' is available", app.getName())); } else { getLog().info(String.format("Application '%s' is available at '%s'", app.getName(), CommonUtils.collectionToCommaDelimitedString(uris, "http://"))); } } } /** * Adds custom domains when provided in the pom file. */ protected void addDomains() { List domains = getClient().getDomains(); List currentDomains = new ArrayList(domains.size()); for (CloudDomain domain : domains) { currentDomains.add(domain.getName()); } for (String domain : getCustomDomains()) { if (!currentDomains.contains(domain)) { getClient().addDomain(domain); } } } private List getApplicationInstances(CloudApplication app) { InstancesInfo instancesInfo = client.getApplicationInstances(app); if (instancesInfo != null) { return instancesInfo.getInstances(); } return null; } private int getExpectedInstances(List instances) { return instances == null ? 0 : instances.size(); } private int getRunningInstances(List instances) { return getInstanceCount(instances, InstanceState.RUNNING); } private int getFlappingInstances(List instances) { return getInstanceCount(instances, InstanceState.FLAPPING); } private int getInstanceCount(List instances, InstanceState state) { int count = 0; if (instances != null) { for (InstanceInfo instance : instances) { if (instance.getState().equals(state)) { count++; } } } return count; } private List replaceRandomWords(List uris) { List finalUris = new ArrayList(uris.size()); for(String uri : uris) { if(uri.contains("${randomWord}")) { finalUris.add(uri.replace("${randomWord}", RandomStringUtils.randomAlphabetic(5))); } else { finalUris.add(uri); } } return finalUris; } protected List getAllUris() throws MojoExecutionException { Assert.configurationUrls(getUrl(), getUrls()); List uris; if (getUrl() != null) { uris = Arrays.asList(getUrl()); } else if (getUrls() != null) { uris = getUrls(); } else { String defaultUri = getAppname() + "." + getClient().getDefaultDomain().getName(); uris = Arrays.asList(defaultUri); } return replaceRandomWords(uris); } protected boolean urlsAreExplicitlySet() { return (getUrl() != null || getUrls() != null); } private long getAppStartupExpiry() { long timeout = System.currentTimeMillis(); if (getAppStartupTimeout() != null) { timeout += minutesToMillis(getAppStartupTimeout()); } else if (getHealthCheckTimeout() != null) { timeout += secondsToMillis(getHealthCheckTimeout()); } else { timeout += minutesToMillis(DEFAULT_APP_STARTUP_TIMEOUT); } return timeout; } private long minutesToMillis(Integer duration) { return TimeUnit.MINUTES.toMillis(duration); } private long secondsToMillis(Integer duration) { return TimeUnit.SECONDS.toMillis(duration); } private String getStringValue(SystemProperties propertyName, String configValue) { final String property = getCommandlineProperty(propertyName); return property != null ? property : configValue; } private Integer getIntegerValue(SystemProperties propertyName, Integer configValue) { final String property = getCommandlineProperty(propertyName); return property != null ? Integer.valueOf(property) : configValue; } /** private Integer getIntegerValue(SystemProperties propertyName, Integer configValue, Integer defaultValue) { final Integer value = getIntegerValue(propertyName, configValue); return value != null ? value : defaultValue; } private Boolean getBooleanValue(SystemProperties propertyName, Boolean configValue, Boolean defaultValue) { final String property = getCommandlineProperty(propertyName); if (property != null) { return Boolean.valueOf(property); } if (configValue != null) { return configValue; } return defaultValue; } ======= private static final int DEFAULT_APP_STARTUP_TIMEOUT = 5; /** * @parameter default-value="${localRepository}" * @readonly * @required */ protected ArtifactRepository localRepository; /** * @parameter default-value="${project.remoteArtifactRepositories}" * @readonly * @required */ protected java.util.List remoteRepositories; /** * The app startup timeout to use for the application. * * @parameter expression = "${cf.appStartupTimeout}" */ private Integer appStartupTimeout; /** * @parameter expression="${cf.appname}" */ private String appname; /** * A string of the form groupId:artifactId:version:packaging[:classifier]. * * @parameter expression = "${cf.artifact}" default-value="${project.groupId}:${project.artifactId}:${project * .version}:${project.packaging}" */ private String artifact; /** * @component */ private ArtifactFactory artifactFactory; /** * @component */ private ArtifactResolver artifactResolver; /** * The buildpack to use for the application. * * @parameter expression = "${cf.buildpack}" */ private String buildpack; /** * The start command to use for the application. * * @parameter expression = "${cf.command}" */ private String command; /** * Set the disk quota for the application * * @parameter expression="${cf.diskQuota}" */ private Integer diskQuota; /** * list of domains to use by the application. * * @parameter expression="${domains}" */ private List domains; /** * Environment variables * * @parameter expression="${cf.env}" */ private Map env = new HashMap(); /** * The health check timeout to use for the application. * * @parameter expression = "${cf.healthCheckTimeout}" */ private Integer healthCheckTimeout; /** * Set the expected number of instances * * @parameter expression="${cf.instances}" */ private Integer instances; * Set the memory reservation for the application * * @parameter expression="${cf.memory}" */ private Integer memory; /** * Merge existing env vars when updating the application * * @parameter expression="${cf.mergeEnv}" */ private Boolean mergeEnv; /** * Do not auto-start the application * * @parameter expression="${cf.no-start}" */ private Boolean noStart; /** * The path of one of the following: * *
  • War file to deploy
  • Zip or Jar file to deploy
  • Exploded War directory
  • *
  • Directory * containing a stand-alone application to deploy
* * @parameter expression = "${cf.path}" */ private File path; /** * list of services to use by the application. * * @parameter expression="${services}" */ private List services; /** * The stack to use for the application. * * @parameter expression = "${cf.stack}" */ private String stack; * @parameter expression="${cf.url}" */ private String url; /** * @parameter expression="${cf.urls}" */ private List urls; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public void createServices() throws MojoExecutionException { List currentServices = getClient().getServices(); List currentServicesNames = new ArrayList(currentServices.size()); for (CloudService currentService : currentServices) { currentServicesNames.add(currentService.getName()); } for (CloudServiceWithUserProvided service : getServices()) { if (currentServicesNames.contains(service.getName())) { getLog().debug(String.format("Service '%s' already exists", service.getName())); } else { getLog().info(String.format("Creating Service '%s'", service.getName())); Assert.configurationServiceNotNull(service, null); try { if (service.getLabel().equals("user-provided")) { service.setLabel(null); client.createUserProvidedService(service, service.getUserProvidedCredentials(), service .getSyslogDrainUrl()); } else { client.createService(service); } } catch (CloudFoundryException e) { throw new MojoExecutionException(String.format("Not able to create service '%s'.", service .getName())); } } } } /** * Returns the app startup timeout to use, if set. Otherwise Null is returned. If the parameter is set via the * command line (aka system property, then that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the app startup timeout or null */ public Integer getAppStartupTimeout() { return getIntegerValue(SystemProperties.APP_STARTUP_TIMEOUT, this.appStartupTimeout); } /** * If the application name was specified via the command line ({@link SystemProperties}) then use that property. * Otherwise return the appname as injected via Maven or if appname is Null return the artifactId instead. * * @return Returns the appName, will never return Null. */ public String getAppname() { final String property = getCommandlineProperty(SystemProperties.APP_NAME); if (property != null) { return property; } else if (this.appname == null) { return getArtifactId(); } else { return appname; } } /** * Returns the buildpack to use, if set. Otherwise Null is returned. If the parameter is set via the command line * (aka system property, then that value is used). If not the pom.xml configuration parameter is used, if * available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the buildpack or null */ public String getBuildpack() { return getStringValue(SystemProperties.BUILDPACK, this.buildpack); } /** * Returns the start command to use, if set. Otherwise Null is returned. If the parameter is set via the command * line (aka system property, then that value is used). If not the pom.xml configuration parameter is used, if * available. * return resolvedArtifact; * For a list of available properties see {@link SystemProperties}. * * @return Returns the command or null */ public String getCommand() { return getStringValue(SystemProperties.COMMAND, this.command); } /** * Returns the custom domain names that shall be created and added to the application. * * @return Never null */ public List getCustomDomains() { return this.domains == null ? new ArrayList(0) : this.domains; } /** * Returns the diskQuota parameter. * * @return Returns the configured disk quota choice */ public Integer getDiskQuota() { return getIntegerValue(SystemProperties.DISK_QUOTA, this.diskQuota); } /** * Environment properties can only be specified from the maven pom. * * Example: * * {code} -XX:MaxPermSize=256m {code} * * @return Returns the env, will never return Null. */ public Map getEnv() { return this.env; } /** * Returns the health check timeout to use, if set. Otherwise Null is returned. If the parameter is set via the * command line (aka system property, then that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the health check timeout or null */ public Integer getHealthCheckTimeout() { return getIntegerValue(SystemProperties.HEALTH_CHECK_TIMEOUT, this.healthCheckTimeout); } /** * Returns the number of instances-parameter, if set. Otherwise Null is returned. If the parameter is set via the * command line (aka system property, then that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties} * * @return Returns the number of configured instance or null */ public Integer getInstances() { String groupId = tokens[0]; return getIntegerValue(SystemProperties.INSTANCES, this.instances, DefaultConstants.DEFAULT_INSTANCE); } /** * Returns the memory-parameter. * * If the parameter is set via the command line (aka system property, then that value is used). If not the pom.xml * configuration parameter is used, if available. * * If the value is not defined, null is returned. Triggering an empty value to be sent to the Cloud Controller * where its default will be used. * * @return Returns the configured memory choice */ public Integer getMemory() { return getIntegerValue(SystemProperties.MEMORY, this.memory); } /** * Specifies the file or directory that shall be pushed to Cloud Foundry. * * This property defaults to the Maven property "${project.build.directory}/${project.build.finalName}.war" * * @return null if not found. */ public File getPath() throws MojoExecutionException { final String property = getCommandlineProperty(SystemProperties.PATH); if (property != null) { final File path = new File(property); validatePath(path); return path; } else if (this.path != null) { return this.path; } else { File resolvedArtifact = this.getArtifact(); if (resolvedArtifact != null) { } return null; } } /** * Returns the services names that shall be bound to the application. * * @return Never null */ public List getServices() { return this.services == null ? new ArrayList(0) : this.services; } /** * Returns the stack to use, if set. Otherwise Null is returned. If the parameter is set via the command line (aka * system property, then that value is used). If not the pom.xml configuration parameter is used, if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the stack or null */ public String getStack() { return getStringValue(SystemProperties.STACK, this.stack); } /** * If the URL was specified via the command line ({@link SystemProperties}) then that property is used. Otherwise * return the appname. * * @return Returns the Cloud Foundry application url. */ public String getUrl() { final String property = getCommandlineProperty(SystemProperties.URL); if (property != null) { return property; } else { return this.url; } } /** * Returns the list of urls that shall be associated with the application. * * @return Never null */ public List getUrls() { return this.urls == null ? new ArrayList(0) : this.urls; } /** * If true, merge the application's existing env vars with those set in the plugin configuration when updating an * application. If not set, this property defaults to false * * @return Never null */ public Boolean isMergeEnv() { return getBooleanValue(SystemProperties.MERGE_ENV, this.mergeEnv, DefaultConstants.MERGE_ENV); } /** * If true, this property specifies that the application shall not automatically started upon "push". If not set, * this property defaults to false * * @return Never null */ public Boolean isNoStart() { return getBooleanValue(SystemProperties.NO_START, this.noStart, DefaultConstants.NO_START); } /** * Adds custom domains when provided in the pom file. */ protected void addDomains() { List domains = getClient().getDomains(); List currentDomains = new ArrayList(domains.size()); for (CloudDomain domain : domains) { currentDomains.add(domain.getName()); } for (String domain : getCustomDomains()) { if (!currentDomains.contains(domain)) { getClient().addDomain(domain); } } } protected List getAllUris() throws MojoExecutionException { Assert.configurationUrls(getUrl(), getUrls()); List uris; if (getUrl() != null) { uris = Arrays.asList(getUrl()); } else if (!getUrls().isEmpty()) { uris = getUrls(); } else { String defaultUri = getAppname() + "." + getClient().getDefaultDomain().getName(); uris = Arrays.asList(defaultUri); } return replaceRandomWords(uris); } protected void showInstancesStatus(List instances, int runningInstances, int expectedInstances) { Map stateCounts = new HashMap(); for (InstanceInfo instance : instances) { final String state = instance.getState().toString(); final Integer stateCount = stateCounts.get(state); if (stateCount == null) { stateCounts.put(state, 1); } else { stateCounts.put(state, stateCount + 1); } } List stateStrings = new ArrayList(); for (Map.Entry stateCount : stateCounts.entrySet()) { stateStrings.add(String.format("%s %s", stateCount.getValue(), stateCount.getKey().toLowerCase())); } getLog().info(String.format(" %d of %d instances running (%s)", runningInstances, expectedInstances, CommonUtils.collectionToCommaDelimitedString(stateStrings))); } protected void showStagingStatus(StartingInfo startingInfo) { if (startingInfo != null) { responseErrorHandler.addExpectedStatus(HttpStatus.NOT_FOUND); int offset = 0; String staging = client.getStagingLogs(startingInfo, offset); while (staging != null) { getLog().info(staging); offset += staging.length(); staging = client.getStagingLogs(startingInfo, offset); } responseErrorHandler.clearExpectedStatus(); } } protected void showStartResults(CloudApplication app, List uris) throws MojoExecutionException { List instances = getApplicationInstances(app); int expectedInstances = getExpectedInstances(instances); int runningInstances = getRunningInstances(instances); int flappingInstances = getFlappingInstances(instances); if (flappingInstances > 0) { throw new MojoExecutionException("Application start unsuccessful"); } else if (runningInstances == 0) { throw new MojoExecutionException("Application start timed out"); } else if (runningInstances > 0) { if (uris.isEmpty()) { getLog().info(String.format("Application '%s' is available", app.getName())); } else { getLog().info(String.format("Application '%s' is available at '%s'", app.getName(), CommonUtils.collectionToCommaDelimitedString(uris, "http://"))); } } } protected void showStartingStatus(CloudApplication app) { getLog().info(String.format("Checking status of application '%s'", getAppname())); responseErrorHandler.addExpectedStatus(HttpStatus.BAD_REQUEST); long appStartupExpiry = getAppStartupExpiry(); while (System.currentTimeMillis() < appStartupExpiry) { List instances = getApplicationInstances(app); if (instances != null) { int expectedInstances = getExpectedInstances(instances); int runningInstances = getRunningInstances(instances); int flappingInstances = getFlappingInstances(instances); showInstancesStatus(instances, runningInstances, expectedInstances); if (flappingInstances > 0) break; if (runningInstances == expectedInstances) break; } try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore } } responseErrorHandler.clearExpectedStatus(); } /** * Executes the actual war deployment to Cloud Foundry. * * @param client The Cloud Foundry client to use * @param file The file or directory to upload * @param appName The name of the application this file upload is for */ protected void uploadApplication(CloudFoundryClient client, File file, String appName) { boolean isDirectory = file.isDirectory(); if (isDirectory) { getLog().debug(String.format("Deploying directory %s to %s.", file.getAbsolutePath(), appName)); } else { getLog().debug(String.format("Deploying file %s (%s Kb) to %s.", file.getAbsolutePath(), file.length() / 1024, appName)); } try { client.uploadApplication(appName, file); } catch (IOException e) { throw new IllegalStateException("Error while uploading application.", e); } } /** * Validate that the path denoting a directory or file does exists. * * @param path Must not be null */ protected void validatePath(File path) { Assert.notNull(path, "A path could not be found to deploy. Please specify a path or artifact GAV."); final String absolutePath = path.getAbsolutePath(); if (!path.exists()) { throw new IllegalStateException(String.format("The file or directory does not exist at '%s'.", absolutePath)); } if (path.isDirectory() && path.list().length == 0) { throw new IllegalStateException(String.format("No files found in directory '%s'.", absolutePath)); } } Artifact createArtifactFromGAV() throws MojoExecutionException { String[] tokens = StringUtils.split(artifact, ":"); if (tokens.length < 4 || tokens.length > 5) { throw new MojoExecutionException( "Invalid artifact, you must specify groupId:artifactId:version:packaging[:classifier] " + artifact); } String artifactId = tokens[1]; String version = tokens[2]; String packaging = null; if (tokens.length >= 4) { packaging = tokens[3]; } String classifier = null; if (tokens.length == 5) { classifier = tokens[4]; } return (classifier == null ? artifactFactory.createBuildArtifact(groupId, artifactId, version, packaging) : artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, packaging, classifier)); } private long getAppStartupExpiry() { long timeout = System.currentTimeMillis(); if (getAppStartupTimeout() != null) { timeout += minutesToMillis(getAppStartupTimeout()); } else if (getHealthCheckTimeout() != null) { timeout += secondsToMillis(getHealthCheckTimeout()); } else { timeout += minutesToMillis(DEFAULT_APP_STARTUP_TIMEOUT); } return timeout; } private List getApplicationInstances(CloudApplication app) { InstancesInfo instancesInfo = client.getApplicationInstances(app); if (instancesInfo != null) { return instancesInfo.getInstances(); } return null; } /** * Provides the File to deploy based on the GAV set in the "artifact" property. * @return Returns null of no artifact specified. */ private File getArtifact() throws MojoExecutionException { if (artifact != null) { Artifact resolvedArtifact = createArtifactFromGAV(); try { artifactResolver.resolve(resolvedArtifact, remoteRepositories, localRepository); } catch (ArtifactNotFoundException ex) { throw new MojoExecutionException("Could not find deploy artifact [" + artifact + "]", ex); } catch (ArtifactResolutionException ex) { throw new MojoExecutionException("Could not resolve deploy artifact [" + artifact + "]", ex); } return resolvedArtifact.getFile(); } return null; } private Boolean getBooleanValue(SystemProperties propertyName, Boolean configValue, Boolean defaultValue) { final String property = getCommandlineProperty(propertyName); if (property != null) { return Boolean.valueOf(property); } if (configValue != null) { return configValue; } return defaultValue; } private int getExpectedInstances(List instances) { return instances == null ? 0 : instances.size(); } private int getFlappingInstances(List instances) { return getInstanceCount(instances, InstanceState.FLAPPING); } private int getInstanceCount(List instances, InstanceState state) { int count = 0; if (instances != null) { for (InstanceInfo instance : instances) { if (instance.getState().equals(state)) { count++; } } } return count; } private Integer getIntegerValue(SystemProperties propertyName, Integer configValue) { final String property = getCommandlineProperty(propertyName); return property != null ? Integer.valueOf(property) : configValue; } private Integer getIntegerValue(SystemProperties propertyName, Integer configValue, Integer defaultValue) { final Integer value = getIntegerValue(propertyName, configValue); return value != null ? value : defaultValue; } private int getRunningInstances(List instances) { return getInstanceCount(instances, InstanceState.RUNNING); } private String getStringValue(SystemProperties propertyName, String configValue) { final String property = getCommandlineProperty(propertyName); return property != null ? property : configValue; } private long minutesToMillis(Integer duration) { return TimeUnit.MINUTES.toMillis(duration); } private List replaceRandomWords(List uris) { List finalUris = new ArrayList(uris.size()); for (String uri : uris) { if (uri.contains("${randomWord}")) { finalUris.add(uri.replace("${randomWord}", RandomStringUtils.randomAlphabetic(5))); } else { finalUris.add(uri); } } return finalUris; } private long secondsToMillis(Integer duration) { return TimeUnit.SECONDS.toMillis(duration); } >>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d }
Solution content
 */
@SuppressWarnings("UnusedDeclaration")
abstract class AbstractApplicationAwareCloudFoundryMojo extends AbstractCloudFoundryMojo {
	private static final int DEFAULT_APP_STARTUP_TIMEOUT = 5;

	/**
	 * @parameter expression="${cf.appname}"
	 */
	private String appname;

	/**
	 * @parameter expression="${cf.url}"
	 */
	private String url;

	/**
	 * @parameter
	 */
	private List urls;

	/**
	 * A string of the form groupId:artifactId:version:packaging[:classifier].
	 * @parameter expression = "${cf.artifact}" default-value="${project.groupId}:${project.artifactId}:${project.version}:${project.packaging}"
	 */
	private String artifact;

	/**
	 * The path of one of the following:
	 *
	 * 
    *
  • War file to deploy
  • *
  • Zip or Jar file to deploy
  • *
  • Exploded War directory
  • *
  • Directory containing a stand-alone application to deploy
  • *
* * @parameter expression = "${cf.path}" */ private File path; /** * The start command to use for the application. * * @parameter expression = "${cf.command}" */ private String command; /** * The buildpack to use for the application. * * @parameter expression = "${cf.buildpack}" */ private String buildpack; /** * The stack to use for the application. * * @parameter expression = "${cf.stack}" */ private String stack; /** * The health check timeout to use for the application. * * @parameter expression = "${cf.healthCheckTimeout}" */ private Integer healthCheckTimeout; /** * The app startup timeout to use for the application. * * @parameter expression = "${cf.appStartupTimeout}" */ private Integer appStartupTimeout; /** * Set the disk quota for the application * * @parameter expression="${cf.diskQuota}" */ private Integer diskQuota; /** * Set the memory reservation for the application * * @parameter expression="${cf.memory}" */ private Integer memory; /** * Set the expected number of instances * * @parameter expression="${cf.instances}" */ private Integer instances; /** * list of services to use by the application; defined in the pom; cannot be specified on the command line * * @parameter */ private List services; /** * list of domains to use by the application. * * @parameter expression="${domains}" */ private List domains; /** * Environment variables * * @parameter */ private Map env; /** * Merge existing env vars when updating the application * * @parameter expression="${cf.mergeEnv}" */ private Boolean mergeEnv; /** * Do not auto-start the application * * @parameter expression="${cf.no-start}" */ private Boolean noStart; /** * @parameter default-value="${localRepository}" * @readonly * @required */ protected ArtifactRepository localRepository; /** * @parameter default-value="${project.remoteArtifactRepositories}" * @readonly * @required */ protected java.util.List remoteRepositories; /** * @component */ private ArtifactFactory artifactFactory; /** * @component */ private ArtifactResolver artifactResolver; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * If the application name was specified via the command line ({@link SystemProperties}) * then use that property. Otherwise return the appname as injected via Maven or * if appname is Null return the artifactId instead. * * @return Returns the appName, will never return Null. */ public String getAppname() { final String property = getCommandlineProperty(SystemProperties.APP_NAME); if (property != null) { return property; } else if (this.appname == null) { return getArtifactId(); } else { return appname; } } /** * Environment properties can only be specified from the maven pom. *

Example: *

	 * <env>
	 *   <JAVA_OPTS>-XX:MaxPermSize=256m</JAVA_OPTS>
	 * </env>
	 * 
* @return Returns the environment, may be null. */ public Map getEnv() { return this.env; } /** * If true, merge the application's existing env vars with those set in the plugin configuration when updating * an application. If not set, this property defaults to false * * @return Never null */ public boolean isMergeEnv() { return getBooleanValue(SystemProperties.MERGE_ENV, this.mergeEnv, DefaultConstants.MERGE_ENV); } /** * If the URL was specified via the command line ({@link SystemProperties}) * then that property is used. Otherwise return the appname. * * @return Returns the Cloud Foundry application url. */ public String getUrl() { final String property = getCommandlineProperty(SystemProperties.URL); if (property != null) { return property; } else { return this.url; } } /** * Validate that the path denoting a directory or file does exists. * * @param path Must not be null */ protected void validatePath(File path) { Assert.notNull(path, "A path could not be found to deploy. Please specify a path or artifact GAV."); final String absolutePath = path.getAbsolutePath(); if (!path.exists()) { throw new IllegalStateException(String.format("The file or directory does not exist at '%s'.", absolutePath)); } if (path.isDirectory() && path.list().length == 0) { throw new IllegalStateException(String.format("No files found in directory '%s'.", absolutePath)); } } /** * Returns the diskQuota parameter. * * @return Returns the configured disk quota choice */ public Integer getDiskQuota() { return getIntegerValue(SystemProperties.DISK_QUOTA, this.diskQuota); } /** * Returns the memory-parameter. * * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * If the value is not defined, null is returned. Triggering an empty value * to be sent to the Cloud Controller where its default will be used. * * @return Returns the configured memory choice */ public Integer getMemory() { return getIntegerValue(SystemProperties.MEMORY, this.memory); } /** * Specifies the file or directory that shall be pushed to Cloud Foundry. * * This property defaults to the Maven property * "${project.build.directory}/${project.build.finalName}.war" * * * @return null if not found. */ public File getPath() throws MojoExecutionException { final String property = getCommandlineProperty(SystemProperties.PATH); if (property != null) { final File path = new File(property); validatePath(path); return path; } else if (this.path != null) { return this.path; } else { File resolvedArtifact = this.getArtifact(); if (resolvedArtifact != null) { return resolvedArtifact; } return null; } } /** * Provides the File to deploy based on the GAV set in the "artifact" property. * * @return Returns null of no artifact specified. */ private File getArtifact() throws MojoExecutionException { if (artifact != null) { Artifact resolvedArtifact = createArtifactFromGAV(); try { artifactResolver.resolve(resolvedArtifact, remoteRepositories, localRepository ); } catch (ArtifactNotFoundException ex) { throw new MojoExecutionException("Could not find deploy artifact ["+artifact+"]", ex); } catch (ArtifactResolutionException ex) { throw new MojoExecutionException("Could not resolve deploy artifact ["+artifact+"]", ex); } return resolvedArtifact.getFile(); } return null; } Artifact createArtifactFromGAV() throws MojoExecutionException { String[] tokens = StringUtils.split(artifact, ":"); if (tokens.length < 4 || tokens.length > 5) { throw new MojoExecutionException( "Invalid artifact, you must specify groupId:artifactId:version:packaging[:classifier] " + artifact); } String groupId = tokens[0]; String artifactId = tokens[1]; String version = tokens[2]; String packaging = null; if (tokens.length >= 4) { packaging = tokens[3]; } String classifier = null; if (tokens.length == 5) { classifier = tokens[4]; } return (classifier == null ? artifactFactory.createBuildArtifact( groupId, artifactId, version, packaging ) : artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, packaging, classifier)); } /** * Returns the start command to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the command or null */ public String getCommand() { return getStringValue(SystemProperties.COMMAND, this.command); } /** * Returns the buildpack to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property) then * that value is used; if not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the buildpack or null */ public String getBuildpack() { return getStringValue(SystemProperties.BUILDPACK, this.buildpack); } /** * Returns the stack to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the stack or null */ public String getStack() { return getStringValue(SystemProperties.STACK, this.stack); } /** * Returns the health check timeout to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the health check timeout or null */ public Integer getHealthCheckTimeout() { return getIntegerValue(SystemProperties.HEALTH_CHECK_TIMEOUT, this.healthCheckTimeout); } /** * Returns the app startup timeout to use, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties}. * * @return Returns the app startup timeout or null */ public Integer getAppStartupTimeout() { return getIntegerValue(SystemProperties.APP_STARTUP_TIMEOUT, this.appStartupTimeout); } /** * Returns the number of instances-parameter, if set. Otherwise Null is returned. * If the parameter is set via the command line (aka system property, then * that value is used). If not the pom.xml configuration parameter is used, * if available. * * For a list of available properties see {@link SystemProperties} * * @return Returns the number of configured instance or null */ public Integer getInstances() { return getIntegerValue(SystemProperties.INSTANCES, this.instances); } /** * Returns the services names that shall be bound to the application. * * @return list of services defined in the pom; otherwise null */ public List getServices() { return this.services; } /** * Returns the custom domain names that shall be created and added to the application. * * @return Never null */ public List getCustomDomains() { return this.domains == null ? new ArrayList(0) : this.domains; } /** * Returns the list of urls that shall be associated with the application. * * @return the list of urls, or null if not specified */ public List getUrls() { return this.urls; } /** * If true, this property specifies that the application shall not automatically * started upon "push". If not set, this property defaults to false * * @return Never null */ public boolean isNoStart() { return getBooleanValue(SystemProperties.NO_START, this.noStart, DefaultConstants.NO_START); } public void createServices() throws MojoExecutionException { List currentServices = getClient().getServices(); List currentServicesNames = new ArrayList(currentServices.size()); for (CloudService currentService : currentServices) { currentServicesNames.add(currentService.getName()); } if (getServices() != null) { for (CloudServiceWithUserProvided service : getServices()) { if (currentServicesNames.contains(service.getName())) { getLog().debug(String.format("Service '%s' already exists", service.getName())); } else { getLog().info(String.format("Creating Service '%s'", service.getName())); Assert.configurationServiceNotNull(service, null); try { if (service.getLabel().equals("user-provided")) { service.setLabel(null); client.createUserProvidedService(service, service.getUserProvidedCredentials(), service.getSyslogDrainUrl()); } else { client.createService(service); } } catch (CloudFoundryException e) { throw new MojoExecutionException(String.format("Not able to create service '%s'.", service.getName())); } } } } } /** * Executes the actual war deployment to Cloud Foundry. * * @param client The Cloud Foundry client to use * @param file The file or directory to upload * @param appName The name of the application this file upload is for */ protected void uploadApplication(CloudFoundryClient client, File file, String appName) { boolean isDirectory = file.isDirectory(); if (isDirectory) { getLog().debug(String.format("Deploying directory %s to %s.", file.getAbsolutePath(), appName)); } else { getLog().debug(String.format("Deploying file %s (%s Kb) to %s.", file.getAbsolutePath(), file.length() / 1024, appName)); } try { client.uploadApplication(appName, file); } catch (IOException e) { throw new IllegalStateException("Error while uploading application.", e); } } protected void showStagingStatus(StartingInfo startingInfo) { if (startingInfo != null) { responseErrorHandler.addExpectedStatus(HttpStatus.NOT_FOUND); int offset = 0; String staging = client.getStagingLogs(startingInfo, offset); while (staging != null) { getLog().info(staging); offset += staging.length(); staging = client.getStagingLogs(startingInfo, offset); } responseErrorHandler.clearExpectedStatus(); } } protected void showStartingStatus(CloudApplication app) { getLog().info(String.format("Checking status of application '%s'", getAppname())); responseErrorHandler.addExpectedStatus(HttpStatus.BAD_REQUEST); long appStartupExpiry = getAppStartupExpiry(); while (System.currentTimeMillis() < appStartupExpiry) { List instances = getApplicationInstances(app); if (instances != null) { int expectedInstances = getExpectedInstances(instances); int runningInstances = getRunningInstances(instances); int flappingInstances = getFlappingInstances(instances); showInstancesStatus(instances, runningInstances, expectedInstances); if (flappingInstances > 0) break; if (runningInstances == expectedInstances) break; } try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore } } responseErrorHandler.clearExpectedStatus(); } protected void showInstancesStatus(List instances, int runningInstances, int expectedInstances) { Map stateCounts = new HashMap(); for (InstanceInfo instance : instances) { final String state = instance.getState().toString(); final Integer stateCount = stateCounts.get(state); if (stateCount == null) { stateCounts.put(state, 1); } else { stateCounts.put(state, stateCount + 1); } } List stateStrings = new ArrayList(); for (Map.Entry stateCount : stateCounts.entrySet()) { stateStrings.add(String.format("%s %s", stateCount.getValue(), stateCount.getKey().toLowerCase())); } getLog().info(String.format(" %d of %d instances running (%s)", runningInstances, expectedInstances, CommonUtils.collectionToCommaDelimitedString(stateStrings))); } protected void showStartResults(CloudApplication app, List uris) throws MojoExecutionException { List instances = getApplicationInstances(app); int expectedInstances = getExpectedInstances(instances); int runningInstances = getRunningInstances(instances); int flappingInstances = getFlappingInstances(instances); if (flappingInstances > 0) { throw new MojoExecutionException("Application start unsuccessful"); } else if (runningInstances == 0) { throw new MojoExecutionException("Application start timed out"); } else if (runningInstances > 0) { if (uris.isEmpty()) { getLog().info(String.format("Application '%s' is available", app.getName())); } else { getLog().info(String.format("Application '%s' is available at '%s'", app.getName(), CommonUtils.collectionToCommaDelimitedString(uris, "http://"))); } } } /** * Adds custom domains when provided in the pom file. */ protected void addDomains() { List domains = getClient().getDomains(); List currentDomains = new ArrayList(domains.size()); for (CloudDomain domain : domains) { currentDomains.add(domain.getName()); } for (String domain : getCustomDomains()) { if (!currentDomains.contains(domain)) { getClient().addDomain(domain); } } } private List getApplicationInstances(CloudApplication app) { InstancesInfo instancesInfo = client.getApplicationInstances(app); if (instancesInfo != null) { return instancesInfo.getInstances(); } return null; } private int getExpectedInstances(List instances) { return instances == null ? 0 : instances.size(); } private int getRunningInstances(List instances) { return getInstanceCount(instances, InstanceState.RUNNING); } private int getFlappingInstances(List instances) { return getInstanceCount(instances, InstanceState.FLAPPING); } private int getInstanceCount(List instances, InstanceState state) { int count = 0; if (instances != null) { for (InstanceInfo instance : instances) { if (instance.getState().equals(state)) { count++; } } } return count; } private List replaceRandomWords(List uris) { List finalUris = new ArrayList(uris.size()); for(String uri : uris) { if(uri.contains("${randomWord}")) { finalUris.add(uri.replace("${randomWord}", RandomStringUtils.randomAlphabetic(5))); } else { finalUris.add(uri); } } return finalUris; } protected List getAllUris() throws MojoExecutionException { Assert.configurationUrls(getUrl(), getUrls()); List uris; if (getUrl() != null) { uris = Arrays.asList(getUrl()); } else if (getUrls() != null) { uris = getUrls(); } else { String defaultUri = getAppname() + "." + getClient().getDefaultDomain().getName(); uris = Arrays.asList(defaultUri); } return replaceRandomWords(uris); } protected boolean urlsAreExplicitlySet() { return (getUrl() != null || getUrls() != null); } private long getAppStartupExpiry() { long timeout = System.currentTimeMillis(); if (getAppStartupTimeout() != null) { timeout += minutesToMillis(getAppStartupTimeout()); } else if (getHealthCheckTimeout() != null) { timeout += secondsToMillis(getHealthCheckTimeout()); } else { timeout += minutesToMillis(DEFAULT_APP_STARTUP_TIMEOUT); } return timeout; } private long minutesToMillis(Integer duration) { return TimeUnit.MINUTES.toMillis(duration); } private long secondsToMillis(Integer duration) { return TimeUnit.SECONDS.toMillis(duration); } private String getStringValue(SystemProperties propertyName, String configValue) { final String property = getCommandlineProperty(propertyName); return property != null ? property : configValue; } private Integer getIntegerValue(SystemProperties propertyName, Integer configValue) { final String property = getCommandlineProperty(propertyName); return property != null ? Integer.valueOf(property) : configValue; } private Integer getIntegerValue(SystemProperties propertyName, Integer configValue, Integer defaultValue) { final Integer value = getIntegerValue(propertyName, configValue); return value != null ? value : defaultValue; } private Boolean getBooleanValue(SystemProperties propertyName, Boolean configValue, Boolean defaultValue) { final String property = getCommandlineProperty(propertyName); if (property != null) { return Boolean.valueOf(property); } if (configValue != null) { return configValue; } return defaultValue; } }
File
AbstractApplicationAwareCloudFoundryMojo.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
Method declaration
Method invocation
Chunk
Conflicting content
			try {
        addDomains();
 */
public class AbstractPush extends AbstractApplicationAwareCloudFoundryMojo {

<<<<<<< HEAD
	@Override

	protected void doExecute() throws MojoExecutionException {
		final String appname = getAppname();
		final String command = getCommand();
		final String buildpack = getBuildpack();
		final String stack = getStack();
		final Integer healthCheckTimeout = getHealthCheckTimeout();
		final Map env = getEnv();
		final Integer instances = getInstances();
		final Integer memory = getMemory();
		final Integer disk = getDiskQuota();
		final File path = getPath();
		final List uris = getAllUris();
		final List serviceNames = getServiceNames();

		validatePath(path);

		addDomains();

		createServices();

		getLog().debug(String.format(
				"Pushing App - Appname: %s," +
						" Command: %s," +
						" Env: %s," +
						" Instances: %s," +
						" Memory: %s," +
						" DiskQuota: %s," +
						" Path: %s," +
						" Services: %s," +
						" Uris: %s,",
				appname, command, env, instances, memory, disk, path, serviceNames, uris));

		getLog().info(String.format("Creating application '%s'", appname));

		createApplication(appname, command, buildpack, stack, healthCheckTimeout, disk, memory, uris, serviceNames, env);

		getLog().info(String.format("Uploading '%s'", path));

		try {
			uploadApplication(getClient(), path, appname);
		} catch (CloudFoundryException e) {
			throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: '%s'. Description: '%s'",
					getAppname(), e.getMessage(), e.getDescription()), e);
		}

		if (instances != null) {
			getLog().debug("Setting the number of instances to " + instances);

			try {
				getClient().updateApplicationInstances(appname, instances);
			} catch (CloudFoundryException e) {
				throw new MojoExecutionException(String.format("Error while setting number of instances for application '%s'. Error message: '%s'. Description: '%s'",
						getAppname(), e.getMessage(), e.getDescription()), e);
			}
		}

		if (!isNoStart()) {
			getLog().info("Starting application");

				final StartingInfo startingInfo = getClient().startApplication(appname);
				showStagingStatus(startingInfo);

				final CloudApplication app = getClient().getApplication(appname);
				showStartingStatus(app);
				showStartResults(app, uris);
			} catch (CloudFoundryException e) {
				throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: '%s'. Description: '%s'",
						getAppname(), e.getMessage(), e.getDescription()), e);
			}
		}
	}

	private void createApplication(String appname, String command, String buildpack, String stack, Integer healthCheckTimeout,
	                               Integer diskQuota, Integer memory, List uris, List serviceNames, Map env) throws MojoExecutionException {
		CloudApplication application = null;
		try {
			application = client.getApplication(appname);
		} catch (CloudFoundryException e) {
			if (!HttpStatus.NOT_FOUND.equals(e.getStatusCode())) {
				throw new MojoExecutionException(String.format("Error while checking for existing application '%s'. Error message: '%s'. Description: '%s'",
						appname, e.getMessage(), e.getDescription()), e);
			}
		}

		try {
			final Staging staging = new Staging(command, buildpack, stack, healthCheckTimeout);
			if (application == null) {
				client.createApplication(appname, staging, diskQuota, memory, uris, serviceNames);
				client.updateApplicationEnv(appname, env);
			} else {
				client.stopApplication(appname);
				client.updateApplicationStaging(appname, staging);
				if (memory != null) {
					client.updateApplicationMemory(appname, memory);
				}
				if (diskQuota != null) {
					client.updateApplicationDiskQuota(appname, diskQuota);
				}
				if (urlsAreExplicitlySet()) {
					client.updateApplicationUris(appname, uris);
				}
				if (null != getServices()) {
					client.updateApplicationServices(appname, serviceNames);
				}
				if (null != env) {
					client.updateApplicationEnv(appname, getMergedEnv(application, env));
				}
			}
		} catch (CloudFoundryException e) {
			throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: '%s'. Description: '%s'",
					getAppname(), e.getMessage(), e.getDescription()), e);
		}
	}

	private Map getMergedEnv(CloudApplication application, Map env) {
		if (!isMergeEnv()) {
			return env;
		}

		Map mergedEnv = application.getEnvAsMap();
		mergedEnv.putAll(env);

		return mergedEnv;
	}

	private List getServiceNames() {
		final List services = getServices();
		List serviceNames = new ArrayList();

		if (services != null) {
			for (CloudService service : services) {
				serviceNames.add(service.getName());
			}
		}
		return serviceNames;
	}
=======
    @Override
    protected void doExecute() throws MojoExecutionException {
        final String appname = getAppname();
        final String command = getCommand();
        final String buildpack = getBuildpack();
        final String stack = getStack();
        final Integer healthCheckTimeout = getHealthCheckTimeout();
        final Map env = getEnv();
        final Integer instances = getInstances();
        final Integer memory = getMemory();
        final Integer disk = getDiskQuota();
        final File path = getPath();
        final List uris = getAllUris();
        final List serviceNames = getServiceNames();

        validatePath(path);

        createServices();

        getLog().debug(String.format(
                "Pushing App - Appname: %s," +
                        " Command: %s," +
                        " Env: %s," +
                        " Instances: %s," +
                        " Memory: %s," +
                        " DiskQuota: %s," +
                        " Path: %s," +
                        " Services: %s," +
                        " Uris: %s,",
                appname, command, env, instances, memory, disk, path, serviceNames, uris));

        getLog().info(String.format("Creating application '%s'", appname));

        createApplication(appname, command, buildpack, stack, healthCheckTimeout, disk, memory, uris, serviceNames,
                env);

        getLog().info(String.format("Uploading '%s'", path));

        try {
            uploadApplication(getClient(), path, appname);
        } catch (CloudFoundryException e) {
            throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: " +
                    "'%s'. Description: '%s'",
                    getAppname(), e.getMessage(), e.getDescription()), e);
        }

        if (instances != null) {
            getLog().debug("Setting the number of instances to " + instances);

            try {
                getClient().updateApplicationInstances(appname, instances);
            } catch (CloudFoundryException e) {
                throw new MojoExecutionException(String.format("Error while setting number of instances for " +
                        "application '%s'. Error message: '%s'. Description: '%s'",
                        getAppname(), e.getMessage(), e.getDescription()), e);
            }
        }

        if (!isNoStart()) {
            getLog().info("Starting application");

            try {
                final StartingInfo startingInfo = getClient().startApplication(appname);
                showStagingStatus(startingInfo);

                final CloudApplication app = getClient().getApplication(appname);
                showStartingStatus(app);
                showStartResults(app, uris);
            } catch (CloudFoundryException e) {
                throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message:" +
                        " '%s'. Description: '%s'",
                        getAppname(), e.getMessage(), e.getDescription()), e);
            }
        }
    }

    private void createApplication(String appname, String command, String buildpack, String stack, Integer
            healthCheckTimeout,
                                   Integer diskQuota, Integer memory, List uris, List serviceNames,
                                   Map env) throws MojoExecutionException {
        CloudApplication application = null;
        try {
            application = client.getApplication(appname);
        } catch (CloudFoundryException e) {
            if (!HttpStatus.NOT_FOUND.equals(e.getStatusCode())) {
                throw new MojoExecutionException(String.format("Error while checking for existing application '%s'. " +
                        "Error message: '%s'. Description: '%s'",
                        appname, e.getMessage(), e.getDescription()), e);
            }
        }

        try {
            final Staging staging = new Staging(command, buildpack, stack, healthCheckTimeout);
            if (application == null) {
                client.createApplication(appname, staging, diskQuota, memory, uris, serviceNames);
                client.updateApplicationEnv(appname, env);
            } else {
                client.stopApplication(appname);
                client.updateApplicationStaging(appname, staging);
                if (memory != null) {
                    client.updateApplicationMemory(appname, memory);
                }
                if (diskQuota != null) {
                    client.updateApplicationDiskQuota(appname, diskQuota);
                }
                client.updateApplicationUris(appname, uris);
                client.updateApplicationServices(appname, serviceNames);
                client.updateApplicationEnv(appname, getMergedEnv(application, env));
            }
        } catch (CloudFoundryException e) {
            throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: '%s'. Description: '%s'",
                    getAppname(), e.getMessage(), e.getDescription()), e);
        }
    }

    private Map getMergedEnv(CloudApplication application, Map env) {
        if (!isMergeEnv()) {
            return env;
        }

        Map mergedEnv = application.getEnvAsMap();
        mergedEnv.putAll(env);

        return mergedEnv;
    }

    private List getServiceNames() {
        final List services = getServices();
        List serviceNames = new ArrayList();

        for (CloudService service : services) {
            serviceNames.add(service.getName());
        }
        return serviceNames;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
 */
public class AbstractPush extends AbstractApplicationAwareCloudFoundryMojo {

	@Override
	protected void doExecute() throws MojoExecutionException {
		final String appname = getAppname();
		final String command = getCommand();
		final String buildpack = getBuildpack();
		final String stack = getStack();
		final Integer healthCheckTimeout = getHealthCheckTimeout();
		final Map env = getEnv();
		final Integer instances = getInstances();
		final Integer memory = getMemory();
		final Integer disk = getDiskQuota();
		final File path = getPath();
		final List uris = getAllUris();
		final List serviceNames = getServiceNames();

		validatePath(path);

		addDomains();

		createServices();

		getLog().debug(String.format(
				"Pushing App - Appname: %s," +
						" Command: %s," +
						" Env: %s," +
						" Instances: %s," +
						" Memory: %s," +
						" DiskQuota: %s," +
						" Path: %s," +
						" Services: %s," +
						" Uris: %s,",
				appname, command, env, instances, memory, disk, path, serviceNames, uris));

		getLog().info(String.format("Creating application '%s'", appname));

		createApplication(appname, command, buildpack, stack, healthCheckTimeout, disk, memory, uris, serviceNames, env);

		getLog().info(String.format("Uploading '%s'", path));

		try {
			uploadApplication(getClient(), path, appname);
		} catch (CloudFoundryException e) {
}
			throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: '%s'. Description: '%s'",
					getAppname(), e.getMessage(), e.getDescription()), e);
		}

		if (instances != null) {
			getLog().debug("Setting the number of instances to " + instances);

			try {
				getClient().updateApplicationInstances(appname, instances);
			} catch (CloudFoundryException e) {
				throw new MojoExecutionException(String.format("Error while setting number of instances for application '%s'. Error message: '%s'. Description: '%s'",
						getAppname(), e.getMessage(), e.getDescription()), e);
			}
		}

		if (!isNoStart()) {
			getLog().info("Starting application");

			try {
				final StartingInfo startingInfo = getClient().startApplication(appname);
				showStagingStatus(startingInfo);

				final CloudApplication app = getClient().getApplication(appname);
				showStartingStatus(app);
				showStartResults(app, uris);
			} catch (CloudFoundryException e) {
				throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: '%s'. Description: '%s'",
						getAppname(), e.getMessage(), e.getDescription()), e);
			}
		}
	}

	private void createApplication(String appname, String command, String buildpack, String stack, Integer healthCheckTimeout,
	                               Integer diskQuota, Integer memory, List uris, List serviceNames, Map env) throws MojoExecutionException {
		CloudApplication application = null;
		try {
			application = client.getApplication(appname);
		} catch (CloudFoundryException e) {
			if (!HttpStatus.NOT_FOUND.equals(e.getStatusCode())) {
				throw new MojoExecutionException(String.format("Error while checking for existing application '%s'. Error message: '%s'. Description: '%s'",
						appname, e.getMessage(), e.getDescription()), e);
			}
		}

		try {
			final Staging staging = new Staging(command, buildpack, stack, healthCheckTimeout);
			if (application == null) {
				client.createApplication(appname, staging, diskQuota, memory, uris, serviceNames);
				client.updateApplicationEnv(appname, env);
			} else {
				client.stopApplication(appname);
				client.updateApplicationStaging(appname, staging);
				if (memory != null) {
					client.updateApplicationMemory(appname, memory);
				}
				if (diskQuota != null) {
					client.updateApplicationDiskQuota(appname, diskQuota);
				}
				if (urlsAreExplicitlySet()) {
					client.updateApplicationUris(appname, uris);
				}
				if (null != getServices()) {
					client.updateApplicationServices(appname, serviceNames);
				}
				if (null != env) {
					client.updateApplicationEnv(appname, getMergedEnv(application, env));
				}
			}
		} catch (CloudFoundryException e) {
			throw new MojoExecutionException(String.format("Error while creating application '%s'. Error message: '%s'. Description: '%s'",
					getAppname(), e.getMessage(), e.getDescription()), e);
		}
	}

	private Map getMergedEnv(CloudApplication application, Map env) {
		if (!isMergeEnv()) {
			return env;
		}

		Map mergedEnv = application.getEnvAsMap();
		mergedEnv.putAll(env);

		return mergedEnv;
	}

	private List getServiceNames() {
		final List services = getServices();
		List serviceNames = new ArrayList();

		if (services != null) {
			for (CloudService service : services) {
				serviceNames.add(service.getName());
			}
		}
		return serviceNames;
	}
File
AbstractPush.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
	@Override

public class BindServices extends AbstractApplicationAwareCloudFoundryMojo {

<<<<<<< HEAD
	protected void doExecute() throws MojoExecutionException {
		final List services = getServices();
		if (services != null) {
			for (CloudService service : services) {
				if (getClient().getService(service.getName()) == null) {
					throw new MojoExecutionException(String.format("Service '%s' does not exist", service.getName()));
				}

				try {
					final CloudApplication application = getClient().getApplication(getAppname());
					if (application.getServices().contains(service.getName())) {
						getLog().info(String.format("Service '%s' is already bound to application '%s'",
								service.getName(), application.getName()));
					}
					else {
						getClient().bindService(getAppname(), service.getName());
						getLog().info(String.format("Binding Service '%s'", service.getName()));
					}
				}
				catch (CloudFoundryException e) {
					throw new MojoExecutionException(String.format("Application '%s' does not exist", getAppname()));
				}
			}
		}
	}
=======
    @Override
    protected void doExecute() throws MojoExecutionException {
        for (CloudService service : getServices()) {
            if (getClient().getService(service.getName()) == null) {
                throw new MojoExecutionException(String.format("Service '%s' does not exist", service.getName()));
            }

            try {
                final CloudApplication application = getClient().getApplication(getAppname());
                if (application.getServices().contains(service.getName())) {
                    getLog().info(String.format("Service '%s' is already bound to application '%s'",
                            service.getName(), application.getName()));
                } else {
                    getClient().bindService(getAppname(), service.getName());
                    getLog().info(String.format("Binding Service '%s'", service.getName()));
                }
            } catch (CloudFoundryException e) {
                throw new MojoExecutionException(String.format("Application '%s' does not exist", getAppname()));
            }
        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
public class BindServices extends AbstractApplicationAwareCloudFoundryMojo {

	@Override
	protected void doExecute() throws MojoExecutionException {
		final List services = getServices();
		if (services != null) {
			for (CloudService service : services) {
				if (getClient().getService(service.getName()) == null) {
					throw new MojoExecutionException(String.format("Service '%s' does not exist", service.getName()));
				}

				try {
					final CloudApplication application = getClient().getApplication(getAppname());
					if (application.getServices().contains(service.getName())) {
						getLog().info(String.format("Service '%s' is already bound to application '%s'",
								service.getName(), application.getName()));
					}
					else {
						getClient().bindService(getAppname(), service.getName());
						getLog().info(String.format("Binding Service '%s'", service.getName()));
					}
				}
				catch (CloudFoundryException e) {
					throw new MojoExecutionException(String.format("Application '%s' does not exist", getAppname()));
				}
			}
		}
	}
}
File
BindServices.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
public class DeleteServices extends AbstractApplicationAwareCloudFoundryMojo {

<<<<<<< HEAD
	@Override
	protected void doExecute() throws MojoExecutionException {
		if (null != getServices()) {
			for (CloudService service : getServices()) {
				try {
					getLog().info(String.format("Deleting service '%s'", service.getName()));
					getClient().deleteService(service.getName());
				}
				catch (NullPointerException e) {
					getLog().info(String.format("Service '%s' does not exist", service.getName()));
				}
			}
		} else {
			getLog().info("No services to delete.");
		}
	}
=======
    @Override
    protected void doExecute() throws MojoExecutionException {
        for (CloudService service : getServices()) {
            try {
                getLog().info(String.format("Deleting service '%s'", service.getName()));
                getClient().deleteService(service.getName());
            } catch (NullPointerException e) {
                getLog().info(String.format("Service '%s' does not exist", service.getName()));
            }
        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
public class DeleteServices extends AbstractApplicationAwareCloudFoundryMojo {

	@Override
	protected void doExecute() throws MojoExecutionException {
		if (null != getServices()) {
			for (CloudService service : getServices()) {
				try {
					getLog().info(String.format("Deleting service '%s'", service.getName()));
					getClient().deleteService(service.getName());
				}
				catch (NullPointerException e) {
					getLog().info(String.format("Service '%s' does not exist", service.getName()));
				}
			}
		} else {
			getLog().info("No services to delete.");
		}
	}
}
File
DeleteServices.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
 */
public class Help extends AbstractApplicationAwareCloudFoundryMojo {

<<<<<<< HEAD
	public static final String HELP_TEXT = "/help.txt";
	public static final String NOT_AVAILABLE = "N/A";

	/**
	 * 	@FIXME Not sure whether one should be able to overwrite execute()
	 *
	 *  The help goal does not require an interaction with Cloud Foundry. A
    /**
        }
	 *  login is not necessary. Therefore, this method is overwritten.
	 *
	 */
	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		doExecute();
	}

	/**
	 * @return
	 */
	private Map getParameterMap() throws MojoExecutionException {
		final Map parameterMap = new TreeMap();

		parameterMap.put("appname", getAppname() != null ? getAppname() : NOT_AVAILABLE);
		parameterMap.put("command", getCommand() != null ? getCommand() : NOT_AVAILABLE);
		parameterMap.put("instances", getInstances() != null ? String.valueOf(getInstances()) : NOT_AVAILABLE);
		parameterMap.put("memory (in MB)", getMemory() != null ? String.valueOf(getMemory()) : NOT_AVAILABLE);
		parameterMap.put("diskQuota (in MB)", getDiskQuota() != null ? String.valueOf(getDiskQuota()) : NOT_AVAILABLE);
		parameterMap.put("healthCheckTimeout", getHealthCheckTimeout() != null ? String.valueOf(getHealthCheckTimeout()) : NOT_AVAILABLE);
		parameterMap.put("url", getUrl() != null ? getUrl() : NOT_AVAILABLE);
		parameterMap.put("urls", getUrls() == null ? NOT_AVAILABLE : CommonUtils.collectionToCommaDelimitedString(getUrls()));
		parameterMap.put("path", getArtifactPath());

		parameterMap.put("env", getEnv() != null ? String.valueOf(getEnv()) : NOT_AVAILABLE);
		parameterMap.put("mergeEnv", String.valueOf(isMergeEnv()));
		parameterMap.put("services", getServices() == null ? NOT_AVAILABLE : CommonUtils.collectionServicesToCommaDelimitedString(getServices()));
		parameterMap.put("noStart", String.valueOf(isNoStart()));

		parameterMap.put("server", getServer());
		parameterMap.put("target", getTarget() != null ? getTarget().toString() : NOT_AVAILABLE);
		parameterMap.put("org", getOrg(false) != null ? getOrg() : NOT_AVAILABLE);
		parameterMap.put("space", getSpace(false) != null ? getSpace() : NOT_AVAILABLE);
		parameterMap.put("username", getUsername() != null ? getUsername() : NOT_AVAILABLE);
		parameterMap.put("password", getPassword() != null ? CommonUtils.maskPassword(getPassword()) : NOT_AVAILABLE);

		parameterMap.put("trustSelfSignedCerts", String.valueOf(getTrustSelfSignedCerts()));

		return parameterMap;
	}

	@Override
	protected void doExecute() throws MojoExecutionException {
		final StringBuilder sb = new StringBuilder();

		sb.append("\n" + UiUtils.HORIZONTAL_LINE);
		sb.append("\nCloud Foundry Maven Plugin detected parameters and/or default values:\n\n");

        return path;
		sb.append(UiUtils.renderParameterInfoDataAsTable(getParameterMap()));

		Reader reader = null;
		BufferedReader in = null;

		try {
			final InputStream is = Help.class.getResourceAsStream(HELP_TEXT);
			reader = new InputStreamReader(is);
			in = new BufferedReader(reader);

			final StringBuilder helpTextStringBuilder = new StringBuilder();

			String line = "";

			while (line != null) {
				try {
					line = in.readLine();
				} catch (IOException e) {
					throw new IllegalStateException("Problem reading internal '" + HELP_TEXT + "' file. This is a bug.", e);
				}

				if (line != null) {
					helpTextStringBuilder.append(line).append("\n");
				}
			}
			sb.append(helpTextStringBuilder);
		} finally {
			CommonUtils.closeReader(in);
			CommonUtils.closeReader(reader);
		}

		getLog().info(sb);
	}

	private String getArtifactPath() {
		String path;
		try {
			path = getPath() != null ? getPath().getAbsolutePath() : NOT_AVAILABLE;
		} catch (MojoExecutionException ex) {
			path = NOT_AVAILABLE;
		}
		return path;
	}
=======
    public static final String HELP_TEXT = "/help.txt";

    public static final String NOT_AVAILABLE = "N/A";
     * @FIXME Not sure whether one should be able to overwrite execute()
     *
     * The help goal does not require an interaction with Cloud Foundry. A login is not necessary. Therefore, this
     * method is overwritten.
     */
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        doExecute();
    }

    @Override
    protected void doExecute() throws MojoExecutionException {
        final StringBuilder sb = new StringBuilder();

        sb.append("\n" + UiUtils.HORIZONTAL_LINE);
        sb.append("\nCloud Foundry Maven Plugin detected parameters and/or default values:\n\n");

        sb.append(UiUtils.renderParameterInfoDataAsTable(getParameterMap()));

        Reader reader = null;
        BufferedReader in = null;

        try {
            final InputStream is = Help.class.getResourceAsStream(HELP_TEXT);
            reader = new InputStreamReader(is);
            in = new BufferedReader(reader);

            final StringBuilder helpTextStringBuilder = new StringBuilder();

            String line = "";

            while (line != null) {
                try {
                    line = in.readLine();
                } catch (IOException e) {
                    throw new IllegalStateException("Problem reading internal '" + HELP_TEXT + "' file. This is a bug" +
                            ".", e);
                }

                if (line != null) {
                    helpTextStringBuilder.append(line).append("\n");
                }
            }
            sb.append(helpTextStringBuilder);
        } finally {
            CommonUtils.closeReader(in);
            CommonUtils.closeReader(reader);
        }

        getLog().info(sb);
    }

    private String getArtifactPath() {
        String path;
        try {
            path = getPath() != null ? getPath().getAbsolutePath() : NOT_AVAILABLE;
        } catch (MojoExecutionException ex) {
            path = NOT_AVAILABLE;
    }

    /**
     * @return
     */
    private Map getParameterMap() throws MojoExecutionException {
        final Map parameterMap = new TreeMap();

        parameterMap.put("appname", getAppname() != null ? getAppname() : NOT_AVAILABLE);
        parameterMap.put("command", getCommand() != null ? getCommand() : NOT_AVAILABLE);
        parameterMap.put("instances", getInstances() != null ? String.valueOf(getInstances()) : NOT_AVAILABLE);
        parameterMap.put("memory (in MB)", getMemory() != null ? String.valueOf(getMemory()) : NOT_AVAILABLE);
        parameterMap.put("diskQuota (in MB)", getDiskQuota() != null ? String.valueOf(getDiskQuota()) : NOT_AVAILABLE);
        parameterMap.put("healthCheckTimeout", getHealthCheckTimeout() != null ? String.valueOf(getHealthCheckTimeout
                ()) : NOT_AVAILABLE);
        parameterMap.put("url", getUrl() != null ? getUrl() : NOT_AVAILABLE);
        parameterMap.put("urls", getUrls().isEmpty() ? NOT_AVAILABLE : CommonUtils.collectionToCommaDelimitedString
                (getUrls()));
        parameterMap.put("path", getArtifactPath());

        parameterMap.put("env", getEnv() != null ? String.valueOf(getEnv()) : NOT_AVAILABLE);
        parameterMap.put("mergeEnv", String.valueOf(isMergeEnv()));
        parameterMap.put("services", getServices().isEmpty() ? NOT_AVAILABLE : CommonUtils
                .collectionServicesToCommaDelimitedString(getServices()));
        parameterMap.put("noStart", String.valueOf(isNoStart()));

        parameterMap.put("server", getServer());
        parameterMap.put("target", getTarget() != null ? getTarget().toString() : NOT_AVAILABLE);
        parameterMap.put("org", getOrg(false) != null ? getOrg() : NOT_AVAILABLE);
        parameterMap.put("space", getSpace(false) != null ? getSpace() : NOT_AVAILABLE);
        parameterMap.put("username", getUsername() != null ? getUsername() : NOT_AVAILABLE);
        parameterMap.put("password", getPassword() != null ? CommonUtils.maskPassword(getPassword()) : NOT_AVAILABLE);

        parameterMap.put("trustSelfSignedCerts", String.valueOf(getTrustSelfSignedCerts()));

        return parameterMap;
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
 */
public class Help extends AbstractApplicationAwareCloudFoundryMojo {

	public static final String HELP_TEXT = "/help.txt";
	public static final String NOT_AVAILABLE = "N/A";

	/**
	 * 	@FIXME Not sure whether one should be able to overwrite execute()
	 *
	 *  The help goal does not require an interaction with Cloud Foundry. A
	 *  login is not necessary. Therefore, this method is overwritten.
	 *
	 */
	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		doExecute();
	}

	/**
	 * @return
	 */
	private Map getParameterMap() throws MojoExecutionException {
		final Map parameterMap = new TreeMap();

		parameterMap.put("appname", getAppname() != null ? getAppname() : NOT_AVAILABLE);
		parameterMap.put("command", getCommand() != null ? getCommand() : NOT_AVAILABLE);
		parameterMap.put("instances", getInstances() != null ? String.valueOf(getInstances()) : NOT_AVAILABLE);
		parameterMap.put("memory (in MB)", getMemory() != null ? String.valueOf(getMemory()) : NOT_AVAILABLE);
		parameterMap.put("diskQuota (in MB)", getDiskQuota() != null ? String.valueOf(getDiskQuota()) : NOT_AVAILABLE);
		parameterMap.put("healthCheckTimeout", getHealthCheckTimeout() != null ? String.valueOf(getHealthCheckTimeout()) : NOT_AVAILABLE);
		parameterMap.put("url", getUrl() != null ? getUrl() : NOT_AVAILABLE);
		parameterMap.put("urls", getUrls() == null ? NOT_AVAILABLE : CommonUtils.collectionToCommaDelimitedString(getUrls()));
		parameterMap.put("path", getArtifactPath());

		parameterMap.put("env", getEnv() != null ? String.valueOf(getEnv()) : NOT_AVAILABLE);
		parameterMap.put("mergeEnv", String.valueOf(isMergeEnv()));
		parameterMap.put("services", getServices() == null ? NOT_AVAILABLE : CommonUtils.collectionServicesToCommaDelimitedString(getServices()));
		parameterMap.put("noStart", String.valueOf(isNoStart()));

		parameterMap.put("server", getServer());
		parameterMap.put("target", getTarget() != null ? getTarget().toString() : NOT_AVAILABLE);
		parameterMap.put("org", getOrg(false) != null ? getOrg() : NOT_AVAILABLE);
		parameterMap.put("space", getSpace(false) != null ? getSpace() : NOT_AVAILABLE);
		parameterMap.put("username", getUsername() != null ? getUsername() : NOT_AVAILABLE);
		parameterMap.put("password", getPassword() != null ? CommonUtils.maskPassword(getPassword()) : NOT_AVAILABLE);

		parameterMap.put("trustSelfSignedCerts", String.valueOf(getTrustSelfSignedCerts()));

		return parameterMap;
	}

	@Override
	protected void doExecute() throws MojoExecutionException {
		final StringBuilder sb = new StringBuilder();

		sb.append("\n" + UiUtils.HORIZONTAL_LINE);
		sb.append("\nCloud Foundry Maven Plugin detected parameters and/or default values:\n\n");

		sb.append(UiUtils.renderParameterInfoDataAsTable(getParameterMap()));

		Reader reader = null;
		BufferedReader in = null;

		try {
			final InputStream is = Help.class.getResourceAsStream(HELP_TEXT);
			reader = new InputStreamReader(is);
			in = new BufferedReader(reader);

			final StringBuilder helpTextStringBuilder = new StringBuilder();

			String line = "";

			while (line != null) {
				try {
					line = in.readLine();
				} catch (IOException e) {
					throw new IllegalStateException("Problem reading internal '" + HELP_TEXT + "' file. This is a bug.", e);
				}

				if (line != null) {
					helpTextStringBuilder.append(line).append("\n");
				}
			}
			sb.append(helpTextStringBuilder);
		} finally {
			CommonUtils.closeReader(in);
			CommonUtils.closeReader(reader);
		}

		getLog().info(sb);
	}

	private String getArtifactPath() {
		String path;
		try {
			path = getPath() != null ? getPath().getAbsolutePath() : NOT_AVAILABLE;
		} catch (MojoExecutionException ex) {
			path = NOT_AVAILABLE;
		}
		return path;
	}
}
File
Help.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Comment
Method declaration
Chunk
Conflicting content
public class UnbindServices extends AbstractApplicationAwareCloudFoundryMojo {

<<<<<<< HEAD
	@Override
	protected void doExecute() throws MojoExecutionException {
		if (null != getServices()) {
			for (CloudService service : getServices()) {
				if (getClient().getService(service.getName()) == null) {
					throw new MojoExecutionException(String.format("Service '%s' does not exist", service.getName()));
				}

				try {
					final CloudApplication application = getClient().getApplication(getAppname());
					if (application.getServices().contains(service.getName())) {
						getLog().info(String.format("Unbinding Service '%s'", service.getName()));
						getClient().unbindService(getAppname(), service.getName());
					}
					else {
						getLog().info(String.format("Service '%s' is not bound to application '%s'",
								service.getName(), application.getName()));
					}
				}
				catch (CloudFoundryException e) {
					throw new MojoExecutionException(String.format("Application '%s' does not exist", getAppname()));
				}

			}
		} else {
			getLog().info("No services to unbind.");
		}
	}
=======
    @Override
    protected void doExecute() throws MojoExecutionException {
        for (CloudService service : getServices()) {
            if (getClient().getService(service.getName()) == null) {
                throw new MojoExecutionException(String.format("Service '%s' does not exist", service.getName()));
            }

            try {
                final CloudApplication application = getClient().getApplication(getAppname());
                if (application.getServices().contains(service.getName())) {
                    getLog().info(String.format("Unbinding Service '%s'", service.getName()));
                    getClient().unbindService(getAppname(), service.getName());
                } else {
                    getLog().info(String.format("Service '%s' is not bound to application '%s'",
                            service.getName(), application.getName()));
                }
            } catch (CloudFoundryException e) {
                throw new MojoExecutionException(String.format("Application '%s' does not exist", getAppname()));
            }

        }
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
public class UnbindServices extends AbstractApplicationAwareCloudFoundryMojo {

	@Override
	protected void doExecute() throws MojoExecutionException {
		if (null != getServices()) {
			for (CloudService service : getServices()) {
				if (getClient().getService(service.getName()) == null) {
					throw new MojoExecutionException(String.format("Service '%s' does not exist", service.getName()));
				}

				try {
					final CloudApplication application = getClient().getApplication(getAppname());
					if (application.getServices().contains(service.getName())) {
						getLog().info(String.format("Unbinding Service '%s'", service.getName()));
						getClient().unbindService(getAppname(), service.getName());
					}
					else {
						getLog().info(String.format("Service '%s' is not bound to application '%s'",
								service.getName(), application.getName()));
					}
				}
				catch (CloudFoundryException e) {
					throw new MojoExecutionException(String.format("Application '%s' does not exist", getAppname()));
				}

			}
		} else {
			getLog().info("No services to unbind.");
		}
	}
}
File
UnbindServices.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
    }

    private Assert() {
 */
public final class Assert {

<<<<<<< HEAD
	/**
	 * Prevent instantiation.
	 */
	private Assert() {
		throw new AssertionError();
	}

	/**
	 * Assert that an object is not null .
	 * 
Assert.notNull(clazz, "The class must not be null");
* @param object the object to check * @param message the exception message to use if the assertion fails * @throws IllegalArgumentException if the object is null */ public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } /** * * @param object * @param objectName * @param property */ throw new AssertionError(); public static void configurationNotNull(Object object, String objectName, SystemProperties property) throws MojoExecutionException { configurationNotNull(object, objectName, property, null); } /** * * @param object * @param objectName * @param property * @param additionalDescription */ public static void configurationNotNull(Object object, String objectName, SystemProperties property, String additionalDescription) throws MojoExecutionException { if (object == null) { final StringBuilder message = new StringBuilder("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); message.append(String.format("\nRequired argument '%s' is missing.\n", objectName)); message.append("========================================================================\n\n"); message.append(String.format("Did you configure the parameter? You " + "can provide the parameter either as:\n\n" + "- System Property using: -D%1$s= or \n" + "- Add the parameter to the pom.xml under the plugin's configuration element:\n\n" + " \n" + " <%2$s>provide value\n" + " \n" + "\n", property.getProperty(), property.getXmlElement())); message.append(UiUtils.HORIZONTAL_LINE); if (additionalDescription != null) { message.append(additionalDescription).append("\n"); message.append(UiUtils.HORIZONTAL_LINE); } throw new MojoExecutionException(message.toString()); } } /** * * @param cloudService Object * @param additionalDescription */ public static void configurationServiceNotNull(CloudService cloudService, String additionalDescription) throws MojoExecutionException { if (cloudService.getName() == null || cloudService.getLabel() == null) { final StringBuilder message = new StringBuilder("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); message.append(String.format("\nRequired arguments for '%s' are missing.\n", cloudService.getName())); message.append("========================================================================\n\n"); message.append("Did you configure the parameter? You "); message.append("can provide the parameter in the pom.xml under the plugin's configuration element:\n\n"); message.append("\n"); message.append(" \n"); message.append(" \n"); message.append(" provide value\n"); message.append(" \n"); message.append(" \n"); message.append(" \n"); message.append("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); if (additionalDescription != null) { message.append(additionalDescription).append("\n"); message.append(UiUtils.HORIZONTAL_LINE); } throw new MojoExecutionException(message.toString()); } } /** * Cannot use elements url and urls together */ public static void configurationUrls(String url, List urls) throws MojoExecutionException { if (url != null && urls != null && !urls.isEmpty()) { final String message = "\n\n" + "Both url and urls elements are specified at the same level\n" + "========================================================================\n\n" + "The element should be nested inside a element or specified alone without a element present.\n" + UiUtils.HORIZONTAL_LINE; throw new MojoExecutionException(message); } } ======= /** * Prevent instantiation. */ /** * @param object * @param objectName * @param property */ public static void configurationNotNull(Object object, String objectName, SystemProperties property) throws MojoExecutionException { configurationNotNull(object, objectName, property, null); } /** * @param object * @param objectName * @param property * @param additionalDescription */ public static void configurationNotNull(Object object, String objectName, SystemProperties property, String additionalDescription) throws MojoExecutionException { if (object == null) { final StringBuilder message = new StringBuilder("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); message.append(String.format("\nRequired argument '%s' is missing.\n", objectName)); message.append("========================================================================\n\n"); message.append(String.format("Did you configure the parameter? You " + "can provide the parameter either as:\n\n" + "- System Property using: -D%1$s= or \n" + "- Add the parameter to the pom.xml under the plugin's configuration element:\n\n" + " \n" + " <%2$s>provide value\n" + " \n" + "\n", property.getProperty(), property.getXmlElement())); message.append(UiUtils.HORIZONTAL_LINE); if (additionalDescription != null) { message.append(additionalDescription).append("\n"); message.append(UiUtils.HORIZONTAL_LINE); } throw new MojoExecutionException(message.toString()); } } /** * @param cloudService Object * @param additionalDescription */ public static void configurationServiceNotNull(CloudService cloudService, String additionalDescription) throws MojoExecutionException { if (cloudService.getName() == null || cloudService.getLabel() == null) { final StringBuilder message = new StringBuilder("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); message.append(String.format("\nRequired arguments for '%s' are missing.\n", cloudService.getName())); message.append("========================================================================\n\n"); message.append("Did you configure the parameter? You "); message.append("can provide the parameter in the pom.xml under the plugin's configuration element:\n\n"); message.append("\n"); message.append(" \n"); message.append(" \n"); message.append(" provide value\n"); message.append(" \n"); message.append(" \n"); message.append(" \n"); message.append("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); if (additionalDescription != null) { message.append(additionalDescription).append("\n"); message.append(UiUtils.HORIZONTAL_LINE); } throw new MojoExecutionException(message.toString()); } } /** * Cannot use elements url and urls together */ public static void configurationUrls(String url, List urls) throws MojoExecutionException { if (url != null && !urls.isEmpty()) { final String message = "\n\n" + "Both url and urls elements are specified at the same level\n" + "========================================================================\n\n" + "The element should be nested inside a element or specified alone without a element present.\n" + UiUtils.HORIZONTAL_LINE; throw new MojoExecutionException(message); } } /** * Assert that an object is not null .
Assert.notNull(clazz, "The class must not be
     * null");
* * @param object the object to check * @param message the exception message to use if the assertion fails * @throws IllegalArgumentException if the object is null */ public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } >>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d }
Solution content
 */
public final class Assert {

	/**
	 * Prevent instantiation.
	 */
	private Assert() {
		throw new AssertionError();
	}

	/**
	 * Assert that an object is not null .
	 * 
Assert.notNull(clazz, "The class must not be null");
* @param object the object to check * @param message the exception message to use if the assertion fails * @throws IllegalArgumentException if the object is null */ public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } /** * * @param object * @param objectName * @param property */ public static void configurationNotNull(Object object, String objectName, SystemProperties property) throws MojoExecutionException { configurationNotNull(object, objectName, property, null); } /** * * @param object * @param objectName * @param property * @param additionalDescription */ public static void configurationNotNull(Object object, String objectName, SystemProperties property, String additionalDescription) throws MojoExecutionException { if (object == null) { final StringBuilder message = new StringBuilder("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); message.append(String.format("\nRequired argument '%s' is missing.\n", objectName)); message.append("========================================================================\n\n"); message.append(String.format("Did you configure the parameter? You " + "can provide the parameter either as:\n\n" + "- System Property using: -D%1$s= or \n" + "- Add the parameter to the pom.xml under the plugin's configuration element:\n\n" + " \n" + " <%2$s>provide value\n" + " \n" + "\n", property.getProperty(), property.getXmlElement())); message.append(UiUtils.HORIZONTAL_LINE); if (additionalDescription != null) { message.append(additionalDescription).append("\n"); message.append(UiUtils.HORIZONTAL_LINE); } throw new MojoExecutionException(message.toString()); } } /** * * @param cloudService Object * @param additionalDescription */ public static void configurationServiceNotNull(CloudService cloudService, String additionalDescription) throws MojoExecutionException { if (cloudService.getName() == null || cloudService.getLabel() == null) { final StringBuilder message = new StringBuilder("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); message.append(String.format("\nRequired arguments for '%s' are missing.\n", cloudService.getName())); message.append("========================================================================\n\n"); message.append("Did you configure the parameter? You "); message.append("can provide the parameter in the pom.xml under the plugin's configuration element:\n\n"); message.append("\n"); message.append(" \n"); message.append(" \n"); message.append(" provide value\n"); message.append(" \n"); message.append(" \n"); message.append(" \n"); message.append("\n\n"); message.append(UiUtils.HORIZONTAL_LINE); if (additionalDescription != null) { message.append(additionalDescription).append("\n"); message.append(UiUtils.HORIZONTAL_LINE); } throw new MojoExecutionException(message.toString()); } } /** * Cannot use elements url and urls together */ public static void configurationUrls(String url, List urls) throws MojoExecutionException { if (url != null && urls != null && !urls.isEmpty()) { final String message = "\n\n" + "Both url and urls elements are specified at the same level\n" + "========================================================================\n\n" + "The element should be nested inside a element or specified alone without a element present.\n" + UiUtils.HORIZONTAL_LINE; throw new MojoExecutionException(message); } } }
File
Assert.java
Developer's decision
Version 1
Kind of conflict
Comment
Method declaration
Chunk
Conflicting content
 * @since 1.0.0
 */
public final class UiUtils {
<<<<<<< HEAD
	public static final String HORIZONTAL_LINE = "-------------------------------------------------------------------------------\n";

	public static final int COLUMN_1 = 1;
	public static final int COLUMN_2 = 2;
	public static final int COLUMN_3 = 3;
	public static final int COLUMN_4 = 4;
	public static final int COLUMN_5 = 5;
	public static final int COLUMN_6 = 6;

	/**
	 * Prevent instantiation.
	 *
	 */
	private UiUtils() {
		throw new AssertionError();
	}

	/**
	 * Renders a textual representation of a Application {@link CloudApplication}
	 *
	 * 
    *
  • Names of the Applications
  • *
  • Number of Instances
  • *
  • Current State (Health)
  • *
  • Used Memory
  • *
  • The comma-separated list of Uris
  • *
  • The comma-separated list of Services
  • *
      */ public static String renderCloudApplicationDataAsTable(CloudApplication application, ApplicationStats stats) { StringBuilder sb = new StringBuilder("\n"); sb.append(String.format("application: %s\n", application.getName())); sb.append(String.format("state: %s\n", application.getState())); sb.append(String.format("instances: %d/%d\n", application.getRunningInstances(), application.getInstances())); sb.append(String.format("usage: %s x %s instance\n", formatMBytes(application.getMemory()), application.getInstances())); sb.append(String.format("urls: %s\n", CommonUtils.collectionToCommaDelimitedString(application.getUris()))); sb.append(String.format("services: %s\n", CommonUtils.collectionToCommaDelimitedString(application.getServices()))); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("instance")); table.getHeaders().put(COLUMN_2, new TableHeader("state")); table.getHeaders().put(COLUMN_3, new TableHeader("cpu")); table.getHeaders().put(COLUMN_4, new TableHeader("memory")); table.getHeaders().put(COLUMN_5, new TableHeader("disk")); for (InstanceStats instance : stats.getRecords()) { TableRow tableRow = new TableRow(); String index = instance.getId(); table.getHeaders().get(COLUMN_1).updateWidth(String.valueOf(index).length()); tableRow.addValue(COLUMN_1, String.valueOf(index)); String state = instance.getState().toString().toLowerCase(); table.getHeaders().get(COLUMN_2).updateWidth(String.valueOf(state).length()); tableRow.addValue(COLUMN_2, String.valueOf(state)); InstanceStats.Usage usage = instance.getUsage(); if (usage != null) { String cpu = String.format("%.2f%%", usage.getCpu() * 100); table.getHeaders().get(COLUMN_3).updateWidth(String.valueOf(cpu).length()); tableRow.addValue(COLUMN_3, String.valueOf(cpu)); String memory = String.format("%s of %s", formatBytes(usage.getMem()), formatBytes(instance.getMemQuota())); table.getHeaders().get(COLUMN_4).updateWidth(String.valueOf(memory).length()); tableRow.addValue(COLUMN_4, String.valueOf(memory)); String disk = String.format("%s of %s", formatBytes(usage.getDisk()), formatBytes(instance.getDiskQuota())); table.getHeaders().get(COLUMN_5).updateWidth(String.valueOf(disk).length()); tableRow.addValue(COLUMN_5, String.valueOf(disk)); } table.getRows().add(tableRow); } sb.append("\n").append(renderTextTable(table)); return sb.toString(); } /** * Renders a textual representation of the list of provided {@link CloudApplication} * * The following information is shown: * *
        *
      • Names of the Applications
      • *
      • Number of Instances
      • *
      • Current State (Health)
      • *
      • Used Memory
      • *
      • The comma-separated list of Uris
      • *
      • The comma-separated list of Services
      • *
          * * @param applications List of {@CloudApplication} * @return The rendered table representation as String * */ public static String renderCloudApplicationsDataAsTable(List applications) { Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("name")); table.getHeaders().put(COLUMN_2, new TableHeader("status")); table.getHeaders().put(COLUMN_3, new TableHeader("instances")); table.getHeaders().put(COLUMN_4, new TableHeader("memory")); table.getHeaders().put(COLUMN_5, new TableHeader("disk")); table.getHeaders().put(COLUMN_6, new TableHeader("url")); Comparator nameComparator = new Comparator() { public int compare(CloudApplication a, CloudApplication b) { return a.getName().compareTo(b.getName()); } }; Collections.sort(applications, nameComparator); for (CloudApplication application : applications) { TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(application.getName().length()); tableRow.addValue(COLUMN_1, application.getName()); String status = renderHealthStatus(application); table.getHeaders().get(COLUMN_2).updateWidth(status.length()); tableRow.addValue(COLUMN_2, status); String instances = String.format("%d/%d", application.getRunningInstances(), application.getInstances()); table.getHeaders().get(COLUMN_3).updateWidth(String.valueOf(instances).length()); tableRow.addValue(COLUMN_3, String.valueOf(instances)); String memory = formatMBytes(application.getMemory()); table.getHeaders().get(COLUMN_4).updateWidth(String.valueOf(memory).length()); tableRow.addValue(COLUMN_4, String.valueOf(memory)); String disk = formatMBytes(application.getDiskQuota()); table.getHeaders().get(COLUMN_5).updateWidth(String.valueOf(disk).length()); tableRow.addValue(COLUMN_5, String.valueOf(disk)); String uris = CommonUtils.collectionToCommaDelimitedString(application.getUris()); table.getHeaders().get(COLUMN_6).updateWidth(uris.length()); tableRow.addValue(COLUMN_6, uris); table.getRows().add(tableRow); } return renderTextTable(table); } private static String renderHealthStatus(CloudApplication app) { String state = app.getState().toString(); if (state.equals("STARTED")) { int running_instances = app.getRunningInstances(); int expected_instances = app.getInstances(); if (expected_instances > 0) { float ratio = running_instances / expected_instances; if (ratio == 1.0) return "running"; else return new Float((ratio * 100)).intValue() + "%"; } else { return "n/a"; } } else { return state.toLowerCase(); } } /** * Renders a textual representation of a application's environment variables */ public static String renderEnvVarDataAsTable(CloudApplication application) { StringBuilder sb = new StringBuilder("\n"); sb.append(String.format("Environment for application '%s'\n", application.getName())); final List envVars = application.getEnv(); for (String envVar : envVars) { sb.append(envVar).append("\n"); } return sb.toString(); } /** * Renders a sorted textual representation of the list of provided {@link CloudFoundryClient, @link CloudServiceOffering} * * @param serviceOfferings * @return The rendered table representation as String * */ public static String renderServiceOfferingDataAsTable(List serviceOfferings) { Comparator labelComparator = new Comparator() { public int compare(CloudServiceOffering a, CloudServiceOffering b) { return a.getLabel().compareTo(b.getLabel()); } }; Collections.sort(serviceOfferings, labelComparator); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("service")); table.getHeaders().put(COLUMN_2, new TableHeader("plans")); table.getHeaders().put(COLUMN_3, new TableHeader("description")); List CloudServicePlanNames; for (CloudServiceOffering serviceOffering : serviceOfferings) { TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(serviceOffering.getLabel().length()); tableRow.addValue(COLUMN_1, serviceOffering.getLabel()); CloudServicePlanNames = new ArrayList(); for (CloudServicePlan servicePlan : serviceOffering.getCloudServicePlans()) { CloudServicePlanNames.add(servicePlan.getName()); } table.getHeaders().get(COLUMN_2).updateWidth(CloudServicePlanNames.toString().length() - 1); tableRow.addValue(COLUMN_2, CloudServicePlanNames.toString().substring(1, CloudServicePlanNames.toString().length() - 1)); table.getHeaders().get(COLUMN_3).updateWidth(serviceOffering.getDescription().length()); tableRow.addValue(COLUMN_3, serviceOffering.getDescription()); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a sorted textual representation of the list of provided {@link CloudService} * * The following information is shown: * * * @param services * @param servicesToApps * @return The rendered table representation as String * */ public static String renderServiceDataAsTable(List services, Map> servicesToApps) { Comparator nameComparator = new Comparator() { public int compare(CloudService a, CloudService b) { return a.getName().compareTo(b.getName()); } }; Collections.sort(services, nameComparator); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("name")); table.getHeaders().put(COLUMN_2, new TableHeader("service")); table.getHeaders().put(COLUMN_3, new TableHeader("plan")); table.getHeaders().put(COLUMN_4, new TableHeader("bound apps")); for (CloudService service : services) { TableRow tableRow = new TableRow(); String name = service.getName(); String label; String plan; if (service.isUserProvided()) { label = "user-provided"; plan = ""; } else { label = service.getLabel(); plan = service.getPlan(); } table.getHeaders().get(COLUMN_1).updateWidth(name.length()); tableRow.addValue(COLUMN_1, name); table.getHeaders().get(COLUMN_2).updateWidth(label.length()); tableRow.addValue(COLUMN_2, label); table.getHeaders().get(COLUMN_3).updateWidth(plan.length()); tableRow.addValue(COLUMN_3, plan); final List appNames = servicesToApps.get(name); final String appNamesString = CommonUtils.collectionToCommaDelimitedString(appNames); table.getHeaders().get(COLUMN_4).updateWidth(appNamesString.length()); tableRow.addValue(COLUMN_4, appNamesString); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a textual representation of provided parameter map. * * @param parameters Map of parameters (key, value) * @return The rendered table representation as String * */ public static String renderParameterInfoDataAsTable(Map parameters) { final Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("Parameter")); table.getHeaders().put(COLUMN_2, new TableHeader("Value (Configured or Default)")); for (Entry entry : parameters.entrySet()) { final TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(entry.getKey().length()); tableRow.addValue(COLUMN_1, entry.getKey()); table.getHeaders().get(COLUMN_2).updateWidth(entry.getValue() != null ? entry.getValue().length() : 0); tableRow.addValue(COLUMN_2, entry.getValue()); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a textual representation of the provided {@link Table} * * @param table Table data {@link Table} * @return The rendered table representation as String */ public static String renderTextTable(Table table) { final String padding = " "; final String headerBorder = getHeaderBorder(table.getHeaders()); final StringBuilder textTable = new StringBuilder(); for (TableHeader header : table.getHeaders().values()) { textTable.append(padding + CommonUtils.padRight(header.getName(), header.getWidth())); } textTable.append("\n"); textTable.append(headerBorder); for (TableRow row : table.getRows()) { for (Entry entry : table.getHeaders().entrySet()) { textTable.append(padding + CommonUtils.padRight(row.getValue(entry.getKey()), entry.getValue().getWidth())); } textTable.append("\n"); } return textTable.toString(); } /** * Renders the help text. If the callers is logged in successfully the full * information is rendered if not only basic Cloud Foundry information is * rendered and returned as String. * * * * @param cloudInfo Contains the information about the Cloud Foundry environment * @param target The target Url from which the information was obtained * @param org * @param space * @return Returns a formatted String for console output */ public static String renderCloudInfoFormattedAsString(CloudInfo cloudInfo, String target, String org, String space) { final String cloudInfoMessage = "\n" + UiUtils.HORIZONTAL_LINE + String.format("API endpoint: %s (API version: %s) \n", target, cloudInfo.getVersion()) + String.format("user: %s\n", cloudInfo.getUser()) + String.format("org: %s\n", org) + String.format("space: %s\n", space) + UiUtils.HORIZONTAL_LINE; return cloudInfoMessage; } /** * Renders a line of application logging output. */ public static String renderApplicationLogEntry(ApplicationLog logEntry) { StringBuilder logLine = new StringBuilder(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); logLine.append(dateFormat.format(logEntry.getTimestamp())).append(" "); String source; if (logEntry.getSourceName().equals("App")) { source = String.format("[%s/%s]", logEntry.getSourceName(), logEntry.getSourceId()); } else { source = String.format("[%s]", logEntry.getSourceName()); } logLine.append(String.format("%-10s", source)); logLine.append(logEntry.getMessageType().name().substring("STD".length())).append(" "); logLine.append(logEntry.getMessage()); return logLine.toString(); } /** * Renders the Table header border, based on the map of provided headers. * * @param headers Map of headers containing meta information e.g. name+width of header * @return Returns the rendered header border as String */ public static String getHeaderBorder(Map headers) { final StringBuilder headerBorder = new StringBuilder(); for (TableHeader header : headers.values()) { headerBorder.append(CommonUtils.padRight(" ", header.getWidth() + 2, '-')); } headerBorder.append("\n"); return headerBorder.toString(); } public static String formatMBytes(int size) { int g = size / 1024; DecimalFormat dec = new DecimalFormat("0"); if (g > 1) { return dec.format(g).concat("G"); } else { return dec.format(size).concat("M"); } } public static String formatBytes(double size) { double k = size / 1024.0; double m = k / 1024.0; double g = m / 1024.0; DecimalFormat dec = new DecimalFormat("0"); if (g > 1) { return dec.format(g).concat("G"); } else if (m > 1) { return dec.format(m).concat("M"); } else if (k > 1) { return dec.format(k).concat("K"); } else { return dec.format(size).concat("B"); } } ======= public static final int COLUMN_1 = 1; public static final int COLUMN_2 = 2; public static final int COLUMN_3 = 3; public static final int COLUMN_4 = 4; public static final int COLUMN_5 = 5; public static final int COLUMN_6 = 6; public static final String HORIZONTAL_LINE = "-------------------------------------------------------------------------------\n"; /** * Prevent instantiation. */ private UiUtils() { throw new AssertionError(); } public static String formatBytes(double size) { double k = size / 1024.0; double m = k / 1024.0; double g = m / 1024.0; DecimalFormat dec = new DecimalFormat("0"); if (g > 1) { return dec.format(g).concat("G"); } else if (m > 1) { return dec.format(m).concat("M"); } else if (k > 1) { return dec.format(k).concat("K"); } else { return dec.format(size).concat("B"); } } public static String formatMBytes(int size) { int g = size / 1024; DecimalFormat dec = new DecimalFormat("0"); if (g > 1) { return dec.format(g).concat("G"); } else { return dec.format(size).concat("M"); } } /** * Renders the Table header border, based on the map of provided headers. * * @param headers Map of headers containing meta information e.g. name+width of header * @return Returns the rendered header border as String */ public static String getHeaderBorder(Map headers) { final StringBuilder headerBorder = new StringBuilder(); for (TableHeader header : headers.values()) { headerBorder.append(CommonUtils.padRight(" ", header.getWidth() + 2, '-')); } headerBorder.append("\n"); return headerBorder.toString(); } /** * Renders a line of application logging output. */ public static String renderApplicationLogEntry(ApplicationLog logEntry) { StringBuilder logLine = new StringBuilder(); /** SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); logLine.append(dateFormat.format(logEntry.getTimestamp())).append(" "); String source; if (logEntry.getSourceName().equals("App")) { source = String.format("[%s/%s]", logEntry.getSourceName(), logEntry.getSourceId()); } else { source = String.format("[%s]", logEntry.getSourceName()); } logLine.append(String.format("%-10s", source)); logLine.append(logEntry.getMessageType().name().substring("STD".length())).append(" "); logLine.append(logEntry.getMessage()); return logLine.toString(); } /** * Renders a textual representation of a Application {@link CloudApplication} * *
          • Names of the Applications
          • Number of Instances
          • Current State (Health)
          • Used * Memory
          • The comma-separated list of Uris
          • The comma-separated list of Services
            • */ public static String renderCloudApplicationDataAsTable(CloudApplication application, ApplicationStats stats) { StringBuilder sb = new StringBuilder("\n"); sb.append(String.format("application: %s\n", application.getName())); sb.append(String.format("state: %s\n", application.getState())); sb.append(String.format("instances: %d/%d\n", application.getRunningInstances(), application.getInstances())); sb.append(String.format("usage: %s x %s instance\n", formatMBytes(application.getMemory()), application .getInstances())); sb.append(String.format("urls: %s\n", CommonUtils.collectionToCommaDelimitedString(application.getUris()))); sb.append(String.format("services: %s\n", CommonUtils.collectionToCommaDelimitedString(application .getServices()))); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("instance")); table.getHeaders().put(COLUMN_2, new TableHeader("state")); table.getHeaders().put(COLUMN_3, new TableHeader("cpu")); table.getHeaders().put(COLUMN_4, new TableHeader("memory")); table.getHeaders().put(COLUMN_5, new TableHeader("disk")); for (InstanceStats instance : stats.getRecords()) { TableRow tableRow = new TableRow(); String index = instance.getId(); table.getHeaders().get(COLUMN_1).updateWidth(String.valueOf(index).length()); tableRow.addValue(COLUMN_1, String.valueOf(index)); String state = instance.getState().toString().toLowerCase(); table.getHeaders().get(COLUMN_2).updateWidth(String.valueOf(state).length()); tableRow.addValue(COLUMN_2, String.valueOf(state)); String cpu = String.format("%.2f%%", instance.getUsage().getCpu() * 100); table.getHeaders().get(COLUMN_3).updateWidth(String.valueOf(cpu).length()); tableRow.addValue(COLUMN_3, String.valueOf(cpu)); String memory = String.format("%s of %s", formatBytes(instance.getUsage().getMem()), formatBytes(instance.getMemQuota())); table.getHeaders().get(COLUMN_4).updateWidth(String.valueOf(memory).length()); tableRow.addValue(COLUMN_4, String.valueOf(memory)); String disk = String.format("%s of %s", formatBytes(instance.getUsage().getDisk()), formatBytes(instance.getDiskQuota())); table.getHeaders().get(COLUMN_5).updateWidth(String.valueOf(disk).length()); tableRow.addValue(COLUMN_5, String.valueOf(disk)); table.getRows().add(tableRow); } sb.append("\n").append(renderTextTable(table)); return sb.toString(); } /** * Renders a textual representation of the list of provided {@link CloudApplication} * * The following information is shown: * public static String renderEnvVarDataAsTable(CloudApplication application) { *
              • Names of the Applications
              • Number of Instances
              • Current State (Health)
              • Used * Memory
              • The comma-separated list of Uris
              • The comma-separated list of Services
                • * * @param applications List of {@CloudApplication} * @return The rendered table representation as String */ public static String renderCloudApplicationsDataAsTable(List applications) { Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("name")); table.getHeaders().put(COLUMN_2, new TableHeader("status")); table.getHeaders().put(COLUMN_3, new TableHeader("instances")); table.getHeaders().put(COLUMN_4, new TableHeader("memory")); table.getHeaders().put(COLUMN_5, new TableHeader("disk")); table.getHeaders().put(COLUMN_6, new TableHeader("url")); Comparator nameComparator = new Comparator() { public int compare(CloudApplication a, CloudApplication b) { return a.getName().compareTo(b.getName()); } }; Collections.sort(applications, nameComparator); for (CloudApplication application : applications) { TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(application.getName().length()); tableRow.addValue(COLUMN_1, application.getName()); String status = renderHealthStatus(application); table.getHeaders().get(COLUMN_2).updateWidth(status.length()); tableRow.addValue(COLUMN_2, status); String instances = String.format("%d/%d", application.getRunningInstances(), application.getInstances()); table.getHeaders().get(COLUMN_3).updateWidth(String.valueOf(instances).length()); tableRow.addValue(COLUMN_3, String.valueOf(instances)); String memory = formatMBytes(application.getMemory()); table.getHeaders().get(COLUMN_4).updateWidth(String.valueOf(memory).length()); tableRow.addValue(COLUMN_4, String.valueOf(memory)); String disk = formatMBytes(application.getDiskQuota()); table.getHeaders().get(COLUMN_5).updateWidth(String.valueOf(disk).length()); tableRow.addValue(COLUMN_5, String.valueOf(disk)); String uris = CommonUtils.collectionToCommaDelimitedString(application.getUris()); table.getHeaders().get(COLUMN_6).updateWidth(uris.length()); tableRow.addValue(COLUMN_6, uris); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders the help text. If the callers is logged in successfully the full information is rendered if not only * basic Cloud Foundry information is rendered and returned as String. * * @param cloudInfo Contains the information about the Cloud Foundry environment * @param target The target Url from which the information was obtained * @param org * @param space * @return Returns a formatted String for console output */ public static String renderCloudInfoFormattedAsString(CloudInfo cloudInfo, String target, String org, String space) { final String cloudInfoMessage = "\n" + UiUtils.HORIZONTAL_LINE + String.format("API endpoint: %s (API version: %s) \n", target, cloudInfo.getVersion()) + String.format("user: %s\n", cloudInfo.getUser()) + String.format("org: %s\n", org) + String.format("space: %s\n", space) + UiUtils.HORIZONTAL_LINE; return cloudInfoMessage; } /** * Renders a textual representation of a application's environment variables */ StringBuilder sb = new StringBuilder("\n"); sb.append(String.format("Environment for application '%s'\n", application.getName())); final List envVars = application.getEnv(); for (String envVar : envVars) { sb.append(envVar).append("\n"); } return sb.toString(); } /** * Renders a textual representation of provided parameter map. * * @param parameters Map of parameters (key, value) * @return The rendered table representation as String */ public static String renderParameterInfoDataAsTable(Map parameters) { final Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("Parameter")); table.getHeaders().put(COLUMN_2, new TableHeader("Value (Configured or Default)")); for (Entry entry : parameters.entrySet()) { final TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(entry.getKey().length()); tableRow.addValue(COLUMN_1, entry.getKey()); table.getHeaders().get(COLUMN_2).updateWidth(entry.getValue() != null ? entry.getValue().length() : 0); tableRow.addValue(COLUMN_2, entry.getValue()); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a sorted textual representation of the list of provided {@link CloudService} * * The following information is shown: * * @param services * @param servicesToApps * @return The rendered table representation as String */ public static String renderServiceDataAsTable(List services, Map> servicesToApps) { Comparator nameComparator = new Comparator() { public int compare(CloudService a, CloudService b) { return a.getName().compareTo(b.getName()); } }; Collections.sort(services, nameComparator); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("name")); table.getHeaders().put(COLUMN_2, new TableHeader("service")); table.getHeaders().put(COLUMN_3, new TableHeader("plan")); table.getHeaders().put(COLUMN_4, new TableHeader("bound apps")); for (CloudService service : services) { TableRow tableRow = new TableRow(); String name = service.getName(); String label; String plan; if (service.isUserProvided()) { label = "user-provided"; plan = ""; } else { label = service.getLabel(); plan = service.getPlan(); } table.getHeaders().get(COLUMN_1).updateWidth(name.length()); tableRow.addValue(COLUMN_1, name); table.getHeaders().get(COLUMN_2).updateWidth(label.length()); tableRow.addValue(COLUMN_2, label); table.getHeaders().get(COLUMN_3).updateWidth(plan.length()); tableRow.addValue(COLUMN_3, plan); final List appNames = servicesToApps.get(name); final String appNamesString = CommonUtils.collectionToCommaDelimitedString(appNames); table.getHeaders().get(COLUMN_4).updateWidth(appNamesString.length()); tableRow.addValue(COLUMN_4, appNamesString); table.getRows().add(tableRow); } return renderTextTable(table); } * Renders a sorted textual representation of the list of provided {@link CloudFoundryClient, @link * CloudServiceOffering} * * @param serviceOfferings * @return The rendered table representation as String */ public static String renderServiceOfferingDataAsTable(List serviceOfferings) { Comparator labelComparator = new Comparator() { public int compare(CloudServiceOffering a, CloudServiceOffering b) { return a.getLabel().compareTo(b.getLabel()); } }; Collections.sort(serviceOfferings, labelComparator); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("service")); table.getHeaders().put(COLUMN_2, new TableHeader("plans")); table.getHeaders().put(COLUMN_3, new TableHeader("description")); List CloudServicePlanNames; for (CloudServiceOffering serviceOffering : serviceOfferings) { TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(serviceOffering.getLabel().length()); tableRow.addValue(COLUMN_1, serviceOffering.getLabel()); CloudServicePlanNames = new ArrayList(); for (CloudServicePlan servicePlan : serviceOffering.getCloudServicePlans()) { CloudServicePlanNames.add(servicePlan.getName()); } table.getHeaders().get(COLUMN_2).updateWidth(CloudServicePlanNames.toString().length() - 1); tableRow.addValue(COLUMN_2, CloudServicePlanNames.toString().substring(1, CloudServicePlanNames.toString ().length() - 1)); table.getHeaders().get(COLUMN_3).updateWidth(serviceOffering.getDescription().length()); tableRow.addValue(COLUMN_3, serviceOffering.getDescription()); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a textual representation of the provided {@link Table} * * @param table Table data {@link Table} * @return The rendered table representation as String */ public static String renderTextTable(Table table) { final String padding = " "; final String headerBorder = getHeaderBorder(table.getHeaders()); final StringBuilder textTable = new StringBuilder(); for (TableHeader header : table.getHeaders().values()) { textTable.append(padding + CommonUtils.padRight(header.getName(), header.getWidth())); } textTable.append("\n"); textTable.append(headerBorder); for (TableRow row : table.getRows()) { for (Entry entry : table.getHeaders().entrySet()) { textTable.append(padding + CommonUtils.padRight(row.getValue(entry.getKey()), entry.getValue() .getWidth())); } textTable.append("\n"); } return textTable.toString(); } private static String renderHealthStatus(CloudApplication app) { String state = app.getState().toString(); if (state.equals("STARTED")) { int running_instances = app.getRunningInstances(); int expected_instances = app.getInstances(); if (expected_instances > 0) { float ratio = running_instances / expected_instances; if (ratio == 1.0) return "running"; else return new Float((ratio * 100)).intValue() + "%"; } else { return "n/a"; } } else { return state.toLowerCase(); } } >>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d }
Solution content
 * @since 1.0.0
 *
 */
public final class UiUtils {
	public static final String HORIZONTAL_LINE = "-------------------------------------------------------------------------------\n";

	public static final int COLUMN_1 = 1;
	public static final int COLUMN_2 = 2;
	public static final int COLUMN_3 = 3;
	public static final int COLUMN_4 = 4;
	public static final int COLUMN_5 = 5;
	public static final int COLUMN_6 = 6;

	/**
	 * Prevent instantiation.
	 *
	 */
	private UiUtils() {
		throw new AssertionError();
	}

	/**
	 * Renders a textual representation of a Application {@link CloudApplication}
	 *
	 * 
    *
  • Names of the Applications
  • *
  • Number of Instances
  • *
  • Current State (Health)
  • *
  • Used Memory
  • *
  • The comma-separated list of Uris
  • *
  • The comma-separated list of Services
  • *
      */ public static String renderCloudApplicationDataAsTable(CloudApplication application, ApplicationStats stats) { StringBuilder sb = new StringBuilder("\n"); sb.append(String.format("application: %s\n", application.getName())); sb.append(String.format("state: %s\n", application.getState())); sb.append(String.format("instances: %d/%d\n", application.getRunningInstances(), application.getInstances())); sb.append(String.format("usage: %s x %s instance\n", formatMBytes(application.getMemory()), application.getInstances())); sb.append(String.format("urls: %s\n", CommonUtils.collectionToCommaDelimitedString(application.getUris()))); sb.append(String.format("services: %s\n", CommonUtils.collectionToCommaDelimitedString(application.getServices()))); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("instance")); table.getHeaders().put(COLUMN_2, new TableHeader("state")); table.getHeaders().put(COLUMN_3, new TableHeader("cpu")); table.getHeaders().put(COLUMN_4, new TableHeader("memory")); table.getHeaders().put(COLUMN_5, new TableHeader("disk")); for (InstanceStats instance : stats.getRecords()) { TableRow tableRow = new TableRow(); String index = instance.getId(); table.getHeaders().get(COLUMN_1).updateWidth(String.valueOf(index).length()); tableRow.addValue(COLUMN_1, String.valueOf(index)); String state = instance.getState().toString().toLowerCase(); table.getHeaders().get(COLUMN_2).updateWidth(String.valueOf(state).length()); tableRow.addValue(COLUMN_2, String.valueOf(state)); InstanceStats.Usage usage = instance.getUsage(); if (usage != null) { String cpu = String.format("%.2f%%", usage.getCpu() * 100); table.getHeaders().get(COLUMN_3).updateWidth(String.valueOf(cpu).length()); tableRow.addValue(COLUMN_3, String.valueOf(cpu)); String memory = String.format("%s of %s", formatBytes(usage.getMem()), formatBytes(instance.getMemQuota())); table.getHeaders().get(COLUMN_4).updateWidth(String.valueOf(memory).length()); tableRow.addValue(COLUMN_4, String.valueOf(memory)); String disk = String.format("%s of %s", formatBytes(usage.getDisk()), formatBytes(instance.getDiskQuota())); table.getHeaders().get(COLUMN_5).updateWidth(String.valueOf(disk).length()); tableRow.addValue(COLUMN_5, String.valueOf(disk)); } table.getRows().add(tableRow); } sb.append("\n").append(renderTextTable(table)); return sb.toString(); } /** * Renders a textual representation of the list of provided {@link CloudApplication} * * The following information is shown: * *
        *
      • Names of the Applications
      • *
      • Number of Instances
      • *
      • Current State (Health)
      • *
      • Used Memory
      • *
      • The comma-separated list of Uris
      • *
      • The comma-separated list of Services
      • *
          * * @param applications List of {@CloudApplication} * @return The rendered table representation as String * */ public static String renderCloudApplicationsDataAsTable(List applications) { Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("name")); table.getHeaders().put(COLUMN_2, new TableHeader("status")); table.getHeaders().put(COLUMN_3, new TableHeader("instances")); table.getHeaders().put(COLUMN_4, new TableHeader("memory")); table.getHeaders().put(COLUMN_5, new TableHeader("disk")); table.getHeaders().put(COLUMN_6, new TableHeader("url")); Comparator nameComparator = new Comparator() { public int compare(CloudApplication a, CloudApplication b) { return a.getName().compareTo(b.getName()); } }; Collections.sort(applications, nameComparator); for (CloudApplication application : applications) { TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(application.getName().length()); tableRow.addValue(COLUMN_1, application.getName()); String status = renderHealthStatus(application); table.getHeaders().get(COLUMN_2).updateWidth(status.length()); tableRow.addValue(COLUMN_2, status); String instances = String.format("%d/%d", application.getRunningInstances(), application.getInstances()); table.getHeaders().get(COLUMN_3).updateWidth(String.valueOf(instances).length()); tableRow.addValue(COLUMN_3, String.valueOf(instances)); String memory = formatMBytes(application.getMemory()); table.getHeaders().get(COLUMN_4).updateWidth(String.valueOf(memory).length()); tableRow.addValue(COLUMN_4, String.valueOf(memory)); String disk = formatMBytes(application.getDiskQuota()); table.getHeaders().get(COLUMN_5).updateWidth(String.valueOf(disk).length()); tableRow.addValue(COLUMN_5, String.valueOf(disk)); String uris = CommonUtils.collectionToCommaDelimitedString(application.getUris()); table.getHeaders().get(COLUMN_6).updateWidth(uris.length()); tableRow.addValue(COLUMN_6, uris); table.getRows().add(tableRow); } return renderTextTable(table); } private static String renderHealthStatus(CloudApplication app) { String state = app.getState().toString(); if (state.equals("STARTED")) { int running_instances = app.getRunningInstances(); int expected_instances = app.getInstances(); if (expected_instances > 0) { float ratio = running_instances / expected_instances; if (ratio == 1.0) return "running"; else return new Float((ratio * 100)).intValue() + "%"; } else { return "n/a"; } } else { return state.toLowerCase(); } } /** * Renders a textual representation of a application's environment variables */ public static String renderEnvVarDataAsTable(CloudApplication application) { StringBuilder sb = new StringBuilder("\n"); sb.append(String.format("Environment for application '%s'\n", application.getName())); final List envVars = application.getEnv(); for (String envVar : envVars) { sb.append(envVar).append("\n"); } return sb.toString(); } /** * Renders a sorted textual representation of the list of provided {@link CloudFoundryClient, @link CloudServiceOffering} * * @param serviceOfferings * @return The rendered table representation as String * */ public static String renderServiceOfferingDataAsTable(List serviceOfferings) { Comparator labelComparator = new Comparator() { public int compare(CloudServiceOffering a, CloudServiceOffering b) { return a.getLabel().compareTo(b.getLabel()); } }; Collections.sort(serviceOfferings, labelComparator); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("service")); table.getHeaders().put(COLUMN_2, new TableHeader("plans")); table.getHeaders().put(COLUMN_3, new TableHeader("description")); List CloudServicePlanNames; for (CloudServiceOffering serviceOffering : serviceOfferings) { TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(serviceOffering.getLabel().length()); tableRow.addValue(COLUMN_1, serviceOffering.getLabel()); CloudServicePlanNames = new ArrayList(); for (CloudServicePlan servicePlan : serviceOffering.getCloudServicePlans()) { CloudServicePlanNames.add(servicePlan.getName()); } table.getHeaders().get(COLUMN_2).updateWidth(CloudServicePlanNames.toString().length() - 1); tableRow.addValue(COLUMN_2, CloudServicePlanNames.toString().substring(1, CloudServicePlanNames.toString().length() - 1)); table.getHeaders().get(COLUMN_3).updateWidth(serviceOffering.getDescription().length()); tableRow.addValue(COLUMN_3, serviceOffering.getDescription()); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a sorted textual representation of the list of provided {@link CloudService} * * The following information is shown: * * * @param services * @param servicesToApps * @return The rendered table representation as String * */ public static String renderServiceDataAsTable(List services, Map> servicesToApps) { Comparator nameComparator = new Comparator() { public int compare(CloudService a, CloudService b) { return a.getName().compareTo(b.getName()); } }; Collections.sort(services, nameComparator); Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("name")); table.getHeaders().put(COLUMN_2, new TableHeader("service")); table.getHeaders().put(COLUMN_3, new TableHeader("plan")); table.getHeaders().put(COLUMN_4, new TableHeader("bound apps")); for (CloudService service : services) { TableRow tableRow = new TableRow(); String name = service.getName(); String label; String plan; if (service.isUserProvided()) { label = "user-provided"; plan = ""; } else { label = service.getLabel(); plan = service.getPlan(); } table.getHeaders().get(COLUMN_1).updateWidth(name.length()); tableRow.addValue(COLUMN_1, name); table.getHeaders().get(COLUMN_2).updateWidth(label.length()); tableRow.addValue(COLUMN_2, label); table.getHeaders().get(COLUMN_3).updateWidth(plan.length()); tableRow.addValue(COLUMN_3, plan); final List appNames = servicesToApps.get(name); final String appNamesString = CommonUtils.collectionToCommaDelimitedString(appNames); table.getHeaders().get(COLUMN_4).updateWidth(appNamesString.length()); tableRow.addValue(COLUMN_4, appNamesString); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a textual representation of provided parameter map. * * @param parameters Map of parameters (key, value) * @return The rendered table representation as String * */ public static String renderParameterInfoDataAsTable(Map parameters) { final Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("Parameter")); table.getHeaders().put(COLUMN_2, new TableHeader("Value (Configured or Default)")); for (Entry entry : parameters.entrySet()) { final TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(entry.getKey().length()); tableRow.addValue(COLUMN_1, entry.getKey()); table.getHeaders().get(COLUMN_2).updateWidth(entry.getValue() != null ? entry.getValue().length() : 0); tableRow.addValue(COLUMN_2, entry.getValue()); table.getRows().add(tableRow); } return renderTextTable(table); } /** * Renders a textual representation of the provided {@link Table} * * @param table Table data {@link Table} * @return The rendered table representation as String */ public static String renderTextTable(Table table) { final String padding = " "; final String headerBorder = getHeaderBorder(table.getHeaders()); final StringBuilder textTable = new StringBuilder(); for (TableHeader header : table.getHeaders().values()) { textTable.append(padding + CommonUtils.padRight(header.getName(), header.getWidth())); } textTable.append("\n"); textTable.append(headerBorder); for (TableRow row : table.getRows()) { for (Entry entry : table.getHeaders().entrySet()) { textTable.append(padding + CommonUtils.padRight(row.getValue(entry.getKey()), entry.getValue().getWidth())); } textTable.append("\n"); } return textTable.toString(); } /** * Renders the help text. If the callers is logged in successfully the full * information is rendered if not only basic Cloud Foundry information is * rendered and returned as String. * * * * @param cloudInfo Contains the information about the Cloud Foundry environment * @param target The target Url from which the information was obtained * @param org * @param space * @return Returns a formatted String for console output */ public static String renderCloudInfoFormattedAsString(CloudInfo cloudInfo, String target, String org, String space) { final String cloudInfoMessage = "\n" + UiUtils.HORIZONTAL_LINE + String.format("API endpoint: %s (API version: %s) \n", target, cloudInfo.getVersion()) + String.format("user: %s\n", cloudInfo.getUser()) + String.format("org: %s\n", org) + String.format("space: %s\n", space) + UiUtils.HORIZONTAL_LINE; return cloudInfoMessage; } /** * Renders a line of application logging output. */ public static String renderApplicationLogEntry(ApplicationLog logEntry) { StringBuilder logLine = new StringBuilder(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); logLine.append(dateFormat.format(logEntry.getTimestamp())).append(" "); String source; if (logEntry.getSourceName().equals("App")) { source = String.format("[%s/%s]", logEntry.getSourceName(), logEntry.getSourceId()); } else { source = String.format("[%s]", logEntry.getSourceName()); } logLine.append(String.format("%-10s", source)); logLine.append(logEntry.getMessageType().name().substring("STD".length())).append(" "); logLine.append(logEntry.getMessage()); return logLine.toString(); } /** * Renders the Table header border, based on the map of provided headers. * * @param headers Map of headers containing meta information e.g. name+width of header * @return Returns the rendered header border as String */ public static String getHeaderBorder(Map headers) { final StringBuilder headerBorder = new StringBuilder(); for (TableHeader header : headers.values()) { headerBorder.append(CommonUtils.padRight(" ", header.getWidth() + 2, '-')); } headerBorder.append("\n"); return headerBorder.toString(); } public static String formatMBytes(int size) { int g = size / 1024; DecimalFormat dec = new DecimalFormat("0"); if (g > 1) { return dec.format(g).concat("G"); } else { return dec.format(size).concat("M"); } } public static String formatBytes(double size) { double k = size / 1024.0; double m = k / 1024.0; double g = m / 1024.0; DecimalFormat dec = new DecimalFormat("0"); if (g > 1) { return dec.format(g).concat("G"); } else if (m > 1) { return dec.format(m).concat("M"); } else if (k > 1) { return dec.format(k).concat("K"); } else { return dec.format(size).concat("B"); } } }
File
UiUtils.java
Developer's decision
Manual
Kind of conflict
Attribute
Comment
Method declaration
Chunk
Conflicting content
    }

<<<<<<< HEAD
		assertTrue(mojo.isNoStart());
=======
    public void testGetUrlSpecifiedRandomWord() throws Exception {
        Push mojo = setupMojo();
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        doReturn("custom-${randomWord}.expliciturl.com").when(mojo).getCommandlineProperty(SystemProperties.URL);
Solution content
/*
 * Copyright 2009-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cloudfoundry.maven;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.maven.artifact.Artifact;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.apache.maven.plugin.testing.stubs.StubArtifactRepository;
import org.cloudfoundry.client.lib.CloudFoundryClient;
import org.cloudfoundry.client.lib.domain.CloudDomain;
import org.cloudfoundry.maven.common.SystemProperties;

/**
 *
 * @author Gunnar Hillert
 * @author Scott Frederick
 * @since 1.0.0
 *
 */
public class AbstractApplicationAwareCloudFoundryMojoTest extends AbstractMojoTestCase {

	/**
	 * @see junit.framework.TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
	}

	/**
	 * @throws Exception
	 */
	public void testGetUrlDefaultNoAppName() throws Exception {

		Push mojo = setupMojo();

		setupClient(mojo);

		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.URL);
		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.APP_NAME);

		List uris = mojo.getAllUris();
		assertEquals(1, uris.size());
		assertEquals("cf-maven-tests.apps.cloudfoundry.com", uris.get(0));

	}

	public void testGetUrlDefaultAppName() throws Exception {
		Push mojo = setupMojo();

		setupClient(mojo);

		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.URL);
		doReturn("myapp").when(mojo).getCommandlineProperty(SystemProperties.APP_NAME);

		List uris = mojo.getAllUris();
		assertEquals(1, uris.size());
		assertEquals("myapp.apps.cloudfoundry.com", uris.get(0));

	}

	public void testGetUrlSpecified() throws Exception {

		Push mojo = setupMojo();

		doReturn("custom.expliciturl.com").when(mojo).getCommandlineProperty(SystemProperties.URL);

		List uris = mojo.getAllUris();
		assertEquals(1, uris.size());
		assertEquals("custom.expliciturl.com", uris.get(0));

	}
	
	public void testGetUrlSpecifiedRandomWord() throws Exception {
	  Push mojo = setupMojo();

	  doReturn("custom-${randomWord}.expliciturl.com").when(mojo).getCommandlineProperty(SystemProperties.URL);

	  List uris = mojo.getAllUris();
	  assertEquals(1, uris.size());
	  Pattern p = Pattern.compile("^custom-[a-zA-Z]{5,5}.expliciturl.com$");
	  Matcher m = p.matcher(uris.get(0));
	  assertTrue(m.matches());
	}

	public void testGetNoStart() throws Exception {

		File testPom = new File( getBasedir(), "src/test/resources/test-pom.xml" );

		Push unspiedMojo = (Push) lookupMojo ( "push", testPom );

		Push mojo = spy(unspiedMojo);

		/**
		 * Injecting some test values as expressions are not evaluated.
		 */
		setVariableValueToObject( mojo, "noStart", Boolean.TRUE );
		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.NO_START);

		assertTrue(mojo.isNoStart());

	}
File
AbstractApplicationAwareCloudFoundryMojoTest.java
Developer's decision
Manual
Kind of conflict
Method invocation
Method signature
Variable
Chunk
Conflicting content
        file.mkdir();
        file.deleteOnExit();

<<<<<<< HEAD
		assertFalse(mojo.isNoStart());
=======
        final File artifactFile = File.createTempFile(
                "test", "artifact", file);
        artifactFile.deleteOnExit();
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        setVariableValueToObject(mojo, "localRepository",
                new StubArtifactRepository(file.getAbsolutePath()) {
Solution content

		assertFalse(mojo.isNoStart());

	}

	public void testGetEnv() throws Exception {
				File testPom = new File( getBasedir(), "src/test/resources/test-pom.xml" );

		Push unspiedMojo = (Push) lookupMojo ( "push", testPom );
		Push mojo = spy(unspiedMojo);

		Map env = new HashMap();
		env.put("JAVA_OPTS", "-XX:MaxPermSize=256m");

		/**
		 * Injecting some test values as expressions are not evaluated.
		 */
		setVariableValueToObject( mojo, "env", env);

		assertEquals("-XX:MaxPermSize=256m", mojo.getEnv().get("JAVA_OPTS"));
	}
	
	public void testRepositoryArtifactResolution() throws Exception {
		Push mojo = setupMojo();

		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.PATH);
		doReturn("http://api.cloudfoundry.com").when(mojo).getCommandlineProperty(SystemProperties.TARGET);
		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.APP_NAME);
		
		setVariableValueToObject(mojo, "artifact", "groupId:artifactId:version:type");
		
		final File file = File.createTempFile("cf-maven-plugin", "testrepo");
		file.delete();
		file.mkdir();
		file.deleteOnExit();

		final File artifactFile = File.createTempFile(
				"test", "artifact", file);
		artifactFile.deleteOnExit();

		setVariableValueToObject(mojo, "localRepository",
				new StubArtifactRepository(file.getAbsolutePath()) {
					@Override
					public String pathOf(Artifact artifact) {
						//Return tmp file name
						return artifactFile.getName();
					}
				});
		assertEquals(mojo.getPath(), artifactFile);
	}
	
	public void testGAVProcessing() throws Exception {
		Push mojo = setupMojo();

		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.PATH);
		doReturn("http://api.cloudfoundry.com").when(mojo).getCommandlineProperty(SystemProperties.TARGET);
		doReturn(null).when(mojo).getCommandlineProperty(SystemProperties.APP_NAME);

		{ //Test No Classifier or Type
			setVariableValueToObject(mojo, "artifact", "groupId:artifactId:version");
			
			boolean exception = false;
			try {
				mojo.createArtifactFromGAV();
			} catch(MojoExecutionException e) {
				exception = true;
			}
			if(!exception) {
				fail("Should have thrown a MojoExcecutionException");
			}
		}

		{ //Test No Classifier
			setVariableValueToObject(mojo, "artifact", "groupId:artifactId:version:type");
			
			Artifact artifact = mojo.createArtifactFromGAV();
			assertEquals("groupId", artifact.getGroupId());
			assertEquals("artifactId", artifact.getArtifactId());
			assertEquals("version", artifact.getVersion());
			assertEquals("type", artifact.getType());
			assertNull(artifact.getClassifier());
		}

		{ //All
			setVariableValueToObject(mojo, "artifact", "groupId:artifactId:version:type:classifier");
			
			Artifact artifact = mojo.createArtifactFromGAV();
			assertEquals("groupId", artifact.getGroupId());
			assertEquals("artifactId", artifact.getArtifactId());
			assertEquals("version", artifact.getVersion());
			assertEquals("type", artifact.getType());
			assertEquals("classifier", artifact.getClassifier());
		}

	}

	private Push setupMojo() throws Exception {
		File testPom = new File( getBasedir(), "src/test/resources/test-pom.xml" );

		Push unspiedMojo = (Push) lookupMojo ( "push", testPom );

		Push mojo = spy(unspiedMojo);

		/**
		 * Injecting some test values as expressions are not evaluated.
		 */
		setVariableValueToObject( mojo, "artifactId", "cf-maven-tests" );

		return mojo;
	}

	private void setupClient(Push mojo) {
		CloudFoundryClient client = mock(CloudFoundryClient.class);
		doReturn(new CloudDomain(null, "apps.cloudfoundry.com", null)).when(client).getDefaultDomain();
		doReturn(client).when(mojo).getClient();
	}

}
File
AbstractApplicationAwareCloudFoundryMojoTest.java
Developer's decision
Manual
Kind of conflict
Method invocation
Variable
Chunk
Conflicting content
        assertNull("Username by default is null.", mojo.getUsername());
    }

<<<<<<< HEAD
		assertEquals("cf-maven-tests", mojo.getAppname());
		assertNull(mojo.getAppStartupTimeout());
		assertNull(mojo.getCommand());
		assertNull(mojo.getBuildpack());
		assertNull(mojo.getDiskQuota());
		assertNull(mojo.getEnv());
		assertNull(mojo.getHealthCheckTimeout());
		assertNull(mojo.getInstances());
		assertNull(mojo.getMemory());
		assertFalse(mojo.isMergeEnv());
		assertFalse(mojo.isNoStart());
		assertNull(mojo.getPassword());
//		assertNull(mojo.getPath()); // cannot be null
		assertNull(mojo.getServices());
		assertNull(mojo.getUrls());
		assertNull(mojo.getUsername());
		
		assertNull("Password by default is null.", mojo.getPassword());
		assertEquals("cloud-foundry-credentials", mojo.getServer());
		assertNull("Target Url is not backed by a default value.", mojo.getTarget());
		assertNull("Username by default is null.", mojo.getUsername());
	}
=======
    /**
     * @see junit.framework.TestCase#setUp()
     */
    protected void setUp() throws Exception {
        super.setUp();
    }
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
		assertEquals("cf-maven-tests", mojo.getAppname());
		assertNull(mojo.getAppStartupTimeout());
		assertNull(mojo.getCommand());
		assertNull(mojo.getBuildpack());
		assertNull(mojo.getDiskQuota());
		assertNull(mojo.getEnv());
		assertNull(mojo.getHealthCheckTimeout());
		assertNull(mojo.getInstances());
		assertNull(mojo.getMemory());
		assertFalse(mojo.isMergeEnv());
		assertFalse(mojo.isNoStart());
		assertNull(mojo.getPassword());
//		assertNull(mojo.getPath()); // cannot be null
		assertNull(mojo.getServices());
		assertNull(mojo.getUrls());
		assertNull(mojo.getUsername());
		
		assertNull("Password by default is null.", mojo.getPassword());
		assertEquals("cloud-foundry-credentials", mojo.getServer());
		assertNull("Target Url is not backed by a default value.", mojo.getTarget());
		assertNull("Username by default is null.", mojo.getUsername());
	}
}
File
CheckDefaultParametersMojosTest.java
Developer's decision
Version 1
Kind of conflict
Comment
Method declaration
Method invocation
Chunk
Conflicting content
 * limitations under the License.
 */

<<<<<<< HEAD
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
=======
package org.cloudfoundry.maven.common;
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

import edu.emory.mathcs.backport.java.util.Collections;
import junit.framework.Assert;
Solution content
 * limitations under the License.
 */
package org.cloudfoundry.maven.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.emory.mathcs.backport.java.util.Collections;
import junit.framework.Assert;
File
UiUtilsTest.java
Developer's decision
Concatenation
Kind of conflict
Import
Package declaration
Chunk
Conflicting content
import edu.emory.mathcs.backport.java.util.Collections;
import junit.framework.Assert;
<<<<<<< HEAD
import org.cloudfoundry.client.lib.domain.ApplicationStats;
=======
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
import org.cloudfoundry.client.lib.domain.CloudApplication;
import org.cloudfoundry.client.lib.domain.CloudApplication.AppState;
import org.junit.Test;
Solution content
import edu.emory.mathcs.backport.java.util.Collections;
import junit.framework.Assert;
import org.cloudfoundry.client.lib.domain.ApplicationStats;
import org.cloudfoundry.client.lib.domain.CloudApplication;
import org.cloudfoundry.client.lib.domain.CloudApplication.AppState;
import org.junit.Test;
File
UiUtilsTest.java
Developer's decision
Version 1
Kind of conflict
Import
Chunk
Conflicting content

    private static final Logger LOGGER = LoggerFactory.getLogger(UiUtilsTest.class);

<<<<<<< HEAD
	@Test
	public void testRenderAppNullUsageTextTable() {
		@SuppressWarnings("unchecked")
		final List services = Collections.singletonList("mysql");
		@SuppressWarnings("unchecked")
		final List uris = Collections.singletonList("cf-rocks.api.run.pivotal.io");
		final CloudApplication app1 = new CloudApplication("first", "command",
				"buildpack", 1024, 2, uris, services, AppState.STARTED);

		Map instStatsNullUsage = new HashMap<>();
		instStatsNullUsage.put("cores", "2");
		instStatsNullUsage.put("name", "test-name");
		instStatsNullUsage.put("usage", null);

		Map instAttrs = new HashMap<>();
		instAttrs.put("state", "RUNNING");
		instAttrs.put("stats", instStatsNullUsage);

		Map attributes = new HashMap<>();
		attributes.put("id1", instAttrs);

		ApplicationStats applicationStats = new ApplicationStats(attributes);

		final String renderedAppTableAsString = UiUtils.renderCloudApplicationDataAsTable(app1, applicationStats);

		Assert.assertEquals(getExpectedStringFromResource("testRenderAppStatsNullUsageTextTable-expected-output.txt"),
				renderedAppTableAsString);
	}

	@Test
	public void testRenderAppUsageTextTable() {
		@SuppressWarnings("unchecked")
		final List services = Collections.singletonList("mysql");
		@SuppressWarnings("unchecked")
		final List uris = Collections.singletonList("cf-rocks.api.run.pivotal.io");

		final CloudApplication app1 = new CloudApplication("first", "command",
				"buildpack", 1024, 2, uris, services, AppState.STARTED);

		Map usageAttrs = new HashMap<>();
		usageAttrs.put("time", "1984-01-01 11:11:11 UTC");
		usageAttrs.put("cpu", "1e-3");
		usageAttrs.put("disk", "512");
		usageAttrs.put("mem", "513");

		Map instUsage = new HashMap<>();
		instUsage.put("cores", "3");
		instUsage.put("name", "test-name-2");
		instUsage.put("usage", usageAttrs);
		instUsage.put("disk_quota", "1025");
		instUsage.put("port", "2020");
		instUsage.put("mem_quota", "613");
		instUsage.put("uris", "uri1.com, uri2.org");
		instUsage.put("fds_quota", "99");
		instUsage.put("host", "test-host");
		instUsage.put("uptime", "1e-2");

		Map instAttrs = new HashMap<>();
		instAttrs.put("state", "RUNNING");
		instAttrs.put("stats", instUsage);

		Map attributes = new HashMap<>();
		attributes.put("id1", instAttrs);

		ApplicationStats applicationStats = new ApplicationStats(attributes);

		final String renderedAppTableAsString = UiUtils.renderCloudApplicationDataAsTable(app1, applicationStats);

		Assert.assertEquals(getExpectedStringFromResource("testRenderAppStatsTextTable-expected-output.txt"),
				renderedAppTableAsString);
	}

	private static String getExpectedStringFromResource(String resourceFile) {
		String expectedString = null;
		try {
			InputStream resourceAsStream = UiUtilsTest.class.getResourceAsStream(resourceFile);
			Assert.assertNotNull("Expected string file " + resourceFile + " not found", resourceAsStream);
			expectedString = FileCopyUtils.copyToString(new InputStreamReader(resourceAsStream));
		}
		catch (IOException e) {
			e.printStackTrace();
			Assert.fail();
		}
		Assert.assertNotNull("Expected string file " + resourceFile + " not readable", expectedString);
		return expectedString;
	}

	@Test
	public void testRenderTextTable() {
		final List services = new ArrayList<>();

		services.add("mysql");
		services.add("MyMongoInstance");

		final List uris = new ArrayList<>();

		uris.add("cf-rocks.api.run.pivotal.io");
		uris.add("spring-rocks.api.run.pivotal.io");

		final CloudApplication app1 = new CloudApplication("first", "command",
				"buildpack", 512, 1, uris, services, AppState.STARTED);
		final CloudApplication app2 = new CloudApplication("second", "command",
				"buildpack", 1024, 2, uris, services, AppState.STOPPED);
=======
    @Test
    public void testRenderTextTable() {
        final List services = new ArrayList();

        services.add("mysql");
        services.add("MyMongoInstance");

        final List uris = new ArrayList();

        uris.add("cf-rocks.api.run.pivotal.io");
        uris.add("spring-rocks.api.run.pivotal.io");

        String expectedTableAsString = null;

        try {
            expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(
                    UiUtilsTest.class.getResourceAsStream("testRenderTextTable-expected-output.txt")));
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail();
        }

        Assert.assertNotNull(expectedTableAsString);

        final CloudApplication app1 = new CloudApplication("first", "command",
                "buildpack", 512, 1, uris, services, AppState.STARTED);
        final CloudApplication app2 = new CloudApplication("second", "command",
                "buildpack", 1024, 2, uris, services, AppState.STOPPED);
>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d

        final List applications = Arrays.asList(app1, app2);
Solution content
	private static final Logger LOGGER = LoggerFactory.getLogger(UiUtilsTest.class);

	@Test
	public void testRenderAppNullUsageTextTable() {
		@SuppressWarnings("unchecked")
		final List services = Collections.singletonList("mysql");
		@SuppressWarnings("unchecked")
		final List uris = Collections.singletonList("cf-rocks.api.run.pivotal.io");

		final CloudApplication app1 = new CloudApplication("first", "command",
				"buildpack", 1024, 2, uris, services, AppState.STARTED);

		Map instStatsNullUsage = new HashMap<>();
		instStatsNullUsage.put("cores", "2");
		instStatsNullUsage.put("name", "test-name");
		instStatsNullUsage.put("usage", null);

		Map instAttrs = new HashMap<>();
		instAttrs.put("state", "RUNNING");
		instAttrs.put("stats", instStatsNullUsage);

		Map attributes = new HashMap<>();
		attributes.put("id1", instAttrs);

		ApplicationStats applicationStats = new ApplicationStats(attributes);

		final String renderedAppTableAsString = UiUtils.renderCloudApplicationDataAsTable(app1, applicationStats);

		Assert.assertEquals(getExpectedStringFromResource("testRenderAppStatsNullUsageTextTable-expected-output.txt"),
				renderedAppTableAsString);
	}

	@Test
	public void testRenderAppUsageTextTable() {
		@SuppressWarnings("unchecked")
		final List services = Collections.singletonList("mysql");
		@SuppressWarnings("unchecked")
		final List uris = Collections.singletonList("cf-rocks.api.run.pivotal.io");

		final CloudApplication app1 = new CloudApplication("first", "command",
				"buildpack", 1024, 2, uris, services, AppState.STARTED);

		Map usageAttrs = new HashMap<>();
		usageAttrs.put("time", "1984-01-01 11:11:11 UTC");
		usageAttrs.put("cpu", "1e-3");
		usageAttrs.put("disk", "512");
		usageAttrs.put("mem", "513");

		Map instUsage = new HashMap<>();
		instUsage.put("cores", "3");
		instUsage.put("name", "test-name-2");
		instUsage.put("usage", usageAttrs);
		instUsage.put("disk_quota", "1025");
		instUsage.put("port", "2020");
		instUsage.put("mem_quota", "613");
		instUsage.put("uris", "uri1.com, uri2.org");
		instUsage.put("fds_quota", "99");
		instUsage.put("host", "test-host");
		instUsage.put("uptime", "1e-2");

		Map instAttrs = new HashMap<>();
		instAttrs.put("state", "RUNNING");
		instAttrs.put("stats", instUsage);

		Map attributes = new HashMap<>();
		attributes.put("id1", instAttrs);

		ApplicationStats applicationStats = new ApplicationStats(attributes);

		final String renderedAppTableAsString = UiUtils.renderCloudApplicationDataAsTable(app1, applicationStats);

		Assert.assertEquals(getExpectedStringFromResource("testRenderAppStatsTextTable-expected-output.txt"),
				renderedAppTableAsString);
	}

	private static String getExpectedStringFromResource(String resourceFile) {
		String expectedString = null;
		try {
			InputStream resourceAsStream = UiUtilsTest.class.getResourceAsStream(resourceFile);
			Assert.assertNotNull("Expected string file " + resourceFile + " not found", resourceAsStream);
			expectedString = FileCopyUtils.copyToString(new InputStreamReader(resourceAsStream));
		}
		catch (IOException e) {
			e.printStackTrace();
			Assert.fail();
		}
		Assert.assertNotNull("Expected string file " + resourceFile + " not readable", expectedString);
		return expectedString;
	}

	@Test
	public void testRenderTextTable() {
		final List services = new ArrayList<>();

		services.add("mysql");
		services.add("MyMongoInstance");

		final List uris = new ArrayList<>();

		uris.add("cf-rocks.api.run.pivotal.io");
		uris.add("spring-rocks.api.run.pivotal.io");

		final CloudApplication app1 = new CloudApplication("first", "command",
				"buildpack", 512, 1, uris, services, AppState.STARTED);
		final CloudApplication app2 = new CloudApplication("second", "command",
				"buildpack", 1024, 2, uris, services, AppState.STOPPED);

		final List applications = Arrays.asList(app1, app2);

		final String renderedTableAsString = UiUtils.renderCloudApplicationsDataAsTable(applications);

		LOGGER.info("\n" + renderedTableAsString);

		Assert.assertEquals(getExpectedStringFromResource("testRenderTextTable-expected-output.txt"),
				renderedTableAsString);
	}
}
File
UiUtilsTest.java
Developer's decision
Manual
Kind of conflict
Annotation
Method declaration
Method invocation
Method signature
Try statement
Variable
Chunk
Conflicting content
<<<<<<< HEAD

        LOGGER.info("\n" + renderedTableAsString);
		Assert.assertEquals(getExpectedStringFromResource("testRenderTextTable-expected-output.txt"),
				renderedTableAsString);
	}
=======
        Assert.assertEquals(expectedTableAsString, renderedTableAsString);
    }

>>>>>>> 9ca6e8ba6103e1de4352e24f14510352244eb67d
}
Solution content
		Assert.assertEquals(getExpectedStringFromResource("testRenderTextTable-expected-output.txt"),
				renderedTableAsString);
	}
}
File
UiUtilsTest.java
Developer's decision
Version 1
Kind of conflict
Method invocation