/*
 * $Id: shutdown.java,v 1.1 2005/10/10 13:59:09 rampil Exp $
 * LOGICAL-PARADOX.ORG
 * Copyright (C)2005 satoshi akabane(akabane@logical-paradox.org)
 *
 */
package org.logical_paradox.gdrn.shell.command;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import org.logical_paradox.rss.lookup.LookupFactory;
import org.logical_paradox.shell.Argument;
import org.logical_paradox.shell.Command;
import org.logical_paradox.shell.ResultCode;
import org.logical_paradox.shell.ShellEnv;
import org.logical_paradox.shell.exception.CommandExecutionException;
import org.logical_paradox.shell.exception.TerminationException;

/**
 * <pre>
 * ■shutdown
 * 
 * 【動作仕様】
 * サービス停止します。
 * 
 * 【書式】
 * shutdown [<DSR uri>] <サービス名>
 * </pre>
 * 
 * @author satoshi akabane@logical-paradox.org
 * @version $Revision: 1.1 $
 */
public class shutdown implements Command {
	// 使用方法
	public static final String USAGE = "services [<DSR-uri> [<service-type>]]";

	public String usage() {
		return USAGE;
	}
	public ResultCode execute(OutputStream arg0, ShellEnv arg1, Argument arg2) throws CommandExecutionException, TerminationException {
		String[] arguments = arg2 != null ? arg2.getArguments() : new String[0];
		String dsruri = arg1.getProperty("DEFAULT_DSR_URI");
		String serviceName = null;

		if(arguments == null || arguments.length == 0 || arguments.length > 2) {
			throw new CommandExecutionException();
		}
		if(arguments.length == 1) {
			serviceName = arguments[0];
		} else {
			dsruri = arguments[0];
			serviceName = arguments[1];
		}

		// 各サービスのスタブを取得する
		PrintWriter pw = new PrintWriter(arg0);
		try {
			pw.println("service shutting down..");
			pw.flush();
			sendShutdown(pw, dsruri, serviceName);
			pw.println("done.");
			pw.flush();
			pw.close();
		} catch(RemoteException re) {
			re.printStackTrace();
			throw new CommandExecutionException("RemoteException has been caused in communicating to remote server [serviceName:" + serviceName + "]");
		}
		// OK
		return new ResultCode(ResultCode.STATUS_OK);
	}
	/**
	 * サービスを停止する
	 * @param pw 出力先
	 * @param dsruri DSRのURI
	 * @param serviceName サービス名
	 * @throws RemoteException
	 */
	protected void sendShutdown(PrintWriter pw, String dsruri, String serviceName) throws RemoteException {
		try {
			LookupFactory.getLookup(dsruri).lookup(serviceName).shutdown(true);
		} catch(RemoteException re) {
			throw re;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RemoteException(e.getMessage());
		}
	}

}
