/*
 *    MyGetUserAndPassword.java
 *    Copyright (C) 2005 New Zealand Digital Library, http://www.nzdl.org
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program 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 General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.greenstone.anttasks;

import java.net.Authenticator;
import java.net.PasswordAuthentication;      

/** A new ant task for as the setproxy task has a bug in it.
 * To use this task, the compiled class must be put in the classpath. add a taskdef line to the build.xml:
 * <taskdef name="mysetproxy" classname="MySetProxy" />
 * and call it like the following:
 *  <mysetproxy proxyhost="" proxyport="" proxyuser="" proxypassword=""/>
*/
public class MySetProxy 
    extends org.apache.tools.ant.Task {

    String host = null;
    String port = null;
    String user = null;
    String password = null;

    public void setProxyhost(String proxy_host) {
	host = proxy_host;
    }

    public void setProxyPort(int proxy_port) {
	port = Integer.toString(proxy_port);
    }

    public void setProxyuser(String proxy_user) {
	user = proxy_user;
    }
    
    public void setProxypassword(String proxy_password) {
	password = proxy_password;
    }

    public void execute() {

	try {
	    System.setProperty("http.proxyType", "4");
	    System.setProperty("http.proxyHost", host);
	    System.setProperty("http.proxyPort", port);
	    System.setProperty("http.proxySet", "true");
	    Authenticator.setDefault(new Authenticator(){ 
		    protected PasswordAuthentication getPasswordAuthentication(){ 
			return new PasswordAuthentication(user, new String(password).toCharArray()); 
		    } 
		}); 
	} catch (Exception e) {
	    System.err.println("MySetProxy Error: couldn't set up the proxy");    
	}
    }
}
