package com.jware.util.xml;

import javax.servlet.http.HttpServletRequest;


import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jware.base.error.JwareApplicationException;

/**
 * @author jrmt
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class HttpClientUtil {

    protected static Log log = LogFactory.getLog( XHtmlUtils.class );

    private HttpClient httpClient;
	private GetMethodUtil getMethod = null;
	private PostMethodUtil postMethod = null;

    private String requestUserAgent = null;
    private String requestAccept = null;
    private String requestAcceptCharset = null;
    private String requestAcceptEncoding = null;
    private String requestAcceptLanguage = null;
    private String requestAcceptAuthorization = null;
    
	private String charset = null;
	private String getMethodContentType = null;
	private String postMethodContentType = null;
	
    private String sessionId = null;
    
    /**
     * 
     */
    public HttpClientUtil() {

        HttpState initialState = new HttpState();
        initialState.setCookiePolicy(CookiePolicy.RFC2109 );
        // A different cookie management spec can be selected
        // when desired
		
		httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
		httpClient.getHttpConnectionManager().
			getParams().setConnectionTimeout(30000);

        httpClient.setState(initialState);

    }


    public void copyRequestHeader(HttpServletRequest request) {
        
	  	requestUserAgent = request.getHeader("User-Agent");
	  	requestAccept = request.getHeader("Accept");
	  	requestAcceptCharset = request.getHeader("Accept-Charset");
	  	requestAcceptEncoding = request.getHeader("Accept-Encoding");
	  	requestAcceptLanguage = request.getHeader("Accept-Language");
	  	requestAcceptAuthorization = request.getHeader("Accept-Authorization");
	  	
    }

    public String submitGet(String url) throws JwareApplicationException {
        return submitGet(url, null);
    }
    
    public String submitGet(String url, NameValuePair[] nameValuePairs) 
    	throws JwareApplicationException {
        
        String result = null;
        
		getMethod = new GetMethodUtil(url);
		if( getMethodContentType != null ){
		    getMethod.setRequestHeader( "Content-Type", getMethodContentType);
		}
		if( requestUserAgent != null ){
		    getMethod.setRequestHeader( "User-Agent", requestUserAgent);
		}
		if( requestAccept != null ){
		    getMethod.setRequestHeader( "Accept", requestAccept);
		}
		if( requestAcceptEncoding != null ){
		    getMethod.setRequestHeader( "Accept-Encoding", requestAcceptEncoding);
		}
		if( requestAcceptLanguage != null ){
		    getMethod.setRequestHeader( "Accept-Language", requestAcceptLanguage);
		}
		if( sessionId != null ){
		    getMethod.setRequestHeader( "JSESSIONID", sessionId);
		}
		
		getMethod.setFollowRedirects(true);

		if( nameValuePairs != null && nameValuePairs.length > 0 ){
		    getMethod.setQueryString( nameValuePairs );
		}

		try {
		    
			int iGetResultCode = httpClient.executeMethod(getMethod);
			if( charset != null){
			    result = getMethod.getResponseBodyAsString( charset );
			} else {
			    result = getMethod.getResponseBodyAsString();
			}

			Header header = getMethod.getResponseHeader("Content-Type");
			String contentType = header.getValue();
			String tempCharset = null;
			if(getMethod != null){
				tempCharset = getMethod.getRequestCharSet();
			}
			if( contentType != null ){
//				if( contentType.indexOf("text/html") >= 0 && contentType.indexOf( "charset" ) < 0 ){
//				    if( charset != null ) {
//				        result = new String(result.getBytes("iso-8859-1"), charset);
//				    }
//				}
				if( contentType.indexOf("text/html") >= 0 && contentType.indexOf( "charset" ) < 0 ){
				    if( !StringUtils.isEmpty(charset) ) {
				        result = new String(result.getBytes("iso-8859-1"), charset);
				    }else if( !StringUtils.isEmpty(tempCharset)){
				        result = new String(result.getBytes("iso-8859-1"), tempCharset);					
					}
				}
			}

		} catch (Exception ex) {
		    
			ex.printStackTrace();
			throw new JwareApplicationException("E300001", ex );
			
		} finally {
		    getMethod.releaseConnection();
		}
        
        return result;
        
    }
    
    public byte[] submitGetByte(String url, NameValuePair[] nameValuePairs) 
		throws JwareApplicationException {
    
	    byte[] result = null;
	    
		getMethod = new GetMethodUtil(url);
		if( getMethodContentType != null ){
		    getMethod.setRequestHeader( "Content-Type", getMethodContentType);
		}
		if( requestUserAgent != null ){
		    getMethod.setRequestHeader( "User-Agent", requestUserAgent);
		}
		if( requestAccept != null ){
		    getMethod.setRequestHeader( "Accept", requestAccept);
		}
		if( requestAcceptEncoding != null ){
		    getMethod.setRequestHeader( "Accept-Encoding", requestAcceptEncoding);
		}
		if( requestAcceptLanguage != null ){
		    getMethod.setRequestHeader( "Accept-Language", requestAcceptLanguage);
		}
		if( sessionId != null ){
		    getMethod.setRequestHeader( "JSESSIONID", sessionId);
		}
		
	    getMethod.setFollowRedirects(true);
	
		if( nameValuePairs != null && nameValuePairs.length > 0 ){
		    getMethod.setQueryString( nameValuePairs );
		}
	
		try {
		    
			int iGetResultCode = httpClient.executeMethod(getMethod);
			result = getMethod.getResponseBody();
	
		} catch (Exception ex) {
		    
			ex.printStackTrace();
			throw new JwareApplicationException("E300001", ex );
			
		} finally {
		    getMethod.releaseConnection();
		}
	    
	    return result;
    
}

    
    public String submitPost(String url, NameValuePair[] nameValuePairs) 
    	throws JwareApplicationException {
        
        String result = null;
        
        postMethod = new PostMethodUtil(url);
		if( postMethodContentType != null ){
		    postMethod.setRequestHeader( "Content-Type", postMethodContentType);
		}
		if( requestUserAgent != null ){
		    postMethod.setRequestHeader( "User-Agent", requestUserAgent);
		}
		if( requestAccept != null ){
		    postMethod.setRequestHeader( "Accept", requestAccept);
		}
		if( requestAcceptEncoding != null ){
		    postMethod.setRequestHeader( "Accept-Encoding", requestAcceptEncoding);
		}
		if( requestAcceptLanguage != null ){
		    postMethod.setRequestHeader( "Accept-Language", requestAcceptLanguage);
		}
		if( sessionId != null ){
			postMethod.setRequestHeader( "JSESSIONID", sessionId);
		}
		
		if( nameValuePairs != null ){
		    postMethod.setRequestBody( nameValuePairs );
		}
		
		try {
		    
		    int iGetResultCode = httpClient.executeMethod(postMethod);
		    if( charset != null){
		        result = postMethod.getResponseBodyAsString(charset);
		    } else {
		        result = postMethod.getResponseBodyAsString();
		    }

			Header header = postMethod.getResponseHeader("Content-Type");
			String contentType = header.getValue();
			String tempCharset = null;
			if(getMethod != null){
				tempCharset = getMethod.getRequestCharSet();
			}
			if( contentType != null ){
//				if( contentType.indexOf("text/html") >= 0 && contentType.indexOf( "charset" ) < 0 ){
//				    if( charset != null ) {
//				        result = new String(result.getBytes("iso-8859-1"), charset);
//				    }
//				}
				if( contentType.indexOf("text/html") >= 0 && contentType.indexOf( "charset" ) < 0 ){
				    if( !StringUtils.isEmpty(charset) ) {
				        result = new String(result.getBytes("iso-8859-1"), charset);
				    }else if( !StringUtils.isEmpty(tempCharset)){
				        result = new String(result.getBytes("iso-8859-1"), tempCharset);					
					}
				}
			}
			
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new JwareApplicationException("E300001", ex );
		} finally {
		    postMethod.releaseConnection();
		}
        
        return result;
        
    }
    
    /**
     * @return Returns the getMethod.
     */
    public GetMethod getGetMethod() {
        return getMethod;
    }
    /**
     * @param getMethod The getMethod to set.
     */
    public void setGetMethod(GetMethodUtil getMethod) {
        this.getMethod = getMethod;
    }
    /**
     * @return Returns the postMethod.
     */
    public PostMethod getPostMethod() {
        return postMethod;
    }
    /**
     * @param postMethod The postMethod to set.
     */
    public void setPostMethod(PostMethodUtil postMethod) {
        this.postMethod = postMethod;
    }
    /**
     * @return Returns the requestAccept.
     */
    public String getRequestAccept() {
        return requestAccept;
    }
    /**
     * @param requestAccept The requestAccept to set.
     */
    public void setRequestAccept(String requestAccept) {
        this.requestAccept = requestAccept;
    }
    /**
     * @return Returns the requestAcceptAuthorization.
     */
    public String getRequestAcceptAuthorization() {
        return requestAcceptAuthorization;
    }
    /**
     * @param requestAcceptAuthorization The requestAcceptAuthorization to set.
     */
    public void setRequestAcceptAuthorization(String requestAcceptAuthorization) {
        this.requestAcceptAuthorization = requestAcceptAuthorization;
    }
    /**
     * @return Returns the requestAcceptCharset.
     */
    public String getRequestAcceptCharset() {
        return requestAcceptCharset;
    }
    /**
     * @param requestAcceptCharset The requestAcceptCharset to set.
     */
    public void setRequestAcceptCharset(String requestAcceptCharset) {
        this.requestAcceptCharset = requestAcceptCharset;
    }
    /**
     * @return Returns the requestAcceptEncoding.
     */
    public String getRequestAcceptEncoding() {
        return requestAcceptEncoding;
    }
    /**
     * @param requestAcceptEncoding The requestAcceptEncoding to set.
     */
    public void setRequestAcceptEncoding(String requestAcceptEncoding) {
        this.requestAcceptEncoding = requestAcceptEncoding;
    }
    /**
     * @return Returns the requestAcceptLanguage.
     */
    public String getRequestAcceptLanguage() {
        return requestAcceptLanguage;
    }
    /**
     * @param requestAcceptLanguage The requestAcceptLanguage to set.
     */
    public void setRequestAcceptLanguage(String requestAcceptLanguage) {
        this.requestAcceptLanguage = requestAcceptLanguage;
    }
    /**
     * @return Returns the requestUserAgent.
     */
    public String getRequestUserAgent() {
        return requestUserAgent;
    }
    /**
     * @param requestUserAgent The requestUserAgent to set.
     */
    public void setRequestUserAgent(String requestUserAgent) {
        this.requestUserAgent = requestUserAgent;
    }
    /**
     * @return Returns the charset.
     */
    public String getCharset() {
        return charset;
    }
    /**
     * @param charset The charset to set.
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }
    /**
     * @return Returns the httpClient.
     */
    public HttpClient getHttpClient() {
        return httpClient;
    }
    /**
     * @return Returns the content_type.
     */
    public String getGetMethodContentType() {
        return getMethodContentType;
    }
    /**
     * @param content_type The content_type to set.
     */
    public void setGetMethodContentType(String contentType) {
        this.getMethodContentType = contentType;
    }
    /**
     * @return Returns the content_type.
     */
    public String getPostMethodContentType() {
        return postMethodContentType;
    }
    /**
     * @param content_type The content_type to set.
     */
    public void setPostMethodContentType(String contentType) {
        this.postMethodContentType = contentType;
    }
	/**
	 * @return Returns the sessionId.
	 */
	public String getSessionId() {
		return sessionId;
	}
	/**
	 * @param sessionId The sessionId to set.
	 */
	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}
}


