+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2004 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// Phenome Commons Project
-//
-// OptionComposite.java
-// Since: 2005/01/03
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-
-/**
- *
- * A base class for {@link OptionWithNoArgument} and {@link OptionGroup}
- *
- * @author leo
- *
- */
-abstract class OptionBase<OptionID extends Comparable>
-{
- abstract protected OptionWithNoArgument<OptionID> findByLongOptionName(String longOption);
- abstract protected OptionWithNoArgument<OptionID> findByShortOptionName(String shortOption);
- abstract protected OptionWithNoArgument<OptionID> findOption(OptionID optionID);
- abstract protected void collectOptionID(List<OptionID> optionIDList);
- abstract protected void collectOptionDescriptions(OptionDescriptionContainer container);
-
- protected OptionBase(OptionGroup<OptionID> parentGroup)
- {
- setParent(parentGroup);
- }
-
- protected void setParent(OptionGroup<OptionID> parentGroup)
- {
- _parentGroup = parentGroup;
- }
- protected OptionGroup<OptionID> getParent()
- {
- return _parentGroup;
- }
-
- protected void activateParentGroup()
- {
- OptionGroup<OptionID> parent = getParent();
- if(parent != null)
- parent.activate();
- }
-
-
-
- private OptionGroup<OptionID> _parentGroup = null;
-}
-
-
-
-/**
- * A container class that holds help messages
- * @author leo
- *
- */
-class OptionDescriptionContainer
-{
-
- public void addDescription(String shortOptionColumn, String longOptionColumn, String descriptionColumn)
- {
- String column[] = new String[3];
- column[0] = shortOptionColumn;
- column[1] = longOptionColumn;
- column[2] = descriptionColumn;
- _columnList.add(column);
- }
- public void addDescription(String groupName)
- {
- String singleColumn[] = new String[1];
- singleColumn[0] = groupName;
- _columnList.add(singleColumn);
- }
-
- public String toString()
- {
- // calculate necessary width for each column
- int width[] = { 0, 0, 0 };
- for (Iterator ci = _columnList.iterator(); ci.hasNext();)
- {
- String[] line = (String[]) ci.next();
- if (line.length != 3)
- continue; // single line
- for (int i = 0; i < line.length; i++)
- width[i] = width[i] < line[i].length() ? line[i].length() : width[i];
- }
- for(int i=0; i<width.length; i++)
- width[i]++;
- // print each options
- StringWriter strWriter = new StringWriter();
- PrintWriter out = new PrintWriter(strWriter);
- for (Iterator ci = _columnList.iterator(); ci.hasNext();)
- {
- String[] line = (String[]) ci.next();
- if(line.length == 1)
- out.print(line[0]); // group name
- else
- {
- out.print(" "); /// left margin
- for (int i = 0; i < line.length; i++)
- {
- out.print(line[i]);
- int numSpace = width[i] - line[i].length();
- for (int j = 0; j < numSpace; j++)
- out.print(" ");
- }
- }
- out.println();
- }
- return strWriter.toString();
- }
-
- LinkedList<String[]> _columnList = new LinkedList<String[]>();
-}
-
-
-
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2004 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// Phenome Commons Project
-//
-// OptionGroup.java
-// Since: 2005/01/03
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.TreeSet;
-
-import org.xerial.core.XerialErrorCode;
-import org.xerial.util.opt.OptionParser;
-
-/**
- * OptionGroup creates a bundle of options
- *
- * By setting some OptionGroup as exclusive, you can prevent multiple exclusive
- * OptionGroups will be activated at the same time.
- *
- * <h3>usage</h3>
- *
- * <pre>
- * enum Opt { "cui", "gui" }
- * OptionGroup<Opt> cuiGroup = new OptionGroup<Opt>("cui", true);
- * cuiGroup.addOption(Opt.cui, "c", "cui", "CUI mode");
- * OptionGroup<Opt> guiGroup = new OptionGroup<Opt>("gui", true);
- * guiGroup.addOption(Opt.gui, "g", "gui", "GUI mode");
- *
- * OptionParser<Opt> parser = new OptionParser<Opt>();
- * parser.addOptionGroup(cuiGroup);
- * parser.addOptionGroup(guiGroup);
- *
- * parser.parse(new String[] {"--cui", "--gui" }); // throws OptionParserException
- *
- * </pre>
- *
- * @author leo
- * @see no longer supported. See {@link OptionParser} instead.
- *
- */
-public class OptionGroup<OptionID extends Comparable> extends OptionBase<OptionID>
-{
- private LinkedList<OptionBase<OptionID>> _contents = new LinkedList<OptionBase<OptionID>>();
- private String _groupName;
- private boolean _isActive = false;
- private boolean _isExclusive = false;
- private HashMap<OptionID, OptionHandler> _optionHandlerTable = new HashMap<OptionID, OptionHandler>();
-
- /**
- *
- */
- public OptionGroup(String groupName)
- {
- super(null);
- _groupName = groupName;
- }
-
- /**
- * Creates an option group
- *
- * @param groupName
- * the group name
- * @param isExclusive
- * true when you forbid the activation of other option groups,
- * which belong to the same level with this option group
- * */
- public OptionGroup(String groupName, boolean isExclusive)
- {
- super(null);
- _groupName = groupName;
- _isExclusive = isExclusive;
- }
-
- /**
- * Adds an option to this option group
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name. If you specified "h" as the argument,
- * "-h" can be used as a command line option
- * @param longOptionName
- * the long option name. If you specified "help" as the argument,
- * "--help" can be used as a command line option
- * @param description
- * the description of this option
- */
- public void addOption(OptionID optionID, String shortOptionName, String longOptionName, String description)
- {
- addOption(new OptionWithNoArgument<OptionID>(this, optionID, shortOptionName, longOptionName, description));
- }
-
- /**
- * Adds an option to this option group
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name. If you specified "h" as the argument,
- * "-h" can be used as a command line option
- * @param longOptionName
- * the long option name. If you specified "help" as the argument,
- * "--help" can be used as a command line option
- * @param description
- * the description of this option
- * @param presetValue
- * true: this option is on in default, false: off
- */
- public void addOption(OptionID optionID, String shortOptionName, String longOptionName, String description,
- boolean presetValue)
- {
- addOption(new OptionWithNoArgument<OptionID>(this, optionID, shortOptionName, longOptionName, description,
- presetValue));
- }
-
- /**
- * Adds an option to this option group
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name. If you specified "h" as the argument,
- * "-h" can be used as a command line option
- * @param longOptionName
- * the long option name. If you specified "help" as the argument,
- * "--help" can be used as a command line option
- * @param description
- * the description of this option
- * @param handler
- * {@link OptionHandler} invoked when this option is set
- */
- public void addOption(OptionID optionID, String shortOptionName, String longOptionName, String description,
- OptionHandler<OptionID> handler)
- {
- addOption(new OptionWithNoArgument<OptionID>(this, optionID, shortOptionName, longOptionName, description),
- handler);
- }
-
- /**
- * Adds an option to this option group
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name. If you specified "h" as the argument,
- * "-h" can be used as a command line option
- * @param longOptionName
- * the long option name. If you specified "help" as the argument,
- * "--help" can be used as a command line option
- * @param description
- * the description of this option
- * @param presetValue
- * true: this option is on in default, false: off
- * @param handler
- * {@link OptionHandler} invoked when this option is set
- */
- public void addOption(OptionID optionID, String shortOptionName, String longOptionName, String description,
- boolean presetValue, OptionHandler<OptionID> handler)
- {
- addOption(new OptionWithNoArgument<OptionID>(this, optionID, shortOptionName, longOptionName, description,
- presetValue), handler);
- }
-
- void addOption(OptionWithNoArgument<OptionID> option, OptionHandler<OptionID> optionHandler)
- {
- addOptionHandler(option.getOptionID(), optionHandler);
- _contents.add(option);
- }
-
- void addOption(OptionWithNoArgument<OptionID> option)
- {
- _contents.add(option);
- }
-
- /**
- * Adds an option to this option group
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name. If you specified "h" as the argument,
- * "-h" can be used as a command line option
- * @param longOptionName
- * the long option name. If you specified "help" as the argument,
- * "--help" can be used as a command line option
- * @param argumentName
- * argument name of this option. This argument is used only for
- * displaying the help message.
- * @param description
- * the description of this option
- * @param handler
- * {@link OptionHandler} invoked when this option is set
- */
- public void addOptionWithArgment(OptionID optionID, String shortOptionName, String longOptionName,
- String argumentName, String description)
- {
- _contents.add(new OptionWithArgument<OptionID>(this, optionID, shortOptionName, longOptionName, argumentName,
- description));
- }
-
- /**
- * Adds an option to this option group
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name. If you specified "l" as the argument,
- * "-l" can be used as a command line option
- * @param longOptionName
- * the long option name. If you specified "loglevel" as the
- * argument, "--loglevel" can be used as a command line option
- * @param argumentName
- * argument name of this option. This argument is used only for
- * displaying the help message.
- * @param description
- * the description of this option
- * @param handler
- * {@link OptionHandler} invoked when this option is set
- */
- public void addOptionWithArgment(OptionID optionID, String shortOptionName, String longOptionName,
- String argumentName, String description, OptionHandler<OptionID> handler)
- {
- addOptionHandler(optionID, handler);
- _contents.add(new OptionWithArgument<OptionID>(this, optionID, shortOptionName, longOptionName, argumentName,
- description));
- }
-
- /**
- * Adds an option to this option group
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name. If you specified "h" as the argument,
- * "-h" can be used as a command line option
- * @param longOptionName
- * the long option name. If you specified "help" as the argument,
- * "--help" can be used as a command line option
- * @param argumentName
- * argument name of this option. This argument is used only for
- * displaying the help message.
- * @param description
- * the description of this option
- * @param defaultValue
- * the default value of this option
- */
- public void addOptionWithArgment(OptionID optionID, String shortOptionName, String longOptionName,
- String argumentName, String description, String defaultValue)
- {
- _contents.add(new OptionWithArgument<OptionID>(this, optionID, shortOptionName, longOptionName, argumentName,
- description, defaultValue));
- }
-
- public void addOptionGroup(OptionGroup<OptionID> optionGroup)
- {
- optionGroup.setParent(this);
- _contents.add(optionGroup);
- }
-
- public void addOptionHandler(OptionID optionID, OptionHandler<OptionID> handler)
- {
- if (handler == null)
- throw new IllegalArgumentException("handler is null: " + optionID.toString());
-
- _optionHandlerTable.put(optionID, handler);
- }
-
- protected void collectOptionDescriptions(OptionDescriptionContainer container)
- {
- if (!_groupName.equals(""))
- container.addDescription("[" + _groupName + "]");
- for (OptionBase<OptionID> opt : getChildren())
- {
- opt.collectOptionDescriptions(container);
- }
- }
-
- List<OptionBase<OptionID>> getChildren()
- {
- return _contents;
- }
-
- // @see lab.cb.common.cui.OptionComposite#findByLongOptionName(java.lang.String)
- protected OptionWithNoArgument<OptionID> findByLongOptionName(String longOption)
- {
- for (OptionBase<OptionID> opt : getChildren())
- {
- OptionWithNoArgument<OptionID> searchResult = opt.findByLongOptionName(longOption);
- if (searchResult != null)
- return searchResult;
- }
- return null;
- }
-
- // @see lab.cb.common.cui.OptionComposite#findByShortOptionName(java.lang.String)
- protected OptionWithNoArgument<OptionID> findByShortOptionName(String shortOption)
- {
- for (OptionBase<OptionID> opt : getChildren())
- {
- OptionWithNoArgument<OptionID> searchResult = opt.findByShortOptionName(shortOption);
- if (searchResult != null)
- return searchResult;
- }
- return null;
- }
-
- // @see lab.cb.common.cui.OptionComposite#findOption(java.lang.Comparable)
- protected OptionWithNoArgument<OptionID> findOption(OptionID optionID)
- {
- for (OptionBase<OptionID> opt : getChildren())
- {
- OptionWithNoArgument<OptionID> searchResult = opt.findOption(optionID);
- if (searchResult != null)
- return searchResult;
- }
- return null;
- }
-
- // @see lab.cb.common.cui.OptionComposite#collectOptionID(java.util.List)
- protected void collectOptionID(List<OptionID> optionIDList)
- {
- for (OptionBase<OptionID> opt : getChildren())
- {
- opt.collectOptionID(optionIDList);
- }
- }
-
- /**
- * Finds the option handler of the specified optionID. This method
- * recursively searches nested option groups
- *
- * @param optionID
- * the option ID
- * @return the option handler
- */
- public OptionHandler<OptionID> getOptionHandler(OptionID optionID)
- {
- OptionHandler<OptionID> optionHandler = _optionHandlerTable.get(optionID);
- if (optionHandler != null)
- return optionHandler;
-
- for (OptionBase<OptionID> opt : getChildren())
- {
- if (opt instanceof OptionGroup)
- {
- OptionGroup<OptionID> optionGroup = (OptionGroup<OptionID>) opt;
- optionHandler = optionGroup.getOptionHandler(optionID);
- if (optionHandler != null)
- return optionHandler;
- }
- }
- return null;
- }
-
- public boolean isActive()
- {
- return _isActive;
- }
-
- public void activate()
- {
- _isActive = true;
- }
-
- public String getGroupName()
- {
- return _groupName;
- }
-
- boolean isExclusive()
- {
- return _isExclusive;
- }
-
- /**
- * Tests there are exclusive option groups that are simultaneously activated
- * in the same level (depth)
- *
- * @throws OptionParserException
- * when exclusive option groups are activated at the same time
- */
- void validateExclusiveness() throws OptionParserException
- {
- TreeSet<String> activeAndIncompatibleGroups = new TreeSet<String>();
- for (OptionBase<OptionID> opt : _contents)
- {
- if (opt instanceof OptionGroup)
- {
- OptionGroup<OptionID> optGroup = (OptionGroup<OptionID>) opt;
- if (optGroup.isExclusive() && optGroup.isActive())
- {
- activeAndIncompatibleGroups.add(optGroup.getGroupName());
- }
- optGroup.validateExclusiveness();
- }
- }
- if (activeAndIncompatibleGroups.size() > 1)
- throw new OptionParserException(XerialErrorCode.INVALID_STATE, String.format(
- "options in groups %s cannot be set simultaneously", activeAndIncompatibleGroups));
- }
-
- public void handle(String[] args, int argIndex)
- {
- // do nothing in default
- }
-
-}
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2007 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// XerialJ
-//
-// OptionHandler.java
-// Since: Aug 27, 2007 9:05:52 AM
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-/**
- * A handler called when an option is set.
- *
- * @author leo
- *
- * @see no longer supported. Use {@link org.xerial.util.opt.OptionParser}
- * instead
- */
-public interface OptionHandler<OptionID extends Comparable>
-{
- /**
- * Called when the option is specified
- *
- * @param parser
- * the option parser
- * @throws OptionParserException
- * when handling of this option is failed
- */
- public void handle(OptionParser<OptionID> parser) throws OptionParserException;
-}
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2004 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// XerialJ Project
-//
-// OptionParser.java
-// Since: 2005/01/03
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.TreeSet;
-import java.util.Vector;
-
-import org.xerial.core.XerialErrorCode;
-
-/**
- * <p>
- * {@link OptionParser} parses command line arguments
- * </p>
- *
- * <h3>Usage:</h3>
- *
- * <pre>
- *
- * public static void main(String[] args)
- * {
- * enum Opt { HELP, OUTDIR }
- * OptionParser<Opt> p = new OptionParser<Opt>();
- * p.addOption(Opt.HELP, "h", "help", "display help message");
- * // adds an option with an argument whose default value is "."
- * p.addOptionWithArgument(Opt.OUTDIR, "o", "outdir", "DIR", "specify output direcotry", ".");
- *
- * p.parse(args);
- *
- * if(p.isSet(Opt.HELP))
- * {
- * // print help message
- * System.out.println(p.helpMessage());
- * return;
- * }
- *
- * if(p.isSet(Opt.OUTDIR))
- * {
- * String outDir = p.getValue(Opt.OUTDIR);
- * }
- * }
- *
- * </pre>
- *
- * @param OptionID
- * A {@link Integer} or {@link Enum} class that can be used IDs for
- * options. OptionID must implement {@link Comparable} interface.
- *
- * @author leo
- *
- * @see no longer maintained. Use {@link org.xerial.util.opt.OptionParser},
- * which is easier to use, instead.
- *
- *
- */
-public class OptionParser<OptionID extends Comparable>
-{
-
- private OptionGroup<OptionID> _rootOptionGroup = new OptionGroup<OptionID>("");
- private Vector<String> _argumentList = new Vector<String>();
- private TreeSet<String> _activeGroupSet = new TreeSet<String>();
- private TreeSet<OptionID> _optionIDSet = new TreeSet<OptionID>();
-
- private boolean ignoreUnknownOption = false;
-
- /**
- * A constructor
- */
- public OptionParser()
- {}
-
- /**
- * Adds an option to detect
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name, e.g. "h", which corresponds to "-h" in
- * the command line arguments.
- * @param longOptionName
- * the long option name, e.g. "help", which corresponds to
- * "--help" in the command line arguments.
- * @param description
- * the description of the option, which is used to generate the
- * help message of this option
- */
- public void addOption(OptionID optionID, String shortOptionName, String longOptionName, String description)
- {
- addNewOptionID(optionID);
- _rootOptionGroup.addOption(optionID, shortOptionName, longOptionName, description);
- }
-
- /**
- * Adds an option to detect
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name, e.g. "h", which corresponds to "-h" in
- * the command line arguments.
- * @param longOptionName
- * the long option name, e.g. "help", which corresponds to
- * "--help" in the command line arguments.
- * @param description
- * the description of the option, which is used to generate the
- * help message of this option
- * @param handler
- * the option argument handler invoked when the option is set
- */
- public void addOption(OptionID optionID, String shortOptionName, String longOptionName, String description,
- OptionHandler handler)
- {
- addNewOptionID(optionID);
-
- _rootOptionGroup.addOptionHandler(optionID, handler);
- _rootOptionGroup.addOption(optionID, shortOptionName, longOptionName, description);
- }
-
- /**
- * @param option
- * @deprecated use
- * {@link #addOption(Comparable, String, String, String, OptionHandler)}
- * instead.
- */
- public void addOption(OptionWithNoArgument<OptionID> option)
- {
- option.setParent(_rootOptionGroup);
- addNewOptionID(option.getOptionID());
- _rootOptionGroup.addOption(option);
- }
-
- /**
- * Adds an option with the default argument (set or not set)
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name, e.g. "h", which corresponds to "-h" in
- * the command line arguments.
- * @param longOptionName
- * the long option name, e.g. "help", which corresponds to
- * "--help" in the command line arguments.
- * @param description
- * the description of the option, which is used to generate the
- * help message of this option
- * @param presetValue
- * when true, the option is assumed to be set in default,
- * otherwise false
- */
- public void addOption(OptionID optionID, String shortOptionName, String longOptionName, String description,
- boolean presetValue)
- {
- addNewOptionID(optionID);
- _rootOptionGroup.addOption(optionID, shortOptionName, longOptionName, description, presetValue);
- }
-
- /**
- * Adds an option that takes an argument value
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name, e.g. "h", which corresponds to "-h" in
- * the command line arguments.
- * @param longOptionName
- * the long option name, e.g. "help", which corresponds to
- * "--help" in the command line arguments.
- * @param description
- * the description of the option, which is used to generate the
- * help message of this option
- */
- public void addOptionWithArgument(OptionID optionID, String shortOptionName, String longOptionName,
- String argumentName, String description)
- {
- addNewOptionID(optionID);
- _rootOptionGroup.addOptionWithArgment(optionID, shortOptionName, longOptionName, argumentName, description);
- }
-
- /**
- * Adds an option that takes an argument value
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name, e.g. "h", which corresponds to "-h" in
- * the command line arguments.
- * @param longOptionName
- * the long option name, e.g. "help", which corresponds to
- * "--help" in the command line arguments.
- * @param description
- * the description of the option, which is used to generate the
- * help message of this option
- * @param handler
- * the option argument handler invoked when the option is set
- */
- public void addOptionWithArgument(OptionID optionID, String shortOptionName, String longOptionName,
- String argumentName, String description, OptionHandler<OptionID> handler)
- {
- addNewOptionID(optionID);
- _rootOptionGroup.addOptionHandler(optionID, handler);
- _rootOptionGroup.addOptionWithArgment(optionID, shortOptionName, longOptionName, argumentName, description);
- }
-
- /**
- * Adds an option that takes an argument value
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name, e.g. "h", which corresponds to "-h" in
- * the command line arguments.
- * @param longOptionName
- * the long option name, e.g. "help", which corresponds to
- * "--help" in the command line arguments.
- * @param description
- * the description of the option, which is used to generate the
- * help message of this option
- * @param defaultValue
- * the default value of the option
- */
- public void addOptionWithArgument(OptionID optionID, String shortOptionName, String longOptionName,
- String argumentName, String description, String defaultValue)
- {
- addNewOptionID(optionID);
- _rootOptionGroup.addOptionWithArgment(optionID, shortOptionName, longOptionName, argumentName, description,
- defaultValue);
- }
-
- /**
- * Adds an option that takes an argument value
- *
- * @param optionID
- * the option ID
- * @param shortOptionName
- * the short option name, e.g. "h", which corresponds to "-h" in
- * the command line arguments.
- * @param longOptionName
- * the long option name, e.g. "help", which corresponds to
- * "--help" in the command line arguments.
- * @param description
- * the description of the option, which is used to generate the
- * help message of this option
- * @param defaultValue
- * the default value of the option
- * @param handler
- * the option argument handler invoked when the option is set
- */
- public void addOptionWithArgument(OptionID optionID, String shortOptionName, String longOptionName,
- String argumentName, String description, String defaultValue, OptionHandler<OptionID> handler)
- {
- addNewOptionID(optionID);
- _rootOptionGroup.addOptionHandler(optionID, handler);
- _rootOptionGroup.addOptionWithArgment(optionID, shortOptionName, longOptionName, argumentName, description,
- defaultValue);
- }
-
- /**
- * Adds an option group
- *
- * @param optionGroup
- * the option group
- */
- public void addOptionGroup(OptionGroup<OptionID> optionGroup)
- {
- LinkedList<OptionID> optionIDList = new LinkedList<OptionID>();
- optionGroup.collectOptionID(optionIDList);
- for (OptionID optID : optionIDList)
- addNewOptionID(optID);
- _rootOptionGroup.addOptionGroup(optionGroup);
- }
-
- /**
- * Parses the command line arguments. After calling this method, you can
- * retrieve the status of options via {@link #isSet(Comparable)} or
- * {@link #getValue(Comparable)} methods, etc.
- *
- * @param args
- * the command line arguments, which is given by the
- * main(String[] args) method
- * @throws OptionParserException
- * when the given command line has invalid syntax or when
- * incompatible options are set at the same time.
- */
- public void parse(String[] args) throws OptionParserException
- {
- int index = 0;
-
- TreeSet<OptionID> activatedOptionSet = new TreeSet<OptionID>();
-
- while (index < args.length)
- {
- String arg = args[index];
- if (arg.startsWith("--"))
- {
- // long name option
- int splitPos = arg.indexOf('=');
- String longOptionName, value;
- if (splitPos == -1)
- {
- // no value is found
- longOptionName = arg.substring(2);
- OptionWithNoArgument<OptionID> opt = _rootOptionGroup.findByLongOptionName(longOptionName);
- if (opt == null)
- if (ignoreUnknownOption)
- {
- index++;
- continue;
- }
- else
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "unknown option --"
- + longOptionName);
- if (opt.takeArgument())
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR,
- "parameter value is required for --" + longOptionName);
- opt.set(args, index);
- activatedOptionSet.add(opt.getOptionID());
- }
- else
- {
- // a matching argument value is found
- longOptionName = arg.substring(2, splitPos);
- value = arg.substring(splitPos + 1);
- OptionWithNoArgument<OptionID> opt = _rootOptionGroup.findByLongOptionName(longOptionName);
- if (opt == null)
- if (ignoreUnknownOption)
- {
- index++;
- continue;
- }
- else
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "unknown option --"
- + longOptionName);
- if (opt instanceof OptionWithArgument)
- {
- OptionWithArgument<OptionID> optWithArg = (OptionWithArgument<OptionID>) opt;
- optWithArg.setArgumentValue(value);
- optWithArg.set(args, index);
- activatedOptionSet.add(optWithArg.getOptionID());
- }
- else
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "syntax error --"
- + longOptionName);
- }
- }
- else if (arg.startsWith("-"))
- {
- // short name option
- String shortOptionList = arg.substring(1);
- for (int i = 0; i < shortOptionList.length(); i++)
- {
- String shortOption = shortOptionList.substring(i, i + 1);
- OptionWithNoArgument<OptionID> opt = _rootOptionGroup.findByShortOptionName(shortOption);
- if (opt == null)
- if (ignoreUnknownOption)
- {
- index++;
- continue;
- }
- else
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "unknown option -"
- + shortOption);
- if (opt.takeArgument())
- {
- if (shortOptionList.length() != 1)
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR,
- "options with argument must be isolated: -" + shortOption);
- if (opt instanceof OptionWithArgument)
- {
- OptionWithArgument optWithArg = (OptionWithArgument) opt;
- if (++index < args.length)
- optWithArg.setArgumentValue(args[index]);
- else
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR,
- "parameter value is required for -" + shortOption);
- }
- }
- opt.set(args, index);
- activatedOptionSet.add(opt.getOptionID());
- }
- }
- else
- {
- // plain argument
- _argumentList.add(arg);
- }
- index++;
- }
-
- // validate whether incompatible options are set at the same time
- _rootOptionGroup.validateExclusiveness();
-
- // invokes option handlers
- for (OptionID optID : activatedOptionSet)
- {
- OptionHandler handler = _rootOptionGroup.getOptionHandler(optID);
- if (handler != null)
- {
- handler.handle(this);
- }
- }
- }
-
- /**
- * Get the list of command-line arguments except option related ones
- *
- * @return
- */
- public List<String> getArgument()
- {
- return _argumentList;
- }
-
- /**
- * Get a command line argument
- *
- * @param index
- * argumetn index (0 origin)
- * @return the command line argument at the index
- */
- public String getArgument(int index)
- {
- return _argumentList.get(index);
- }
-
- /**
- * Get the argument length (except option related ones)
- *
- * @return the number of arguments
- */
- public int getArgumentLength()
- {
- return _argumentList.size();
- }
-
- /**
- * Test whether the option is set in the command line argument
- *
- * @param optionID
- * the target option
- * @return true if the option is set in the command line, otherwise false
- * @throws OptionParserException
- * if unknown option ID is given in the argument
- */
- public boolean isSet(OptionID optionID) throws OptionParserException
- {
- OptionWithNoArgument<OptionID> option = findOption(optionID);
- if (option == null)
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "unknown option " + optionID);
- return option.isSet();
- }
-
- /**
- * Get the integer value of the option (ex. if the option is --width=100,
- * return 100 (int))
- *
- * @param optionID
- * @return the integer value of the option value
- * @throws OptionParserException
- * if no corresponding option ID is found in the
- * {@link OptionParser}, or the specified option cannot take any
- * argument. Or the argument value cannot be translated into
- * integer.
- */
- public int getIntValue(OptionID optionID) throws OptionParserException
- {
- try
- {
- return Integer.parseInt(getValue(optionID));
- }
- catch (NumberFormatException e)
- {
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, e);
- }
- }
-
- /**
- * Get the option value in double format
- *
- * @param optionID
- * the option ID
- * @return the double value of the option
- * @throws OptionParserException
- * if no corresponding option ID is found in the
- * {@link OptionParser}, or the specified option cannot take any
- * argument. Or the option value cannot be translated into
- * double.
- */
- public double getDoubleValue(OptionID optionID) throws OptionParserException
- {
- try
- {
- return Double.parseDouble(getValue(optionID));
- }
- catch (NumberFormatException e)
- {
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, e);
- }
-
- }
-
- /**
- * Get the option value in float format
- *
- * @param optionID
- * the option ID
- * @return the float value of the option
- * @throws OptionParserException
- * if no corresponding option ID is found in the
- * {@link OptionParser}, or the specified option cannot take any
- * argument. Or the option value cannot be translated into
- * float.
- */
- public float getFloatValue(OptionID optionID) throws OptionParserException
- {
- try
- {
- return Float.parseFloat(getValue(optionID));
- }
- catch (NumberFormatException e)
- {
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, e);
- }
- }
-
- /**
- * Gets the option argument value as a {@link String}
- *
- * @param optionID
- * the target option that takes argument value
- * @return the string value of the specified option argument
- * @throws OptionParserException
- * if the specified option ID is not found or if the option
- * cannot take arguments
- */
- public String getValue(OptionID optionID) throws OptionParserException
- {
- OptionWithNoArgument<OptionID> targetOption = _rootOptionGroup.findOption(optionID);
- if (targetOption == null)
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "unknown option: " + optionID);
- if (!(targetOption instanceof OptionWithArgument))
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "option " + optionID
- + " cannot take any argument");
-
- OptionWithArgument<OptionID> optWithArg = (OptionWithArgument<OptionID>) (targetOption);
- return optWithArg.getArgumentValue();
- }
-
- /**
- * Gets the option argument value as a {@link String}
- *
- * @param optionID
- * the target option that takes argument value
- * @param defaultValue
- * the default value to be returned when this option is not
- * present in the command line arguments
- * @return the string value of the specified option argument
- * @throws OptionParserException
- * if the specified option ID is not found or if the option
- * cannot take arguments
- */
- public String getValue(OptionID optionID, String defaultValue) throws OptionParserException
- {
- OptionWithNoArgument<OptionID> targetOption = _rootOptionGroup.findOption(optionID);
- if (targetOption == null)
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "unknown option: " + optionID);
- if (!(targetOption instanceof OptionWithArgument))
- throw new OptionParserException(XerialErrorCode.SYNTAX_ERROR, "option " + optionID
- + " cannot take any argument");
-
- OptionWithArgument<OptionID> optWithArg = (OptionWithArgument<OptionID>) (targetOption);
- String value = optWithArg.getArgumentValue();
- return (value == null) ? defaultValue : value;
- }
-
- /**
- * Generates the help message for this option parser
- *
- * @return the help message that can be used as a list of command line
- * options
- */
- public String helpMessage()
- {
- OptionDescriptionContainer container = new OptionDescriptionContainer();
- _rootOptionGroup.collectOptionDescriptions(container);
-
- return container.toString();
- }
-
- private OptionWithNoArgument<OptionID> findOption(OptionID optionID)
- {
- return _rootOptionGroup.findOption(optionID);
- }
-
- private void addNewOptionID(OptionID newOptionID)
- {
- if (_optionIDSet.contains(newOptionID))
- throw new IllegalArgumentException("duplicate addition of OptionID: " + newOptionID);
-
- _optionIDSet.add(newOptionID);
- }
-
- public void setIgnoreUnknownOption(boolean ignore)
- {
- ignoreUnknownOption = ignore;
- }
-
-}
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2004 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// Phenome Commons Project
-//
-// OptionParserException.java
-// Since: 2005/01/04
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-import org.xerial.core.ErrorCode;
-import org.xerial.core.XerialException;
-
-/**
- * An exception class thrown when illegal states are found when parsing command
- * line arguments
- *
- * @author leo
- *
- */
-public class OptionParserException extends XerialException
-{
- /**
- * Comment for <code>serialVersionUID</code>
- */
- private static final long serialVersionUID = 3906085637814695480L;
-
- public OptionParserException(ErrorCode errorCode, String message, Throwable cause)
- {
- super(errorCode, message, cause);
- }
-
- public OptionParserException(ErrorCode errorCode, String message)
- {
- super(errorCode, message);
- }
-
- public OptionParserException(ErrorCode errorCode, Throwable cause)
- {
- super(errorCode, cause);
- }
-
- public OptionParserException(ErrorCode errorCode)
- {
- super(errorCode);
- }
-
-}
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2004 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// Phenome Commons Project
-//
-// OptionWithArgument.java
-// Since: 2005/01/03
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-
-/**
- *
- * A command line option that takes arguments
- *
- * @author leo
- *
- */
-class OptionWithArgument<OptionID extends Comparable> extends OptionWithNoArgument<OptionID>
-{
-
- /**
- *
- */
- public OptionWithArgument(OptionGroup<OptionID> parentGroup, OptionID optionID, String shortOptionName, String longOptionName, String argumentName, String description)
- {
- super(parentGroup, optionID, shortOptionName, longOptionName, description);
- _argumentName = argumentName;
- }
-
- public OptionWithArgument(OptionGroup<OptionID> parentGroup, OptionID optionID, String shortOptionName, String longOptionName, String argumentName, String description, Object defaultValue)
- {
- super(parentGroup, optionID, shortOptionName, longOptionName, description);
- _argumentName = argumentName;
- _argumentValue = defaultValue.toString();
- }
-
- public String getArgumentValue()
- {
- return _argumentValue;
- }
-
- public void setArgumentValue(String value)
- {
- _argumentValue = value;
- }
-
- // @see lab.cb.common.cui.Option#takeArgument()
- public boolean takeArgument()
- {
- return true;
- }
-
- public String getShortOptionName()
- {
- return _shortName.equals("") ? "" : "-" + _shortName + (_longName.equals("") ? " " + _argumentName : ", ");
- }
-
- public String getLongOptionName()
- {
- return _longName.equals("") ? "" : "--" + _longName + "=" + _argumentName;
- }
-
-
- private String _argumentValue = null;
- private String _argumentName;
-}
-
-
-
-
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2004 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// XerialJ Project
-//
-// Option.java
-// Since: 2005/01/03
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-import java.util.List;
-
-/**
- * {@link OptionWithNoArgument} represents a command line option
- *
- * @author leo
- *
- */
-public class OptionWithNoArgument<OptionID extends Comparable> extends OptionBase<OptionID>
-{
- private OptionID _optionID;
- private boolean _flag = false;
- protected String _shortName;
- protected String _longName;
- private String _description;
-
- /**
- *
- */
- OptionWithNoArgument(OptionID optionID, String shortOptionName, String longOptionName, String description)
- {
- super(null);
- setValue(optionID, shortOptionName, longOptionName, description, false);
- }
-
- OptionWithNoArgument(OptionGroup<OptionID> parentGroup, OptionID optionID, String shortOptionName,
- String longOptionName, String description)
- {
- super(parentGroup);
- setValue(optionID, shortOptionName, longOptionName, description, false);
- }
-
- OptionWithNoArgument(OptionGroup<OptionID> parentGroup, OptionID optionID, String shortOptionName,
- String longOptionName, String description, boolean presetValue)
- {
- super(parentGroup);
- setValue(optionID, shortOptionName, longOptionName, description, presetValue);
- }
-
- private void setValue(OptionID optionID, String shortOptionName, String longOptionName, String description,
- boolean presetValue)
- {
- _optionID = optionID;
- _shortName = shortOptionName;
- _longName = longOptionName;
- _description = description;
- _flag = presetValue;
- }
-
- public boolean isSet()
- {
- return _flag;
- }
-
- public void set(String[] args, int argIndex)
- {
- _flag = true;
- this.activateParentGroup();
- }
-
- public OptionID getOptionID()
- {
- return _optionID;
- }
-
- public boolean takeArgument()
- {
- return false;
- }
-
- // @see lab.cb.common.cui.OptionComposite#findByLongOptionName(java.lang.String)
- protected OptionWithNoArgument<OptionID> findByLongOptionName(String longOption)
- {
- if (_longName.equals(longOption))
- return this;
- else
- return null;
- }
-
- // @see lab.cb.common.cui.OptionComposite#findByShortOptionName(java.lang.String)
- protected OptionWithNoArgument<OptionID> findByShortOptionName(String shortOption)
- {
- if (_shortName.equals(shortOption))
- return this;
- else
- return null;
- }
-
- // @see lab.cb.common.cui.OptionComposite#findOption(java.lang.Comparable)
- protected OptionWithNoArgument<OptionID> findOption(OptionID optionID)
- {
- if (optionID.compareTo(_optionID) == 0)
- return this;
- else
- return null;
- }
-
- // @see lab.cb.common.cui.OptionComposite#collectOptionID(java.util.List)
- protected void collectOptionID(List<OptionID> optionIDList)
- {
- optionIDList.add(_optionID);
- }
-
- // @see lab.cb.common.cui.OptionComposite#collectOptionDescriptions(lab.cb.common.cui.OptionDescriptionContainer)
- protected void collectOptionDescriptions(OptionDescriptionContainer container)
- {
- container.addDescription(getShortOptionName(), getLongOptionName(), getDescription());
- }
-
- public String getLongOptionName()
- {
- return _longName.equals("") ? "" : "--" + _longName;
- }
-
- public String getShortOptionName()
- {
- return _shortName.equals("") ? "" : "-" + _shortName + (_longName.equals("") ? " " : ", ");
- }
-
- public String getDescription()
- {
- return _description;
- }
-
-}
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2008 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-/**
- * The command line argument parser. (deprecated use org.xerial.util.opt.OptionParser)
- *
- */
-package org.xerial.util.cui;
\ No newline at end of file
//--------------------------------------
package org.xerial.util.xml.analyzer;
-import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
-import static org.xmlpull.v1.XmlPullParser.END_TAG;
-import static org.xmlpull.v1.XmlPullParser.START_DOCUMENT;
-import static org.xmlpull.v1.XmlPullParser.START_TAG;
-import static org.xmlpull.v1.XmlPullParser.TEXT;
+import static org.xmlpull.v1.XmlPullParser.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.TreeSet;
import org.xerial.core.XerialException;
-import org.xerial.util.cui.OptionParser;
-import org.xerial.util.cui.OptionParserException;
+import org.xerial.util.opt.Argument;
+import org.xerial.util.opt.Option;
+import org.xerial.util.opt.OptionParser;
+import org.xerial.util.opt.OptionParserException;
import org.xerial.util.xml.SinglePathBuilder;
import org.xerial.util.xml.XMLErrorCode;
import org.xerial.util.xml.XMLException;
* @author leo
*
*/
-public class XMLNodeRelationAnalyzer
-{
+public class XMLNodeRelationAnalyzer {
private enum Opt {
help
}
- private OptionParser<Opt> _opt = new OptionParser<Opt>();
+ @Option(symbol = "h", longName = "help", description = "display help message")
+ private boolean displayHelp = false;
+
+ @Argument(index = 0, name = "XMLFile")
+ private String xmlFile = null;
+
+ private OptionParser _opt = new OptionParser(this);
/**
* @throws OptionParserException
*
*/
- public XMLNodeRelationAnalyzer() throws OptionParserException
- {
- _opt.addOption(Opt.help, "h", "help", "display help message");
+ public XMLNodeRelationAnalyzer() throws OptionParserException {
+
}
- public static void main(String[] args)
- {
- try
- {
+ public static void main(String[] args) {
+ try {
XMLNodeRelationAnalyzer instance = new XMLNodeRelationAnalyzer();
instance.perform(args);
}
- catch (XerialException e)
- {
+ catch (XerialException e) {
System.err.println(e.getMessage());
}
- catch (IOException e)
- {
+ catch (IOException e) {
System.err.println(e.getMessage());
}
}
- public void perform(String[] args) throws OptionParserException, IOException, XerialException
- {
+ public void perform(String[] args) throws OptionParserException, IOException, XerialException {
_opt.parse(args);
- if (_opt.isSet(Opt.help) || _opt.getArgumentLength() < 1)
- {
+ if (displayHelp || xmlFile == null) {
printHelpMessage();
return;
}
- String xmlFile = _opt.getArgument(0);
Reader xmlFileReader = new FileReader(xmlFile);
XmlPullParser parser = PullParserUtil.newParser(xmlFileReader);
ParseProcess parseProcess = new ParseProcess(parser);
parseProcess.parse();
- for (String tag : parseProcess.tag2relatedTagNames.keySet())
- {
+ for (String tag : parseProcess.tag2relatedTagNames.keySet()) {
System.out.print(tag + ":\t");
- for (String related : parseProcess.tag2relatedTagNames.get(tag))
- {
+ for (String related : parseProcess.tag2relatedTagNames.get(tag)) {
System.out.print(related + " ");
}
System.out.println();
xmlFileReader.close();
}
- class NodeRelation
- {
+ class NodeRelation {
}
- class ParseProcess
- {
+ class ParseProcess {
XmlPullParser parser;
SinglePathBuilder currentPath = new SinglePathBuilder();
TreeMap<String, TreeSet<String>> tag2relatedTagNames = new TreeMap<String, TreeSet<String>>();
int pathCount = 0;
- ParseProcess(XmlPullParser parser)
- {
+ ParseProcess(XmlPullParser parser) {
this.parser = parser;
}
- void parse() throws IOException, XMLException
- {
+ void parse() throws IOException, XMLException {
int state;
- try
- {
- while ((state = parser.next()) != END_DOCUMENT)
- {
- switch (state)
- {
+ try {
+ while ((state = parser.next()) != END_DOCUMENT) {
+ switch (state) {
case START_TAG:
String currentTag = parser.getName();
currentPath.addChild(currentTag);
TreeSet<String> relatedTagSet = getRelatedTagSet(currentTag);
- for (String t : currentPath)
- {
- if (!t.equals(currentTag))
- {
+ for (String t : currentPath) {
+ if (!t.equals(currentTag)) {
relatedTagSet.add(t);
TreeSet<String> relatedTagSet2 = getRelatedTagSet(t);
relatedTagSet2.add(currentTag);
}
}
// TODO attribute processing
- for (int i = 0; i < parser.getAttributeCount(); i++)
- {
+ for (int i = 0; i < parser.getAttributeCount(); i++) {
}
break;
}
}
}
- catch (XmlPullParserException e)
- {
+ catch (XmlPullParserException e) {
throw new XMLException(XMLErrorCode.PARSE_ERROR, e);
}
}
- private TreeSet<String> getRelatedTagSet(String tag)
- {
+ private TreeSet<String> getRelatedTagSet(String tag) {
TreeSet<String> s = tag2relatedTagNames.get(tag);
- if (s == null)
- {
+ if (s == null) {
s = new TreeSet<String>();
tag2relatedTagNames.put(tag, s);
}
}
- private void printHelpMessage()
- {
+ private void printHelpMessage() {
System.out.println("usage: > java XMLNodeRelationAnalyzer.jar [option] xml_file");
}
\r
import org.xerial.core.XerialException;\r
import org.xerial.util.StringUtil;\r
-import org.xerial.util.cui.OptionParser;\r
-import org.xerial.util.cui.OptionParserException;\r
import org.xerial.util.graph.AdjacencyList;\r
import org.xerial.util.graph.Edge;\r
import org.xerial.util.graph.Graph;\r
+import org.xerial.util.opt.Argument;\r
+import org.xerial.util.opt.Option;\r
+import org.xerial.util.opt.OptionParser;\r
+import org.xerial.util.opt.OptionParserException;\r
import org.xerial.util.xml.SinglePath;\r
import org.xerial.util.xml.XMLException;\r
import org.xerial.util.xml.pullparser.AbstractSAXEventHandler;\r
* @author leo\r
* \r
*/\r
-public class DataGuide extends AbstractSAXEventHandler\r
-{\r
+public class DataGuide extends AbstractSAXEventHandler {\r
/**\r
* Adjacency list of String:tagID (node) and String:label (edge)\r
*/\r
/**\r
* \r
*/\r
- public DataGuide()\r
- {\r
+ public DataGuide() {\r
_rootNodeID = getTagID_internal(ROOT_TAG);\r
init();\r
}\r
\r
- private static XmlPullParser getParser(Reader xmlReader) throws XMLException\r
- {\r
+ private static XmlPullParser getParser(Reader xmlReader) throws XMLException {\r
XmlPullParser parser = PullParserUtil.newParser(xmlReader);\r
return parser;\r
}\r
* @param path\r
* @return the found path ID, if not found returns -1\r
*/\r
- public int getPathID(SinglePath path)\r
- {\r
+ public int getPathID(SinglePath path) {\r
return getTagID(path.getLeaf());\r
}\r
\r
* \r
* @return node ID, or -1 (if not found)\r
*/\r
- public int getTagID(String tagName)\r
- {\r
+ public int getTagID(String tagName) {\r
return _graph.getNodeID(tagName);\r
}\r
\r
- public int newTag(String tagName) throws XMLException\r
- {\r
+ public int newTag(String tagName) throws XMLException {\r
int tagID = this.getTagID_internal(tagName);\r
this.moveCursor(tagID);\r
return _currentNodeID;\r
}\r
\r
- public void newAttribute(String tagName, String attributeName) throws XMLException\r
- {\r
+ public void newAttribute(String tagName, String attributeName) throws XMLException {\r
int attributeID = this.getTagID_internal(String.format("%s@%s", tagName, attributeName));\r
this.moveCursor(attributeID);\r
this.traceBack();\r
}\r
\r
- public void closeTag()\r
- {\r
+ public void closeTag() {\r
this.traceBack();\r
}\r
\r
- public void init()\r
- {\r
+ public void init() {\r
// some initialization\r
_currentNodeID = _rootNodeID;\r
\r
// SAX handler methods\r
// @see org.xerial.util.xml.pullparser.SAXEventHandler#startDocument(org.xmlpull.v1.XmlPullParser)\r
@Override\r
- public void startDocument(XmlPullParser parser) throws XMLException\r
- {\r
+ public void startDocument(XmlPullParser parser) throws XMLException {\r
init();\r
}\r
\r
@Override\r
- public void startTag(XmlPullParser parser) throws XMLException\r
- {\r
+ public void startTag(XmlPullParser parser) throws XMLException {\r
newTag(parser.getName());\r
- for (int i = 0; i < parser.getAttributeCount(); i++)\r
- {\r
+ for (int i = 0; i < parser.getAttributeCount(); i++) {\r
newAttribute(parser.getName(), parser.getAttributeName(i));\r
}\r
}\r
\r
@Override\r
- public void endTag(XmlPullParser parser) throws XMLException\r
- {\r
+ public void endTag(XmlPullParser parser) throws XMLException {\r
closeTag();\r
}\r
\r
* @throws IOException\r
* @throws XerialException\r
*/\r
- public void generateFrom(String xmlFile) throws FileNotFoundException, Exception, IOException, XerialException\r
- {\r
+ public void generateFrom(String xmlFile) throws FileNotFoundException, Exception, IOException,\r
+ XerialException {\r
Reader reader = new BufferedReader(new FileReader(xmlFile));\r
generateFrom(reader);\r
}\r
* @throws FileNotFoundException\r
* @throws XMLParserException\r
*/\r
- public void generateFrom(Reader xmlReader) throws Exception, IOException, XerialException\r
- {\r
+ public void generateFrom(Reader xmlReader) throws Exception, IOException, XerialException {\r
\r
SAXParser saxParser = new SAXParser(this);\r
saxParser.parse(xmlReader);\r
}\r
\r
- void moveCursor(int tagID)\r
- {\r
+ void moveCursor(int tagID) {\r
_graph.addEdge(new Edge(_currentNodeID, tagID), "edge");\r
\r
_cursorHistory.push(_currentNodeID);\r
_currentNodeID = tagID;\r
}\r
\r
- void traceBack()\r
- {\r
+ void traceBack() {\r
assert !_cursorHistory.empty();\r
_currentNodeID = _cursorHistory.pop();\r
}\r
\r
- int getTagID_internal(String tagName)\r
- {\r
+ int getTagID_internal(String tagName) {\r
int tagID = _graph.getNodeID(tagName);\r
- if (tagID == -1)\r
- {\r
+ if (tagID == -1) {\r
tagID = _graph.addNode(tagName);\r
}\r
return tagID;\r
}\r
\r
- public void outputGraphviz(OutputStream out)\r
- {\r
+ public void outputGraphviz(OutputStream out) {\r
PrintWriter gout = new PrintWriter(out);\r
gout.println("digraph G {");\r
// output node labels\r
- for (int tagID : _graph.getNodeIDSet())\r
- {\r
- gout.println(tagID + " [label=" + StringUtil.quote(_graph.getNodeLabel(tagID), "\"") + "];");\r
+ for (int tagID : _graph.getNodeIDSet()) {\r
+ gout.println(tagID + " [label=" + StringUtil.quote(_graph.getNodeLabel(tagID), "\"")\r
+ + "];");\r
}\r
- for (int tagID : _graph.getNodeIDSet())\r
- {\r
- for (int destNodeID : _graph.getDestNodeIDSetOf(tagID))\r
- {\r
+ for (int tagID : _graph.getNodeIDSet()) {\r
+ for (int destNodeID : _graph.getDestNodeIDSetOf(tagID)) {\r
gout.println(tagID + " -> " + destNodeID + ";");\r
}\r
}\r
help\r
}\r
\r
- public static void main(String[] args) throws OptionParserException\r
- {\r
- OptionParser<Opt> opt = new OptionParser<Opt>();\r
- opt.addOption(Opt.help, "h", "help", "display help messages");\r
+ static class Config {\r
+ @Option(symbol = "h", longName = "help", description = "display help messsage")\r
+ boolean displayHelp = false;\r
+\r
+ @Argument(index = 0, required = false)\r
+ String xmlFile = null;\r
+ }\r
+\r
+ public static void main(String[] args) throws OptionParserException {\r
+ Config config = new Config();\r
+ OptionParser opt = new OptionParser(config);\r
\r
opt.parse(args);\r
- if (opt.isSet(Opt.help) || opt.getArgumentLength() < 1)\r
- {\r
+ if (config.displayHelp || config.xmlFile == null) {\r
printHelpMessage(opt);\r
return;\r
}\r
\r
DataGuide dg = new DataGuide();\r
- try\r
- {\r
- dg.generateFrom(opt.getArgument(0));\r
+ try {\r
+ dg.generateFrom(config.xmlFile);\r
dg.outputGraphviz(System.out);\r
}\r
- catch (Exception e)\r
- {\r
+ catch (Exception e) {\r
System.err.println(e.getMessage());\r
}\r
}\r
\r
- private static void printHelpMessage(OptionParser<Opt> opt)\r
- {\r
- System.out.println("usage: > java -jar DataGuide.jar [option] xml_file");\r
- System.out.println(opt.helpMessage());\r
+ private static void printHelpMessage(OptionParser opt) {\r
+ opt.printUsage();\r
}\r
}\r
//--------------------------------------
package org.xerial.util.xml.index;
-import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
-import static org.xmlpull.v1.XmlPullParser.END_TAG;
-import static org.xmlpull.v1.XmlPullParser.START_TAG;
+import static org.xmlpull.v1.XmlPullParser.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.Collection;
import org.xerial.core.XerialException;
-import org.xerial.util.cui.OptionParser;
-import org.xerial.util.cui.OptionParserException;
import org.xerial.util.graph.AdjacencyList;
import org.xerial.util.graph.Edge;
import org.xerial.util.graph.Graph;
import org.xerial.util.graph.GraphvizHelper;
+import org.xerial.util.opt.Argument;
+import org.xerial.util.opt.Option;
+import org.xerial.util.opt.OptionParser;
+import org.xerial.util.opt.OptionParserException;
import org.xerial.util.xml.XMLErrorCode;
import org.xerial.util.xml.XMLException;
import org.xerial.util.xml.pullparser.PullParserUtil;
* @author leo
*
*/
-public class InvertedPathTree
-{
+public class InvertedPathTree {
private Graph<InvertedPath, String> _pathTree = new AdjacencyList<InvertedPath, String>();
// TreeMap<InvertedPath, Integer> _path2idMap = new TreeMap<InvertedPath, Integer>();
// TreeMap<Integer, InvertedPath> _id2pathMap = new TreeMap<Integer, InvertedPath>();
/**
*
*/
- public InvertedPathTree()
- {
+ public InvertedPathTree() {
super();
InvertedPath rootPath = new InvertedPath();
_rootID = _pathTree.addNode(rootPath);
}
- public void generateFrom(String xmlFile) throws XMLException, FileNotFoundException, IOException
- {
+ public void generateFrom(String xmlFile) throws XMLException, FileNotFoundException,
+ IOException {
generateFrom(new BufferedReader(new FileReader(xmlFile)));
}
- public void generateFrom(Reader xmlReader) throws IOException, XMLException
- {
+ public void generateFrom(Reader xmlReader) throws IOException, XMLException {
XmlPullParser parser = PullParserUtil.newParser(xmlReader);
- try
- {
+ try {
int state;
- while ((state = parser.next()) != END_DOCUMENT)
- {
- switch (state)
- {
+ while ((state = parser.next()) != END_DOCUMENT) {
+ switch (state) {
case START_TAG:
_currentInvertedPath.addChild(parser.getName());
- for (int i = 0; i < parser.getAttributeCount(); i++)
- {
+ for (int i = 0; i < parser.getAttributeCount(); i++) {
_currentInvertedPath.addChild("@" + parser.getAttributeName(i));
updateInvertedPathTree();
_currentInvertedPath.removeFirstChild();
}
}
- catch (XmlPullParserException e)
- {
+ catch (XmlPullParserException e) {
throw new XMLException(XMLErrorCode.PARSE_ERROR, e);
}
}
/**
* add nodes and edges corresponding to the current path
*/
- private void updateInvertedPathTree()
- {
+ private void updateInvertedPathTree() {
int cursor = _rootID;
InvertedPath cursorPath = new InvertedPath();
- for (String tag : _currentInvertedPath)
- {
+ for (String tag : _currentInvertedPath) {
cursorPath.addParent(tag);
Collection<Integer> destNodeID = _pathTree.getDestNodeIDSetOf(cursor);
int pathID = getPathID(cursorPath);
- if (!destNodeID.contains(pathID))
- {
+ if (!destNodeID.contains(pathID)) {
// create an edge from the cursor node to the pathID node
_pathTree.addEdge(new Edge(cursor, pathID), "edge");
}
}
}
- private int getPathID(InvertedPath path)
- {
+ private int getPathID(InvertedPath path) {
int pathID = _pathTree.getNodeID(path);
- if (pathID == -1)
- {
+ if (pathID == -1) {
InvertedPath clonePath = new InvertedPath(path);
pathID = _pathTree.addNode(clonePath);
}
return pathID;
}
- public void outputGraphviz(OutputStream os)
- {
+ public void outputGraphviz(OutputStream os) {
GraphvizHelper gout = new GraphvizHelper(os);
gout.beginDigraph("G");
// output node labels
- for (int pathID : _pathTree.getNodeIDSet())
- {
+ for (int pathID : _pathTree.getNodeIDSet()) {
InvertedPath path = _pathTree.getNodeLabel(pathID);
assert path != null;
gout.node(pathID, path.getLastParent());
gout.endOutput();
}
- private void outputGraphvizEdges(GraphvizHelper gout, int currentNodeID)
- {
- for (int dest : _pathTree.getDestNodeIDSetOf(currentNodeID))
- {
+ private void outputGraphvizEdges(GraphvizHelper gout, int currentNodeID) {
+ for (int dest : _pathTree.getDestNodeIDSetOf(currentNodeID)) {
gout.edge(currentNodeID, dest);
outputGraphvizEdges(gout, dest); // recursion
}
}
- enum Opt {
- help
- }
+ @Option(symbol = "h", longName = "help", description = "display help messsage")
+ private boolean displayHelp = false;
+
+ @Argument(index = 0, required = false)
+ private String xmlFile = null;
- public static void main(String[] args) throws OptionParserException
- {
- OptionParser<Opt> opt = new OptionParser<Opt>();
- opt.addOption(Opt.help, "h", "help", "display help messages");
+ public static void main(String[] args) throws OptionParserException {
+ InvertedPathTree ipt = new InvertedPathTree();
+ OptionParser opt = new OptionParser(ipt);
opt.parse(args);
- if (opt.isSet(Opt.help) || opt.getArgumentLength() < 1)
- {
+ if (ipt.displayHelp || ipt.xmlFile == null) {
printHelpMessage(opt);
return;
}
- InvertedPathTree ipt = new InvertedPathTree();
- try
- {
- ipt.generateFrom(opt.getArgument(0));
+ try {
+ ipt.generateFrom(ipt.xmlFile);
ipt.outputGraphviz(System.out);
}
- catch (XerialException e)
- {
+ catch (XerialException e) {
System.err.println(e.getMessage());
}
- catch (IOException e)
- {
+ catch (IOException e) {
System.err.println(e.getMessage());
}
}
- private static void printHelpMessage(OptionParser<Opt> opt)
- {
- System.out.println("usage: > java -jar DataGuide.jar [option] xml_file");
- System.out.println(opt.helpMessage());
+ private static void printHelpMessage(OptionParser opt) {
+ opt.printUsage();
}
}
//--------------------------------------
package org.xerial.util.xml.index;
-import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
-import static org.xmlpull.v1.XmlPullParser.END_TAG;
-import static org.xmlpull.v1.XmlPullParser.START_TAG;
-import static org.xmlpull.v1.XmlPullParser.TEXT;
+import static org.xmlpull.v1.XmlPullParser.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import org.xerial.core.XerialException;
import org.xerial.util.StringUtil;
-import org.xerial.util.cui.OptionParser;
-import org.xerial.util.cui.OptionParserException;
import org.xerial.util.graph.AdjacencyList;
import org.xerial.util.graph.Edge;
import org.xerial.util.graph.Graph;
import org.xerial.util.log.Logger;
+import org.xerial.util.opt.Argument;
+import org.xerial.util.opt.Option;
+import org.xerial.util.opt.OptionParser;
+import org.xerial.util.opt.OptionParserException;
import org.xerial.util.xml.SinglePath;
import org.xerial.util.xml.XMLErrorCode;
import org.xerial.util.xml.XMLException;
* @author leo
*
*/
-public class StrongDataGuide
-{
- private Graph<SinglePath, String> _graph = new AdjacencyList<SinglePath, String>();
- private int _currentPathID = 0;
- private Stack<Integer> _cursorHistory = new Stack<Integer>();
- private SinglePath _currentPath;
- private SinglePath _rootPath;
- private int _rootPathID;
- private Logger _logger = Logger.getLogger(StrongDataGuide.class);
+public class StrongDataGuide {
+ private Graph<SinglePath, String> _graph = new AdjacencyList<SinglePath, String>();
+ private int _currentPathID = 0;
+ private Stack<Integer> _cursorHistory = new Stack<Integer>();
+ private SinglePath _currentPath;
+ private SinglePath _rootPath;
+ private int _rootPathID;
+ private Logger _logger = Logger.getLogger(StrongDataGuide.class);
/**
*
*/
- public StrongDataGuide()
- {
+ public StrongDataGuide() {
super();
_rootPath = SinglePath.rootPath();
_rootPathID = _graph.addNode(_rootPath);
* @throws IOException
* @throws XerialException
*/
- public void generateFrom(String xmlFile) throws FileNotFoundException, XMLException, IOException, XerialException
- {
+ public void generateFrom(String xmlFile) throws FileNotFoundException, XMLException,
+ IOException, XerialException {
Reader reader = new BufferedReader(new FileReader(xmlFile));
generateFrom(reader);
}
* @throws FileNotFoundException
* @throws XMLParserException
*/
- public void generateFrom(Reader xmlReader) throws XMLException, IOException, XerialException
- {
+ public void generateFrom(Reader xmlReader) throws XMLException, IOException, XerialException {
// initialize
_currentPathID = _rootPathID;
_currentPath = _rootPath;
XmlPullParser parser = PullParserUtil.newParser(xmlReader);
- try
- {
+ try {
int state;
- while ((state = parser.next()) != END_DOCUMENT)
- {
- switch (state)
- {
+ while ((state = parser.next()) != END_DOCUMENT) {
+ switch (state) {
case START_TAG:
String name = parser.getName();
_logger.trace("start tag: " + name);
_logger.trace("path ID : " + pathID);
moveCursor(pathID);
// process attributes
- for (int i = 0; i < parser.getAttributeCount(); i++)
- {
- int attributeID = getPathID(String.format("%s@%s", name, parser.getAttributeName(i)));
+ for (int i = 0; i < parser.getAttributeCount(); i++) {
+ int attributeID = getPathID(String.format("%s@%s", name, parser
+ .getAttributeName(i)));
moveCursor(attributeID);
traceBack();
}
}
}
- catch (XmlPullParserException e)
- {
+ catch (XmlPullParserException e) {
throw new XMLException(XMLErrorCode.PARSE_ERROR, e);
}
}
- private void moveCursor(int pathID)
- {
+ private void moveCursor(int pathID) {
Collection<Integer> destNodeID = _graph.getDestNodeIDSetOf(_currentPathID);
- if (!destNodeID.contains(pathID))
- {
+ if (!destNodeID.contains(pathID)) {
_graph.addEdge(new Edge(_currentPathID, pathID), "edge");
}
_cursorHistory.push(_currentPathID);
_currentPath = _graph.getNodeLabel(pathID);
}
- private void traceBack()
- {
+ private void traceBack() {
assert !_cursorHistory.empty();
_currentPathID = _cursorHistory.pop();
_currentPath = _graph.getNodeLabel(_currentPathID);
}
- private int getPathID(String tagName)
- {
+ private int getPathID(String tagName) {
SinglePath path = new SinglePath(_currentPath, tagName);
int pathID = _graph.getNodeID(path);
- if (pathID == -1)
- {
+ if (pathID == -1) {
pathID = _graph.addNode(path);
}
return pathID;
}
- public void outputGraphviz(OutputStream out)
- {
+ public void outputGraphviz(OutputStream out) {
PrintWriter gout = new PrintWriter(out);
gout.println("digraph G {");
// output node labels
- for (int pathID : _graph.getNodeIDSet())
- {
+ for (int pathID : _graph.getNodeIDSet()) {
SinglePath path = _graph.getNodeLabel(pathID);
gout.println(pathID + " [label=" + StringUtil.quote(path.getLeaf(), "\"") + "];");
}
- for (int pathID : _graph.getNodeIDSet())
- {
- for (int destNodeID : _graph.getDestNodeIDSetOf(pathID))
- {
+ for (int pathID : _graph.getNodeIDSet()) {
+ for (int destNodeID : _graph.getDestNodeIDSetOf(pathID)) {
gout.println(pathID + " -> " + destNodeID + ";");
}
}
gout.flush();
}
- public static enum Opt {
- help
- }
+ @Option(symbol = "h", longName = "help", description = "display help messsage")
+ boolean displayHelp = false;
+
+ @Argument(index = 0, required = false)
+ String xmlFile = null;
- public static void main(String[] args) throws OptionParserException
- {
- OptionParser<Opt> opt = new OptionParser<Opt>();
- opt.addOption(Opt.help, "h", "help", "display help messages");
+ public static void main(String[] args) throws OptionParserException {
+ StrongDataGuide sdg = new StrongDataGuide();
+ OptionParser opt = new OptionParser(sdg);
opt.parse(args);
- if (opt.isSet(Opt.help) || opt.getArgumentLength() < 1)
- {
+ if (sdg.displayHelp || sdg.xmlFile == null) {
printHelpMessage(opt);
return;
}
- StrongDataGuide sdg = new StrongDataGuide();
- try
- {
- sdg.generateFrom(opt.getArgument(0));
+ try {
+ sdg.generateFrom(sdg.xmlFile);
sdg.outputGraphviz(System.out);
}
- catch (XerialException e)
- {
+ catch (XerialException e) {
System.err.println(e.getMessage());
}
- catch (IOException e)
- {
+ catch (IOException e) {
System.err.println(e.getMessage());
}
}
- private static void printHelpMessage(OptionParser<Opt> opt)
- {
- System.out.println("usage: > java -jar StrongDataGuide.jar [option] xml_file");
- System.out.println(opt.helpMessage());
-
+ private static void printHelpMessage(OptionParser opt) {
+ opt.printUsage();
}
}
# reference sequence\r
class Reference < Locus\r
Coordinate :coodinate\r
- string :name\r
sequence :sequence \r
end\r
\r
+++ /dev/null
-/*--------------------------------------------------------------------------
- * Copyright 2007 Taro L. Saito
- *
- * 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.
- *--------------------------------------------------------------------------*/
-//--------------------------------------
-// XerialJ Project
-//
-// Option_optParserTest.java
-// Since: 2005/01/03
-//
-// $URL$
-// $Author$
-//--------------------------------------
-package org.xerial.util.cui;
-
-import junit.framework.TestCase;
-
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * @author leo
- *
- */
-public class OptionParserTest extends TestCase
-{
- enum Opt {
- HELP, OUTDIR, VERBOSE, MODE, WINDOWSIZE, LOGLEVEL
- }
-
- OptionParser<Opt> _optParser;
-
- @Before
- protected void setUp() throws Exception
- {
- _optParser = new OptionParser<Opt>();
- _optParser.addOption(Opt.HELP, "h", "help", "display help message");
-
- _optParser.addOptionWithArgument(Opt.OUTDIR, "o", "output", "DIR", "secify output directory", ".");
- _optParser.addOptionWithArgument(Opt.MODE, "m", "mode", "MODE", "select mode (1-3)", "1");
-
- OptionGroup<Opt> cuiOptionGroup = new OptionGroup<Opt>("CUI", true);
- cuiOptionGroup.addOption(Opt.VERBOSE, "v", "verbose", "display verbose messages");
- _optParser.addOptionGroup(cuiOptionGroup);
-
- OptionGroup<Opt> guiOptionGroup = new OptionGroup<Opt>("GUI", true);
- guiOptionGroup.addOptionWithArgment(Opt.WINDOWSIZE, "", "windowsize", "SIZE", "set GUI window size", "100");
- _optParser.addOptionGroup(guiOptionGroup);
- }
-
- @Test
- public void testDeafaultValue() throws OptionParserException
- {
- _optParser.parse(new String[] { "" });
- assertEquals(".", _optParser.getValue(Opt.OUTDIR));
- assertEquals(1, _optParser.getIntValue(Opt.MODE));
- assertEquals(100, _optParser.getIntValue(Opt.WINDOWSIZE));
- }
-
- @Test
- public void testParse() throws OptionParserException
- {
- _optParser.parse(new String[] { "-vh", "-o", "outdir", "inputfile.xml" });
-
- assertTrue(_optParser.isSet(Opt.HELP));
- assertTrue(_optParser.isSet(Opt.VERBOSE));
- assertTrue(_optParser.isSet(Opt.OUTDIR));
- assertFalse(_optParser.isSet(Opt.MODE));
- assertFalse(_optParser.isSet(Opt.WINDOWSIZE));
- assertEquals("outdir", _optParser.getValue(Opt.OUTDIR));
- assertEquals(1, _optParser.getArgumentLength());
- assertEquals("inputfile.xml", _optParser.getArgument(0));
- }
-
- @Test
- public void testDupilicateOption()
- {
- try
- {
- // never allow duplicatte options
- _optParser.addOption(Opt.HELP, "h", "help2", "another help");
- fail("failed to detect duplicate options");
- }
- catch (IllegalArgumentException e)
- {
- // success
- }
- }
-
- @Test
- public void testDupilicateOption2()
- {
- try
- {
- // Even if two options with the same ID belong to the different option groups, we do not allow duplicate option IDs.
- OptionGroup<Opt> tmpGroup = new OptionGroup<Opt>("tmp");
- tmpGroup.addOption(Opt.HELP, "h", "help2", "another help");
- _optParser.addOptionGroup(tmpGroup);
- fail("failed to detect duplicate option IDs");
- }
- catch (IllegalArgumentException e)
- {
- // success
- }
- }
-
- @Test
- public void testLongOptionArgument() throws OptionParserException
- {
- String args[] = { "--mode=mixed" };
- _optParser.parse(args);
- assertTrue(_optParser.isSet(Opt.MODE));
- assertEquals("mixed", _optParser.getValue(Opt.MODE));
- assertEquals(0, _optParser.getArgumentLength());
- }
-
- @Test
- public void testGroupCompatibility()
- {
- String args[] = { "-v", "--windowsize=200" };
- try
- {
- _optParser.parse(args);
- fail("OptionParser must recongnize that imcompatible options are set at the same time");
- }
- catch (OptionParserException e)
- {
- //System.err.println(e.getMessage());
- }
- }
-
- boolean helpflag = false;
- boolean logLevelFlag = false;
- String logLevel = null;
-
- @Test
- public void testHandler() throws OptionParserException
- {
- OptionParser<Opt> parser = new OptionParser<Opt>();
-
- parser.addOption(Opt.HELP, "h", "help", "set the helpflag", new OptionHandler<Opt>() {
- public void handle(OptionParser<Opt> parser) throws OptionParserException
- {
- helpflag = true;
- }
- });
-
- parser.addOptionWithArgument(Opt.LOGLEVEL, "l", "loglevel", "LEVEL", "set loglevel", new OptionHandler<Opt>() {
- public void handle(OptionParser<Opt> parser) throws OptionParserException
- {
- logLevelFlag = true;
- logLevel = parser.getValue(Opt.LOGLEVEL, "INFO");
- }
- });
-
- parser.parse(new String[] { "-h", "--loglevel=DEBUG" });
-
- assertTrue(helpflag);
- assertTrue(logLevelFlag);
- assertEquals("DEBUG", logLevel);
- }
-
- @Test
- public void testGroupOptionHandler() throws OptionParserException
- {
- OptionParser<Opt> parser = new OptionParser<Opt>();
-
- OptionGroup<Opt> group = new OptionGroup<Opt>("group");
- group.addOption(Opt.HELP, "h", "help", "set the helpflag", new OptionHandler<Opt>() {
- public void handle(OptionParser<Opt> parser) throws OptionParserException
- {
- helpflag = true;
- }
- });
-
- parser.addOptionGroup(group);
-
- parser.parse(new String[] { "-h" });
-
- assertTrue(helpflag);
- }
-
-}