/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpHelper {

    static {
        // register the OpenSSLProtocolSocketFactory to allow for self-signed certificates
        com.urbancode.air.XTrustProvider.install();
    }
    
    final private DefaultHttpClient httpClient = new DefaultHttpClient();

    public void setUsernameAndPassword(String username, String password) {
        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(username, password);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, clientCredentials);
    }
    
    public String getContent(String url) {
        return getContentWithHeaders(url, null)
    }
    
    public String getContentWithHeaders(String url, Map<String, String> headerProps) {
        HttpGet httpGet = new HttpGet(url);
        try {
            if (headerProps) {
                for (def headerProp : headerProps.entrySet()) {
                    httpGet.setHeader(headerProp.key, headerProp.value)
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            int responseCode = response.getStatusLine().getStatusCode()
            if (!isGoodResponseCode(responseCode)) {
                throw new RuntimeException("Getting ${url} returned error code ${responseCode}")
            }
            return EntityUtils.toString(response.getEntity());
        }
        finally {
            httpGet.releaseConnection();
        }
    }

    public void postContent(String url, String content) {
        HttpPost httpPost = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(content)
            httpPost.setEntity(entity)
            HttpResponse response = httpClient.execute(httpPost);
            int responseCode = response.getStatusLine().getStatusCode()
            if (!isGoodResponseCode(responseCode)) {
                def responseContent = EntityUtils.toString(response.getEntity());
                throw new RuntimeException("Posting to ${url} returned error code ${responseCode}: ${responseContent}")
            }
        }
        finally {
            httpPost.releaseConnection();
        }
    }
    
    public void putContent(String url, String content) {
        putContentWithHeaders(url, content, null)
    }

    public void putContentWithHeaders(String url, String content, Map<String, String> headerProps) {
        HttpPut httpPut = new HttpPut(url);
        try {
            StringEntity entity = new StringEntity(content)
            httpPut.setEntity(entity)
            if (headerProps) {
                for (def headerProp : headerProps.entrySet()) {
                    httpPut.setHeader(headerProp.key, headerProp.value)
                }
            }
            HttpResponse response = httpClient.execute(httpPut);
            int responseCode = response.getStatusLine().getStatusCode()
            if (!isGoodResponseCode(responseCode)) {
                throw new RuntimeException("Putting to ${url} returned error code ${responseCode}")
            }
        }
        finally {
            httpPut.releaseConnection();
        }
    }

    private boolean isGoodResponseCode(int responseCode) {
        return responseCode >= 200 && responseCode < 300;
    }

}