/*
 * (c) Copyright Sysdeo SA 2001, 2002.
 * All Rights Reserved.
 */

package com.sysdeo.eclipse.tomcat.actions;

import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

import org.eclipse.core.runtime.CoreException;

import com.sysdeo.eclipse.tomcat.TomcatLauncherPlugin;
import com.sysdeo.eclipse.tomcat.TomcatProject;

/**
 * RestartContextActionDelegate
 *
 */
public class RestartContextActionDelegate extends TomcatProjectAbstractActionDelegate {

	/**
	 * @see com.sysdeo.eclipse.tomcat.actions.TomcatProjectAbstractActionDelegate
	 * #doActionOn(com.sysdeo.eclipse.tomcat.TomcatProject)
	 */
	@Override
	public void doActionOn(final TomcatProject prj) throws CoreException {
		String path = TomcatLauncherPlugin.getManagerAppUrl();
		path += "/reload?path=" + prj.getWebPath();

		Authenticator.setDefault(new PasswordAuthenticator());

		try {
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.getContent();
			connection.disconnect();
			Authenticator.setDefault(null);

		} catch (final IOException e) {
			throw new TomcatActionException(e.getMessage()
				+ "The following url was used : \n" + path
				+ "\n\nCheck manager app settings (username and password)\n\n");
		}
	}

	/**
	 * PasswordAuthenticator
	 *
	 */
	static final class PasswordAuthenticator extends Authenticator {
		/**
		 * @see java.net.Authenticator#getPasswordAuthentication()
		 */
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			String user = TomcatLauncherPlugin.getManagerAppUser();
			String password = TomcatLauncherPlugin.getManagerAppPassword();
			return new PasswordAuthentication(user, password.toCharArray());
		}
	}
}
