/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.common;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;

import fr.gouv.finances.cp.xemelios.data.DataConfigurationException;

/**
 * Helper class for network access
 * @author chm
 */
public class NetAccess {
    
    /** Creates a new instance of NetAccess */
    public NetAccess() {
    }
    
    public static HttpClient getHttpClient() throws DataConfigurationException {
        String proxyHost = System.getProperty(Constants.SYS_PROP_PROXY_SERVER);
        String proxyPort = System.getProperty(Constants.SYS_PROP_PROXY_PORT);
        String proxyUser = System.getProperty(Constants.SYS_PROP_PROXY_USER);
        String sTmp = System.getProperty(Constants.SYS_PROP_PROXY_PASSWD);
        String proxyPasswd = sTmp!=null?Scramble.unScramblePassword(sTmp):null;
        int intProxyPort = 0;
        if(proxyPort!=null) {
            try {
                intProxyPort = Integer.parseInt(proxyPort);
            } catch(NumberFormatException nfEx) {
                throw new DataConfigurationException(proxyPort+" n'est pas un numéro de port valide.");
            }
        }

        HttpClient client = new HttpClient();
        //client.getParams().setAuthenticationPreemptive(true);   // check use of this
        HostConfiguration hc = new HostConfiguration();
        if(proxyHost!=null) {
            hc.setProxy(proxyHost,intProxyPort);
            client.setHostConfiguration(hc);
        }
        if(proxyUser!=null) {
            client.getState().setProxyCredentials(AuthScope.ANY,new UsernamePasswordCredentials(proxyUser,proxyPasswd));
        }
        return client;
    }
    
}
