krysalis-update/src/java/org/krysalis/depot/common/util/cli CommandLineParser.java,NONE,1.1 Options.java,NONE,1.1 CommandLine.java,NONE,1.1 Option.java,NONE,1.1 ParseException.java,NONE,1.1

Nick Chalko <[email protected]> Wed, 08 Dec 2004 09:06:37 +0000
Newsgroups gmane.comp.krysalis.cvs
Message-ID <[email protected]>
Update of /cvsroot/krysalis/krysalis-update/src/java/org/krysalis/depot/common/util/cli
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24726/src/java/org/krysalis/depot/common/util/cli

Added Files:
	CommandLineParser.java Options.java CommandLine.java 
	Option.java ParseException.java 
Log Message:
Copied from the apache incubator.

--- NEW FILE: Option.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.common.util.cli;

/**
 *
 * @author $Author: chalko $
 * @version $Revision: 1.1 $
 * 
 */
public class Option implements Comparable {
	private String m_opt = null;
	private String m_longOpt = null;
	private boolean m_hasArg = false;
	private String m_desc = null;

	public Option(String opt, boolean hasArg, String desc) {
		m_opt = opt;
		m_hasArg = hasArg;
		m_desc = desc;

	}

	public Option(String opt, String longOpt, boolean hasArg, String desc) {
		m_opt = opt;
		m_longOpt = longOpt;
		m_hasArg = hasArg;
		m_desc = desc;
	}

	/**
	 * Returns the desc.
	 * @return String
	 */
	public String getDesc() {
		return m_desc;
	}

	/**
	 * Returns the hasArg.
	 * @return boolean
	 */
	public boolean isHasArg() {
		return m_hasArg;
	}

	/**
	 * Returns the longOpt.
	 * @return String
	 */
	public String getLongOpt() {
		return m_longOpt;
	}

	/**
	 * Returns the opt.
	 * @return String
	 */
	public String getOpt() {
		return m_opt;
	}

	/**
	 * Sets the desc.
	 * @param desc The desc to set
	 */
	public void setDesc(String desc) {
		m_desc = desc;
	}

	/**
	 * Sets the hasArg.
	 * @param hasArg The hasArg to set
	 */
	public void setHasArg(boolean hasArg) {
		m_hasArg = hasArg;
	}

	/**
	 * Sets the longOpt.
	 * @param longOpt The longOpt to set
	 */
	public void setLongOpt(String longOpt) {
		m_longOpt = longOpt;
	}

	/**
	 * Sets the opt.
	 * @param opt The opt to set
	 */
	public void setOpt(String opt) {
		m_opt = opt;
	}

	public String toString() {
		return"-"
			+ m_opt
			+ ((null != m_longOpt) ? (" [or -" + m_longOpt) +"]": "")
			+ (m_hasArg ? " {argument}" : "") + " : " +  m_desc;
	}

	public int compareTo(Object other) {
		int comparison = -1;
		if (null == other) {
			comparison = -1;
		}
		else if (other instanceof Option) {
			Option otherOption = (Option) other;

			comparison = m_opt.compareTo(otherOption.m_opt);

			if (0 == comparison)
				if (null != m_longOpt)
					if (null != otherOption.m_longOpt)
						comparison = m_longOpt.compareTo(otherOption.m_longOpt);
					else
						comparison = -1;
				else if (null != otherOption.m_longOpt)
					comparison = -1;

			if (0 == comparison)
				comparison = (m_opt == otherOption.m_opt) ? 0 : -1;

			if (0 == comparison)
				comparison = (m_desc.compareTo(otherOption.m_desc));
		}
		else
			throw new IllegalArgumentException(
				"Not an 'Option':"
					+ other.getClass().getName()
					+ ":"
					+ other.toString());

		return comparison;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	public boolean equals(Object arg0) {
		// TODO Auto-generated method stub
		return m_opt.equals(((Option) arg0).m_opt);
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	public int hashCode() {
		// TODO Auto-generated method stub
		return m_opt.hashCode();
	}

}

--- NEW FILE: CommandLine.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.common.util.cli;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.krysalis.depot.common.util.collection.EntityList;
import org.krysalis.depot.common.util.debug.DebugUtils;
import org.krysalis.depot.common.util.debug.Dumpable;

/**
 *
 * @author $Author: chalko $
 * @version $Revision: 1.1 $
 * 
 */
public class CommandLine implements Dumpable {
	private static final String EMPTY_ARRAY[] = new String[0];

	private Map m_options = null;

	public CommandLine() {
		m_options = new HashMap();
	}

	public void addOption(Option option) {
		addOption(option, "");
	}

	public void addOption(Option option, String argument) {
		List values = (List) m_options.get(option);

		if (null == values) {
			values = new EntityList("Args:" + option.getOpt());
			m_options.put(option, values);
		}

		values.add(argument);
	}

	public String[] getMandatoryOptionValues(Option option)
		throws ParseException {
		String[] values = getOptionValues(option);

		if (null == values)
			throw new ParseException("Missing mandatory option : " + option);

		return values;
	}

	public String[] getOptionValues(Option option) {
		String array[] = null;

		List values = (List) m_options.get(option);

		if (null != values) {
			Object stuff[] = values.toArray();
			String sarray[] = new String[stuff.length];
			for (int i = 0; i < stuff.length; ++i) {
				sarray[i] = (String) stuff[i];
			}

			array = sarray;
		}
		else
			array = EMPTY_ARRAY;

		return array;
	}

	public String getMandatoryOptionValue(Option option)
		throws ParseException {
		return getMandatoryOptionValue(option, null);
	}

	public String getMandatoryOptionValue(Option option, String defaultValue)
		throws ParseException {
		String value = getOptionValue(option, defaultValue);

		if ((null == value) || (0 == value.length()))
			throw new ParseException("Missing mandatory option: " + option);

		return value;
	}

	public String getOptionValue(Option option) {
		return getOptionValue(option, null);
	}

	public String getOptionValue(Option option, String defaultValue) {

		String array[] = getOptionValues(option);
		String value = null;

		if (1 <= array.length) {
			value = array[0];
		}

		if (null == value)
			value = defaultValue;

		return value;
	}

	public boolean isSet(Option option) {
		return (null != m_options.get(option));
	}

	public boolean hasArguments() {
		return !(m_options.isEmpty());
	}

	public void print() {
		DebugUtils.dump("Command Line Provided: ", m_options);
	}

	public void dump(PrintWriter out, int depth, boolean verbose) {
		String indent = DebugUtils.getIndent(depth);

		out.print(indent);
		out.println("Command Line: ");

		DebugUtils.dump(m_options);
	}
}

--- NEW FILE: Options.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.common.util.cli;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author $Author: chalko $
 * @version $Revision: 1.1 $
 * 
 */
public class Options {
    private List m_options = null;
    private Map m_optKey = null;
    private Map m_longOptKey = null;

    public Options() {
        m_options = new ArrayList();
        m_optKey = new HashMap();
        m_longOptKey = new HashMap();
    }

    public void addOption(String opt, boolean hasArg, String desc) {
        addOption(new Option(opt, hasArg, desc));
    }

    public void addOption(
        String opt,
        String logOpt,
        boolean hasArg,
        String desc) {
        addOption(new Option(opt, logOpt, hasArg, desc));
    }

    public void addOption(Option option) {
        m_options.add(option);

        if (m_optKey.containsKey(option.getOpt()))
            throw new Error("Duplicate CommandLine Option [" + option + "]");

        m_optKey.put(option.getOpt(), option);

        if (null != option.getLongOpt())
            m_longOptKey.put(option.getLongOpt(), option);
    }

    public Option getOption(String opt) {
        Option option = (Option) m_optKey.get(opt);

        if (null == option)
            option = (Option) m_longOptKey.get(opt);

        return option;
    }

    public String getOptionsString() {
        StringBuffer list = new StringBuffer();

        for (Iterator i = m_options.iterator(); i.hasNext();) {
            Option option = (Option) i.next();

            list.append(option.getOpt());
            if (null != option.getLongOpt()) {
                list.append("(");
                list.append(option.getLongOpt());
                list.append(")");
            }

            if (i.hasNext())
                list.append(" ");
        }

        return list.toString();
    }

    public void display() {
		System.out.println("Command Line Options:");
        for (Iterator i = m_options.iterator(); i.hasNext();) {
            Option option = (Option) i.next();
            System.out.print("  ");
            System.out.println(option);
        }
    }
}

--- NEW FILE: ParseException.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.common.util.cli;

import org.krysalis.depot.common.DepotException;

/**
 *
 * @author $Author: chalko $
 * @version $Revision: 1.1 $
 * 
 */
public class ParseException extends DepotException {

    /**
     * Constructor for ParseException.
     */
    public ParseException() {
        super();
    }

    /**
     * Constructor for ParseException.
     * @param message
     */
    public ParseException(String message) {
        super(message);
    }

    /**
     * Constructor for ParseException.
     * @param message
     * @param cause
     */
    public ParseException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructor for ParseException.
     * @param cause
     */
    public ParseException(Throwable cause) {
        super(cause);
    }

}

--- NEW FILE: CommandLineParser.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.krysalis.depot.common.util.cli;

/**
 *
 * @author $Author: chalko $
 * @version $Revision: 1.1 $
 * 
 */
public class CommandLineParser {
    private boolean m_strict = true;
    
    public CommandLine parse(Options options, String args[])
        throws ParseException {
        CommandLine cl = new CommandLine();

        if (null != args)
            for (int i = 0; i < args.length; ++i) {
                
                boolean skip = false;
                String opt = args[i];

                if (opt.startsWith("/") || opt.startsWith("-"))
                    opt = opt.substring(1);
                else {
                    if (m_strict)
                        throw new ParseException(
                            "Unrecognizable option ["
                                + opt
                                + "]. Options look like -a or /a");
                    else
                        skip = true;
                }

                if (!skip) {
                    Option option = options.getOption(opt);

                    if (null == option)
                        if (m_strict)
                            throw new ParseException(
                                "Unknown option ["
                                    + opt
                                    + "]. Not in "
                                    + options.getOptionsString());
                        else
                            skip = true;

                    if (!skip) {
                        if (option.isHasArg()) {
                            i++;

                            if (i >= args.length)
                                throw new ParseException(
                                    "Missing argument for [" + option + "]");

                            String arg = args[i];

                            cl.addOption(option, arg);
                        }
                        else
                            cl.addOption(option);
                    }
                }
            }

        return cl;
    }
    
    /**
     * @return
     */
    public boolean isStrict() {
        return m_strict;
    }

    /**
     * @param b
     */
    public void setStrict(boolean b) {
        m_strict = b;
    }
}



-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now. 
http://productguide.itmanagersjournal.com/