commons-cli-1.2-src/src/ 40755 0 0 0 11157377776 12227 5ustar 0 0 commons-cli-1.2-src/src/assembly/ 40755 0 0 0 11157377772 14042 5ustar 0 0 commons-cli-1.2-src/src/conf/ 40755 0 0 0 11157377776 13154 5ustar 0 0 commons-cli-1.2-src/src/java/ 40755 0 0 0 11157377775 13147 5ustar 0 0 commons-cli-1.2-src/src/java/org/ 40755 0 0 0 11157377775 13736 5ustar 0 0 commons-cli-1.2-src/src/java/org/apache/ 40755 0 0 0 11157377775 15157 5ustar 0 0 commons-cli-1.2-src/src/java/org/apache/commons/ 40755 0 0 0 11157377775 16632 5ustar 0 0 commons-cli-1.2-src/src/java/org/apache/commons/cli/ 40755 0 0 0 11157377776 17402 5ustar 0 0 commons-cli-1.2-src/src/media/ 40755 0 0 0 11157377773 13303 5ustar 0 0 commons-cli-1.2-src/src/test/ 40755 0 0 0 11157377773 13203 5ustar 0 0 commons-cli-1.2-src/src/test/org/ 40755 0 0 0 11157377773 13772 5ustar 0 0 commons-cli-1.2-src/src/test/org/apache/ 40755 0 0 0 11157377773 15213 5ustar 0 0 commons-cli-1.2-src/src/test/org/apache/commons/ 40755 0 0 0 11157377773 16666 5ustar 0 0 commons-cli-1.2-src/src/test/org/apache/commons/cli/ 40755 0 0 0 11157377775 17437 5ustar 0 0 commons-cli-1.2-src/src/test/org/apache/commons/cli/bug/ 40755 0 0 0 11157377775 20214 5ustar 0 0 commons-cli-1.2-src/LICENSE.txt100644 0 0 26136 11157377776 13410 0ustar 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. commons-cli-1.2-src/NOTICE.txt100644 0 0 254 11157377776 13240 0ustar 0 0 Apache Commons CLI Copyright 2001-2009 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). commons-cli-1.2-src/pom.xml100644 0 0 17454 11157377776 13105 0ustar 0 0 org.apache.commons commons-parent 11 4.0.0 commons-cli commons-cli 1.2 Commons CLI 2002 Commons CLI provides a simple API for presenting, processing and validating a command line interface. http://commons.apache.org/cli/ jira http://issues.apache.org/jira/browse/CLI scm:svn:http://svn.apache.org/repos/asf/commons/proper/cli/branches/cli-1.x/ scm:svn:https://svn.apache.org/repos/asf/commons/proper/cli/branches/cli-1.x/ http://svn.apache.org/viewvc/commons/proper/cli/branches/cli-1.x/ James Strachan jstrachan jstrachan@apache.org SpiritSoft, Inc. Bob McWhirter bob bob@werken.com Werken contributed ideas and code from werken.opt John Keyes jkeyes jbjk@mac.com integral Source contributed ideas and code from Optz Rob Oxspring roxspring roxspring@imapmail.org Indigo Stone designed CLI2 Peter Donald contributed ideas and code from Avalon Excalibur's cli package Brian Egge made the 1.1 release happen Berin Loritsch bloritsch@apache.org helped in the Avalon CLI merge Peter Maddocks peter_maddocks@hp.com Hewlett-Packard supplied patch Andrew Shirley lots of fixes for 1.1 junit junit 3.8.1 test 1.4 1.4 cli 1.2 commons-cli-${commons.release.version} org.apache.commons.cli CLI 12310463 RC7 src/java src/test . META-INF NOTICE.txt LICENSE.txt maven-assembly-plugin src/assembly/bin.xml src/assembly/src.xml gnu org.codehaus.mojo findbugs-maven-plugin 1.2 Normal Default org.apache.maven.plugins maven-checkstyle-plugin src/conf/checkstyle.xml org.apache.maven.plugins maven-pmd-plugin org.codehaus.mojo cobertura-maven-plugin 2.2 org.codehaus.mojo clirr-maven-plugin 2.2.1 1.1 gump maven.final.name maven-jar-plugin ${maven.final.name} rc apache.website Apache Commons Release Candidate Staging Site ${commons.deployment.protocol}://people.apache.org/www/people.apache.org/builds/commons/${commons.componentid}/${commons.release.version}/${commons.rc.version}/site commons-cli-1.2-src/README.txt100644 0 0 1004 11157377776 13226 0ustar 0 0 Apache Commons CLI =================== Welcome to the CLI 1.x component of the Apache Commons project. The information in this file is relevant if you have downloaded a CLI source distribution. CLI is built with Maven 2, which can be found here: http://maven.apache.org and to build and test the system use: mvn clean package The system will build and test itself. For complete documentation and to create a local copy of the CLI project website, type: mvn site Good luck! - The Apache Commons Team commons-cli-1.2-src/RELEASE-NOTES.txt100644 0 0 5042 11157377776 14245 0ustar 0 0 $Id: RELEASE-NOTES.txt 695235 2008-09-14 15:26:10Z ebourg $ Commons CLI Package Version 1.2 Release Notes INTRODUCTION: This document contains the release notes for this version of the Commons CLI package. Commons CLI provides a simple API for working with the command line arguments and options. Commons CLI 1.2 is a bugfix release. The following notable changes were made: * A major regression introduced in CLI 1.1 that prevented the usage of repeated options has been fixed. * Several parser issues have been fixed, especially with the PosixParser. * HelpFormatter now wraps the lines properly * The ordering of the option in the help message can now be defined. * Various API enhancements (improved exceptions, serializable classes) Commons CLI 1.2 is binary compatible with the previous versions, except for the OptionValidator class that is no longer public. More information can be found on the project site at http://commons.apache.org/cli NEW FEATURES: * The method getOptionProperties() in the CommandLine class was added to retrieve easily the key/value pairs specified with options like -Dkey1=value1 -Dkey2=value2. * GnuParser now supports long options with an '=' sign (ie. --foo=bar and -foo=bar) (CLI-157) * The ordering of options can be defined in help messages. (CLI-155) BUG FIXES: * The number of arguments defined for an option specifies the arguments per occurrence of the option and not for all occurrences. (CLI-137) * PosixParser no longer ignores unrecognized short options. (CLI-164) * PosixParser no longer stops the bursting process of a token if stopAtNonOption is enabled and a non option character is encountered. (CLI-163) * PosixParser no longer keeps processing the tokens after an unrecognized long option when stopAtNonOption is enabled. (CLI-165) * Required options are properly checked if an Options instance is used twice to parse a command line. (CLI-156) * The line wrapping in HelpFormatter now works properly. (CLI-151) CHANGES: * The message of MissingOptionException has been improved. (CLI-149) * The exceptions have been enhanced with methods to retrieve easily the related options. (CLI-86) * Option.toString() now reports arguments properly. (CLI-141) * The Parser class has been changed to be more easily extendable. (CLI-142) * The following classes are now serializable: Option, OptionGroup, CommandLine and Options. (CLI-140) * OptionValidator is no longer public, its methods were all private. commons-cli-1.2-src/src/assembly/bin.xml100644 0 0 3061 11157377772 15431 0ustar 0 0 bin tar.gz zip false LICENSE.txt NOTICE.txt RELEASE-NOTES.txt target *.jar target/site/apidocs apidocs commons-cli-1.2-src/src/assembly/src.xml100644 0 0 3254 11157377772 15454 0ustar 0 0 src tar.gz zip ${project.artifactId}-${commons.release.version}-src build.xml build.properties CLI2Converter.java CLI2ConverterTest.java LICENSE.txt NOTICE.txt pom.xml README.txt RELEASE-NOTES.txt src xdocs commons-cli-1.2-src/src/conf/checkstyle.xml100644 0 0 16665 11157377776 16167 0ustar 0 0 commons-cli-1.2-src/src/conf/HEADER.txt100644 0 0 1443 11157377776 14744 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ commons-cli-1.2-src/src/conf/MANIFEST.MF100644 0 0 1572 11157377776 14710 0ustar 0 0 Manifest-Version: 1.0 Implementation-Title: Commons CLI Implementation-Vendor: The Apache Software Foundation Implementation-Vendor-Id: org.apache Implementation-Version: 1.2-SNAPSHOT Specification-Title: Commons CLI Specification-Vendor: The Apache Software Foundation Specification-Version: 1.2-SNAPSHOT X-Compile-Source-JDK: 1.3 X-Compile-Target-JDK: 1.3 Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt Import-Package: org.apache.commons.cli;version="1.2.0.SNAPSHOT" Export-Package: org.apache.commons.cli;version="1.2.0.SNAPSHOT" Bundle-Version: 1.2.0.SNAPSHOT Bundle-Name: Commons CLI Bundle-Description: Commons CLI provides a simple API for presenting, processing and validating a command line interface. Bundle-DocURL: http://commons.apache.org/cli/ Bundle-ManifestVersion: 2 Bundle-Vendor: The Apache Software Foundation Bundle-SymbolicName: org.apache.commons.cli commons-cli-1.2-src/src/java/org/apache/commons/cli/AlreadySelectedException.java100644 0 0 5001 11157377776 25247 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * Thrown when more than one option in an option group * has been provided. * * @author John Keyes ( john at integralsource.com ) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class AlreadySelectedException extends ParseException { /** The option group selected. */ private OptionGroup group; /** The option that triggered the exception. */ private Option option; /** * Construct a new AlreadySelectedException * with the specified detail message. * * @param message the detail message */ public AlreadySelectedException(String message) { super(message); } /** * Construct a new AlreadySelectedException * for the specified option group. * * @param group the option group already selected * @param option the option that triggered the exception * @since 1.2 */ public AlreadySelectedException(OptionGroup group, Option option) { this("The option '" + option.getKey() + "' was specified but an option from this group " + "has already been selected: '" + group.getSelected() + "'"); this.group = group; this.option = option; } /** * Returns the option group where another option has been selected. * * @return the related option group * @since 1.2 */ public OptionGroup getOptionGroup() { return group; } /** * Returns the option that was added to the group and triggered the exception. * * @return the related option * @since 1.2 */ public Option getOption() { return option; } } commons-cli-1.2-src/src/java/org/apache/commons/cli/BasicParser.java100644 0 0 3601 11157377776 22540 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * The class BasicParser provides a very simple implementation of * the {@link Parser#flatten(Options,String[],boolean) flatten} method. * * @author John Keyes (john at integralsource.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class BasicParser extends Parser { /** *

A simple implementation of {@link Parser}'s abstract * {@link Parser#flatten(Options, String[], boolean) flatten} method.

* *

Note: options and stopAtNonOption * are not used in this flatten method.

* * @param options The command line {@link Options} * @param arguments The command line arguments to be parsed * @param stopAtNonOption Specifies whether to stop flattening * when an non option is found. * @return The arguments String array. */ protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { // just echo the arguments return arguments; } } commons-cli-1.2-src/src/java/org/apache/commons/cli/CommandLine.java100644 0 0 25661 11157377776 22562 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; /** * Represents list of arguments parsed against a {@link Options} descriptor. * *

It allows querying of a boolean {@link #hasOption(String opt)}, * in addition to retrieving the {@link #getOptionValue(String opt)} * for options requiring arguments.

* *

Additionally, any left-over or unrecognized arguments, * are available for further processing.

* * @author bob mcwhirter (bob @ werken.com) * @author James Strachan * @author John Keyes (john at integralsource.com) * @version $Revision: 735247 $, $Date: 2009-01-17 00:23:35 -0800 (Sat, 17 Jan 2009) $ */ public class CommandLine implements Serializable { private static final long serialVersionUID = 1L; /** the unrecognised options/arguments */ private List args = new LinkedList(); /** the processed options */ private List options = new ArrayList(); /** * Creates a command line. */ CommandLine() { // nothing to do } /** * Query to see if an option has been set. * * @param opt Short name of the option * @return true if set, false if not */ public boolean hasOption(String opt) { return options.contains(resolveOption(opt)); } /** * Query to see if an option has been set. * * @param opt character name of the option * @return true if set, false if not */ public boolean hasOption(char opt) { return hasOption(String.valueOf(opt)); } /** * Return the Object type of this Option. * * @param opt the name of the option * @return the type of this Option * @deprecated due to System.err message. Instead use getParsedOptionValue(String) */ public Object getOptionObject(String opt) { try { return getParsedOptionValue(opt); } catch(ParseException pe) { System.err.println("Exception found converting " + opt + " to desired type: " + pe.getMessage() ); return null; } } /** * Return a version of this Option converted to a particular type. * * @param opt the name of the option * @return the value parsed into a particluar object * @throws ParseException if there are problems turning the option value into the desired type * @see PatternOptionBuilder */ public Object getParsedOptionValue(String opt) throws ParseException { String res = getOptionValue(opt); Option option = resolveOption(opt); if (option == null) { return null; } Object type = option.getType(); return (res == null) ? null : TypeHandler.createValue(res, type); } /** * Return the Object type of this Option. * * @param opt the name of the option * @return the type of opt */ public Object getOptionObject(char opt) { return getOptionObject(String.valueOf(opt)); } /** * Retrieve the argument, if any, of this option. * * @param opt the name of the option * @return Value of the argument if option is set, and has an argument, * otherwise null. */ public String getOptionValue(String opt) { String[] values = getOptionValues(opt); return (values == null) ? null : values[0]; } /** * Retrieve the argument, if any, of this option. * * @param opt the character name of the option * @return Value of the argument if option is set, and has an argument, * otherwise null. */ public String getOptionValue(char opt) { return getOptionValue(String.valueOf(opt)); } /** * Retrieves the array of values, if any, of an option. * * @param opt string name of the option * @return Values of the argument if option is set, and has an argument, * otherwise null. */ public String[] getOptionValues(String opt) { List values = new ArrayList(); for (Iterator it = options.iterator(); it.hasNext();) { Option option = (Option) it.next(); if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt())) { values.addAll(option.getValuesList()); } } return values.isEmpty() ? null : (String[]) values.toArray(new String[values.size()]); } /** * Retrieves the option object given the long or short option as a String * * @param opt short or long name of the option * @return Canonicalized option */ private Option resolveOption(String opt) { opt = Util.stripLeadingHyphens(opt); for (Iterator it = options.iterator(); it.hasNext();) { Option option = (Option) it.next(); if (opt.equals(option.getOpt())) { return option; } if (opt.equals(option.getLongOpt())) { return option; } } return null; } /** * Retrieves the array of values, if any, of an option. * * @param opt character name of the option * @return Values of the argument if option is set, and has an argument, * otherwise null. */ public String[] getOptionValues(char opt) { return getOptionValues(String.valueOf(opt)); } /** * Retrieve the argument, if any, of an option. * * @param opt name of the option * @param defaultValue is the default value to be returned if the option * is not specified * @return Value of the argument if option is set, and has an argument, * otherwise defaultValue. */ public String getOptionValue(String opt, String defaultValue) { String answer = getOptionValue(opt); return (answer != null) ? answer : defaultValue; } /** * Retrieve the argument, if any, of an option. * * @param opt character name of the option * @param defaultValue is the default value to be returned if the option * is not specified * @return Value of the argument if option is set, and has an argument, * otherwise defaultValue. */ public String getOptionValue(char opt, String defaultValue) { return getOptionValue(String.valueOf(opt), defaultValue); } /** * Retrieve the map of values associated to the option. This is convenient * for options specifying Java properties like -Dparam1=value1 * -Dparam2=value2. The first argument of the option is the key, and * the 2nd argument is the value. If the option has only one argument * (-Dfoo) it is considered as a boolean flag and the value is * "true". * * @param opt name of the option * @return The Properties mapped by the option, never null * even if the option doesn't exists * @since 1.2 */ public Properties getOptionProperties(String opt) { Properties props = new Properties(); for (Iterator it = options.iterator(); it.hasNext();) { Option option = (Option) it.next(); if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt())) { List values = option.getValuesList(); if (values.size() >= 2) { // use the first 2 arguments as the key/value pair props.put(values.get(0), values.get(1)); } else if (values.size() == 1) { // no explicit value, handle it as a boolean props.put(values.get(0), "true"); } } } return props; } /** * Retrieve any left-over non-recognized options and arguments * * @return remaining items passed in but not parsed as an array */ public String[] getArgs() { String[] answer = new String[args.size()]; args.toArray(answer); return answer; } /** * Retrieve any left-over non-recognized options and arguments * * @return remaining items passed in but not parsed as a List. */ public List getArgList() { return args; } /** * jkeyes * - commented out until it is implemented properly *

Dump state, suitable for debugging.

* * @return Stringified form of this object */ /* public String toString() { StringBuffer buf = new StringBuffer(); buf.append("[ CommandLine: [ options: "); buf.append(options.toString()); buf.append(" ] [ args: "); buf.append(args.toString()); buf.append(" ] ]"); return buf.toString(); } */ /** * Add left-over unrecognized option/argument. * * @param arg the unrecognised option/argument. */ void addArg(String arg) { args.add(arg); } /** * Add an option to the command line. The values of the option are stored. * * @param opt the processed option */ void addOption(Option opt) { options.add(opt); } /** * Returns an iterator over the Option members of CommandLine. * * @return an Iterator over the processed {@link Option} * members of this {@link CommandLine} */ public Iterator iterator() { return options.iterator(); } /** * Returns an array of the processed {@link Option}s. * * @return an array of the processed {@link Option}s. */ public Option[] getOptions() { Collection processed = options; // reinitialise array Option[] optionsArray = new Option[processed.size()]; // return the array return (Option[]) processed.toArray(optionsArray); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/CommandLineParser.java100644 0 0 7332 11157377776 23712 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * A class that implements the CommandLineParser interface * can parse a String array according to the {@link Options} specified * and return a {@link CommandLine}. * * @author John Keyes (john at integralsource.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public interface CommandLineParser { /** * Parse the arguments according to the specified options. * * @param options the specified Options * @param arguments the command line arguments * @return the list of atomic option and value tokens * * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ CommandLine parse(Options options, String[] arguments) throws ParseException; /** * Parse the arguments according to the specified options and * properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @return the list of atomic option and value tokens * * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ /* To maintain binary compatibility, this is commented out. It is still in the abstract Parser class, so most users will still reap the benefit. CommandLine parse(Options options, String[] arguments, Properties properties) throws ParseException; */ /** * Parse the arguments according to the specified options. * * @param options the specified Options * @param arguments the command line arguments * @param stopAtNonOption specifies whether to continue parsing the * arguments if a non option is encountered. * * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException; /** * Parse the arguments according to the specified options and * properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @param stopAtNonOption specifies whether to continue parsing the * * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ /* To maintain binary compatibility, this is commented out. It is still in the abstract Parser class, so most users will still reap the benefit. CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) throws ParseException; */ } commons-cli-1.2-src/src/java/org/apache/commons/cli/GnuParser.java100644 0 0 10030 11157377776 22262 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.ArrayList; import java.util.List; /** * The class GnuParser provides an implementation of the * {@link Parser#flatten(Options, String[], boolean) flatten} method. * * @author John Keyes (john at integralsource.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class GnuParser extends Parser { /** * This flatten method does so using the following rules: *
    *
  1. If an {@link Option} exists for the first character of * the arguments entry AND an {@link Option} * does not exist for the whole argument then * add the first character as an option to the processed tokens * list e.g. "-D" and add the rest of the entry to the also.
  2. *
  3. Otherwise just add the token to the processed tokens list.
  4. *
* * @param options The Options to parse the arguments by. * @param arguments The arguments that have to be flattened. * @param stopAtNonOption specifies whether to stop flattening when * a non option has been encountered * @return a String array of the flattened arguments */ protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { List tokens = new ArrayList(); boolean eatTheRest = false; for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; if ("--".equals(arg)) { eatTheRest = true; tokens.add("--"); } else if ("-".equals(arg)) { tokens.add("-"); } else if (arg.startsWith("-")) { String opt = Util.stripLeadingHyphens(arg); if (options.hasOption(opt)) { tokens.add(arg); } else { if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('=')))) { // the format is --foo=value or -foo=value tokens.add(arg.substring(0, arg.indexOf('='))); // --foo tokens.add(arg.substring(arg.indexOf('=') + 1)); // value } else if (options.hasOption(arg.substring(0, 2))) { // the format is a special properties option (-Dproperty=value) tokens.add(arg.substring(0, 2)); // -D tokens.add(arg.substring(2)); // property=value } else { eatTheRest = stopAtNonOption; tokens.add(arg); } } } else { tokens.add(arg); } if (eatTheRest) { for (i++; i < arguments.length; i++) { tokens.add(arguments[i]); } } } return (String[]) tokens.toArray(new String[tokens.size()]); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/HelpFormatter.java100644 0 0 72540 11157377776 23146 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * A formatter of help messages for the current command line options * * @author Slawek Zachcial * @author John Keyes (john at integralsource.com) * @version $Revision: 751120 $, $Date: 2009-03-06 14:45:57 -0800 (Fri, 06 Mar 2009) $ */ public class HelpFormatter { // --------------------------------------------------------------- Constants /** default number of characters per line */ public static final int DEFAULT_WIDTH = 74; /** default padding to the left of each line */ public static final int DEFAULT_LEFT_PAD = 1; /** * the number of characters of padding to be prefixed * to each description line */ public static final int DEFAULT_DESC_PAD = 3; /** the string to display at the beginning of the usage statement */ public static final String DEFAULT_SYNTAX_PREFIX = "usage: "; /** default prefix for shortOpts */ public static final String DEFAULT_OPT_PREFIX = "-"; /** default prefix for long Option */ public static final String DEFAULT_LONG_OPT_PREFIX = "--"; /** default name for an argument */ public static final String DEFAULT_ARG_NAME = "arg"; // -------------------------------------------------------------- Attributes /** * number of characters per line * * @deprecated Scope will be made private for next major version * - use get/setWidth methods instead. */ public int defaultWidth = DEFAULT_WIDTH; /** * amount of padding to the left of each line * * @deprecated Scope will be made private for next major version * - use get/setLeftPadding methods instead. */ public int defaultLeftPad = DEFAULT_LEFT_PAD; /** * the number of characters of padding to be prefixed * to each description line * * @deprecated Scope will be made private for next major version * - use get/setDescPadding methods instead. */ public int defaultDescPad = DEFAULT_DESC_PAD; /** * the string to display at the begining of the usage statement * * @deprecated Scope will be made private for next major version * - use get/setSyntaxPrefix methods instead. */ public String defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX; /** * the new line string * * @deprecated Scope will be made private for next major version * - use get/setNewLine methods instead. */ public String defaultNewLine = System.getProperty("line.separator"); /** * the shortOpt prefix * * @deprecated Scope will be made private for next major version * - use get/setOptPrefix methods instead. */ public String defaultOptPrefix = DEFAULT_OPT_PREFIX; /** * the long Opt prefix * * @deprecated Scope will be made private for next major version * - use get/setLongOptPrefix methods instead. */ public String defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX; /** * the name of the argument * * @deprecated Scope will be made private for next major version * - use get/setArgName methods instead. */ public String defaultArgName = DEFAULT_ARG_NAME; /** * Comparator used to sort the options when they output in help text * * Defaults to case-insensitive alphabetical sorting by option key */ protected Comparator optionComparator = new OptionComparator(); /** * Sets the 'width'. * * @param width the new value of 'width' */ public void setWidth(int width) { this.defaultWidth = width; } /** * Returns the 'width'. * * @return the 'width' */ public int getWidth() { return defaultWidth; } /** * Sets the 'leftPadding'. * * @param padding the new value of 'leftPadding' */ public void setLeftPadding(int padding) { this.defaultLeftPad = padding; } /** * Returns the 'leftPadding'. * * @return the 'leftPadding' */ public int getLeftPadding() { return defaultLeftPad; } /** * Sets the 'descPadding'. * * @param padding the new value of 'descPadding' */ public void setDescPadding(int padding) { this.defaultDescPad = padding; } /** * Returns the 'descPadding'. * * @return the 'descPadding' */ public int getDescPadding() { return defaultDescPad; } /** * Sets the 'syntaxPrefix'. * * @param prefix the new value of 'syntaxPrefix' */ public void setSyntaxPrefix(String prefix) { this.defaultSyntaxPrefix = prefix; } /** * Returns the 'syntaxPrefix'. * * @return the 'syntaxPrefix' */ public String getSyntaxPrefix() { return defaultSyntaxPrefix; } /** * Sets the 'newLine'. * * @param newline the new value of 'newLine' */ public void setNewLine(String newline) { this.defaultNewLine = newline; } /** * Returns the 'newLine'. * * @return the 'newLine' */ public String getNewLine() { return defaultNewLine; } /** * Sets the 'optPrefix'. * * @param prefix the new value of 'optPrefix' */ public void setOptPrefix(String prefix) { this.defaultOptPrefix = prefix; } /** * Returns the 'optPrefix'. * * @return the 'optPrefix' */ public String getOptPrefix() { return defaultOptPrefix; } /** * Sets the 'longOptPrefix'. * * @param prefix the new value of 'longOptPrefix' */ public void setLongOptPrefix(String prefix) { this.defaultLongOptPrefix = prefix; } /** * Returns the 'longOptPrefix'. * * @return the 'longOptPrefix' */ public String getLongOptPrefix() { return defaultLongOptPrefix; } /** * Sets the 'argName'. * * @param name the new value of 'argName' */ public void setArgName(String name) { this.defaultArgName = name; } /** * Returns the 'argName'. * * @return the 'argName' */ public String getArgName() { return defaultArgName; } /** * Comparator used to sort the options when they output in help text * * Defaults to case-insensitive alphabetical sorting by option key */ public Comparator getOptionComparator() { return optionComparator; } /** * Set the comparator used to sort the options when they output in help text * * Passing in a null parameter will set the ordering to the default mode */ public void setOptionComparator(Comparator comparator) { if (comparator == null) { this.optionComparator = new OptionComparator(); } else { this.optionComparator = comparator; } } /** * Print the help for options with the specified * command line syntax. This method prints help information to * System.out. * * @param cmdLineSyntax the syntax for this application * @param options the Options instance */ public void printHelp(String cmdLineSyntax, Options options) { printHelp(defaultWidth, cmdLineSyntax, null, options, null, false); } /** * Print the help for options with the specified * command line syntax. This method prints help information to * System.out. * * @param cmdLineSyntax the syntax for this application * @param options the Options instance * @param autoUsage whether to print an automatically generated * usage statement */ public void printHelp(String cmdLineSyntax, Options options, boolean autoUsage) { printHelp(defaultWidth, cmdLineSyntax, null, options, null, autoUsage); } /** * Print the help for options with the specified * command line syntax. This method prints help information to * System.out. * * @param cmdLineSyntax the syntax for this application * @param header the banner to display at the begining of the help * @param options the Options instance * @param footer the banner to display at the end of the help */ public void printHelp(String cmdLineSyntax, String header, Options options, String footer) { printHelp(cmdLineSyntax, header, options, footer, false); } /** * Print the help for options with the specified * command line syntax. This method prints help information to * System.out. * * @param cmdLineSyntax the syntax for this application * @param header the banner to display at the begining of the help * @param options the Options instance * @param footer the banner to display at the end of the help * @param autoUsage whether to print an automatically generated * usage statement */ public void printHelp(String cmdLineSyntax, String header, Options options, String footer, boolean autoUsage) { printHelp(defaultWidth, cmdLineSyntax, header, options, footer, autoUsage); } /** * Print the help for options with the specified * command line syntax. This method prints help information to * System.out. * * @param width the number of characters to be displayed on each line * @param cmdLineSyntax the syntax for this application * @param header the banner to display at the beginning of the help * @param options the Options instance * @param footer the banner to display at the end of the help */ public void printHelp(int width, String cmdLineSyntax, String header, Options options, String footer) { printHelp(width, cmdLineSyntax, header, options, footer, false); } /** * Print the help for options with the specified * command line syntax. This method prints help information to * System.out. * * @param width the number of characters to be displayed on each line * @param cmdLineSyntax the syntax for this application * @param header the banner to display at the begining of the help * @param options the Options instance * @param footer the banner to display at the end of the help * @param autoUsage whether to print an automatically generated * usage statement */ public void printHelp(int width, String cmdLineSyntax, String header, Options options, String footer, boolean autoUsage) { PrintWriter pw = new PrintWriter(System.out); printHelp(pw, width, cmdLineSyntax, header, options, defaultLeftPad, defaultDescPad, footer, autoUsage); pw.flush(); } /** * Print the help for options with the specified * command line syntax. * * @param pw the writer to which the help will be written * @param width the number of characters to be displayed on each line * @param cmdLineSyntax the syntax for this application * @param header the banner to display at the begining of the help * @param options the Options instance * @param leftPad the number of characters of padding to be prefixed * to each line * @param descPad the number of characters of padding to be prefixed * to each description line * @param footer the banner to display at the end of the help * * @throws IllegalStateException if there is no room to print a line */ public void printHelp(PrintWriter pw, int width, String cmdLineSyntax, String header, Options options, int leftPad, int descPad, String footer) { printHelp(pw, width, cmdLineSyntax, header, options, leftPad, descPad, footer, false); } /** * Print the help for options with the specified * command line syntax. * * @param pw the writer to which the help will be written * @param width the number of characters to be displayed on each line * @param cmdLineSyntax the syntax for this application * @param header the banner to display at the begining of the help * @param options the Options instance * @param leftPad the number of characters of padding to be prefixed * to each line * @param descPad the number of characters of padding to be prefixed * to each description line * @param footer the banner to display at the end of the help * @param autoUsage whether to print an automatically generated * usage statement * * @throws IllegalStateException if there is no room to print a line */ public void printHelp(PrintWriter pw, int width, String cmdLineSyntax, String header, Options options, int leftPad, int descPad, String footer, boolean autoUsage) { if ((cmdLineSyntax == null) || (cmdLineSyntax.length() == 0)) { throw new IllegalArgumentException("cmdLineSyntax not provided"); } if (autoUsage) { printUsage(pw, width, cmdLineSyntax, options); } else { printUsage(pw, width, cmdLineSyntax); } if ((header != null) && (header.trim().length() > 0)) { printWrapped(pw, width, header); } printOptions(pw, width, options, leftPad, descPad); if ((footer != null) && (footer.trim().length() > 0)) { printWrapped(pw, width, footer); } } /** *

Prints the usage statement for the specified application.

* * @param pw The PrintWriter to print the usage statement * @param width The number of characters to display per line * @param app The application name * @param options The command line Options * */ public void printUsage(PrintWriter pw, int width, String app, Options options) { // initialise the string buffer StringBuffer buff = new StringBuffer(defaultSyntaxPrefix).append(app).append(" "); // create a list for processed option groups final Collection processedGroups = new ArrayList(); // temp variable Option option; List optList = new ArrayList(options.getOptions()); Collections.sort(optList, getOptionComparator()); // iterate over the options for (Iterator i = optList.iterator(); i.hasNext();) { // get the next Option option = (Option) i.next(); // check if the option is part of an OptionGroup OptionGroup group = options.getOptionGroup(option); // if the option is part of a group if (group != null) { // and if the group has not already been processed if (!processedGroups.contains(group)) { // add the group to the processed list processedGroups.add(group); // add the usage clause appendOptionGroup(buff, group); } // otherwise the option was displayed in the group // previously so ignore it. } // if the Option is not part of an OptionGroup else { appendOption(buff, option, option.isRequired()); } if (i.hasNext()) { buff.append(" "); } } // call printWrapped printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString()); } /** * Appends the usage clause for an OptionGroup to a StringBuffer. * The clause is wrapped in square brackets if the group is required. * The display of the options is handled by appendOption * @param buff the StringBuffer to append to * @param group the group to append * @see #appendOption(StringBuffer,Option,boolean) */ private void appendOptionGroup(final StringBuffer buff, final OptionGroup group) { if (!group.isRequired()) { buff.append("["); } List optList = new ArrayList(group.getOptions()); Collections.sort(optList, getOptionComparator()); // for each option in the OptionGroup for (Iterator i = optList.iterator(); i.hasNext();) { // whether the option is required or not is handled at group level appendOption(buff, (Option) i.next(), true); if (i.hasNext()) { buff.append(" | "); } } if (!group.isRequired()) { buff.append("]"); } } /** * Appends the usage clause for an Option to a StringBuffer. * * @param buff the StringBuffer to append to * @param option the Option to append * @param required whether the Option is required or not */ private static void appendOption(final StringBuffer buff, final Option option, final boolean required) { if (!required) { buff.append("["); } if (option.getOpt() != null) { buff.append("-").append(option.getOpt()); } else { buff.append("--").append(option.getLongOpt()); } // if the Option has a value if (option.hasArg() && option.hasArgName()) { buff.append(" <").append(option.getArgName()).append(">"); } // if the Option is not a required option if (!required) { buff.append("]"); } } /** * Print the cmdLineSyntax to the specified writer, using the * specified width. * * @param pw The printWriter to write the help to * @param width The number of characters per line for the usage statement. * @param cmdLineSyntax The usage statement. */ public void printUsage(PrintWriter pw, int width, String cmdLineSyntax) { int argPos = cmdLineSyntax.indexOf(' ') + 1; printWrapped(pw, width, defaultSyntaxPrefix.length() + argPos, defaultSyntaxPrefix + cmdLineSyntax); } /** *

Print the help for the specified Options to the specified writer, * using the specified width, left padding and description padding.

* * @param pw The printWriter to write the help to * @param width The number of characters to display per line * @param options The command line Options * @param leftPad the number of characters of padding to be prefixed * to each line * @param descPad the number of characters of padding to be prefixed * to each description line */ public void printOptions(PrintWriter pw, int width, Options options, int leftPad, int descPad) { StringBuffer sb = new StringBuffer(); renderOptions(sb, width, options, leftPad, descPad); pw.println(sb.toString()); } /** * Print the specified text to the specified PrintWriter. * * @param pw The printWriter to write the help to * @param width The number of characters to display per line * @param text The text to be written to the PrintWriter */ public void printWrapped(PrintWriter pw, int width, String text) { printWrapped(pw, width, 0, text); } /** * Print the specified text to the specified PrintWriter. * * @param pw The printWriter to write the help to * @param width The number of characters to display per line * @param nextLineTabStop The position on the next line for the first tab. * @param text The text to be written to the PrintWriter */ public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text) { StringBuffer sb = new StringBuffer(text.length()); renderWrappedText(sb, width, nextLineTabStop, text); pw.println(sb.toString()); } // --------------------------------------------------------------- Protected /** * Render the specified Options and return the rendered Options * in a StringBuffer. * * @param sb The StringBuffer to place the rendered Options into. * @param width The number of characters to display per line * @param options The command line Options * @param leftPad the number of characters of padding to be prefixed * to each line * @param descPad the number of characters of padding to be prefixed * to each description line * * @return the StringBuffer with the rendered Options contents. */ protected StringBuffer renderOptions(StringBuffer sb, int width, Options options, int leftPad, int descPad) { final String lpad = createPadding(leftPad); final String dpad = createPadding(descPad); // first create list containing only -a,--aaa where // -a is opt and --aaa is long opt; in parallel look for // the longest opt string this list will be then used to // sort options ascending int max = 0; StringBuffer optBuf; List prefixList = new ArrayList(); List optList = options.helpOptions(); Collections.sort(optList, getOptionComparator()); for (Iterator i = optList.iterator(); i.hasNext();) { Option option = (Option) i.next(); optBuf = new StringBuffer(8); if (option.getOpt() == null) { optBuf.append(lpad).append(" " + defaultLongOptPrefix).append(option.getLongOpt()); } else { optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt()); if (option.hasLongOpt()) { optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt()); } } if (option.hasArg()) { if (option.hasArgName()) { optBuf.append(" <").append(option.getArgName()).append(">"); } else { optBuf.append(' '); } } prefixList.add(optBuf); max = (optBuf.length() > max) ? optBuf.length() : max; } int x = 0; for (Iterator i = optList.iterator(); i.hasNext();) { Option option = (Option) i.next(); optBuf = new StringBuffer(prefixList.get(x++).toString()); if (optBuf.length() < max) { optBuf.append(createPadding(max - optBuf.length())); } optBuf.append(dpad); int nextLineTabStop = max + descPad; if (option.getDescription() != null) { optBuf.append(option.getDescription()); } renderWrappedText(sb, width, nextLineTabStop, optBuf.toString()); if (i.hasNext()) { sb.append(defaultNewLine); } } return sb; } /** * Render the specified text and return the rendered Options * in a StringBuffer. * * @param sb The StringBuffer to place the rendered text into. * @param width The number of characters to display per line * @param nextLineTabStop The position on the next line for the first tab. * @param text The text to be rendered. * * @return the StringBuffer with the rendered Options contents. */ protected StringBuffer renderWrappedText(StringBuffer sb, int width, int nextLineTabStop, String text) { int pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(rtrim(text)); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); if (nextLineTabStop >= width) { // stops infinite loop happening nextLineTabStop = 1; } // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { pos = width; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } } /** * Finds the next text wrap position after startPos for the * text in text with the column width width. * The wrap point is the last postion before startPos+width having a * whitespace character (space, \n, \r). * * @param text The text being searched for the wrap position * @param width width of the wrapped text * @param startPos position from which to start the lookup whitespace * character * @return postion on which the text must be wrapped or -1 if the wrap * position is at the end of the text */ protected int findWrapPos(String text, int width, int startPos) { int pos = -1; // the line ends before the max wrap pos or a new line char found if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width)) { return pos + 1; } else if (startPos + width >= text.length()) { return -1; } // look for the last whitespace character before startPos+width pos = startPos + width; char c; while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { --pos; } // if we found it - just return if (pos > startPos) { return pos; } // must look for the first whitespace chearacter after startPos // + width pos = startPos + width; while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { ++pos; } return (pos == text.length()) ? (-1) : pos; } /** * Return a String of padding of length len. * * @param len The length of the String of padding to create. * * @return The String of padding */ protected String createPadding(int len) { StringBuffer sb = new StringBuffer(len); for (int i = 0; i < len; ++i) { sb.append(' '); } return sb.toString(); } /** * Remove the trailing whitespace from the specified String. * * @param s The String to remove the trailing padding from. * * @return The String of without the trailing padding */ protected String rtrim(String s) { if ((s == null) || (s.length() == 0)) { return s; } int pos = s.length(); while ((pos > 0) && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); } // ------------------------------------------------------ Package protected // ---------------------------------------------------------------- Private // ---------------------------------------------------------- Inner classes /** * This class implements the Comparator interface * for comparing Options. */ private static class OptionComparator implements Comparator { /** * Compares its two arguments for order. Returns a negative * integer, zero, or a positive integer as the first argument * is less than, equal to, or greater than the second. * * @param o1 The first Option to be compared. * @param o2 The second Option to be compared. * @return a negative integer, zero, or a positive integer as * the first argument is less than, equal to, or greater than the * second. */ public int compare(Object o1, Object o2) { Option opt1 = (Option) o1; Option opt2 = (Option) o2; return opt1.getKey().compareToIgnoreCase(opt2.getKey()); } } } commons-cli-1.2-src/src/java/org/apache/commons/cli/MissingArgumentException.java100644 0 0 4021 11157377776 25332 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * Thrown when an option requiring an argument * is not provided with an argument. * * @author John Keyes (john at integralsource.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class MissingArgumentException extends ParseException { /** The option requiring additional arguments */ private Option option; /** * Construct a new MissingArgumentException * with the specified detail message. * * @param message the detail message */ public MissingArgumentException(String message) { super(message); } /** * Construct a new MissingArgumentException * with the specified detail message. * * @param option the option requiring an argument * @since 1.2 */ public MissingArgumentException(Option option) { this("Missing argument for option: " + option.getKey()); this.option = option; } /** * Return the option requiring an argument that wasn't provided * on the command line. * * @return the related option * @since 1.2 */ public Option getOption() { return option; } } commons-cli-1.2-src/src/java/org/apache/commons/cli/MissingOptionException.java100644 0 0 5251 11157377776 25026 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.List; import java.util.Iterator; /** * Thrown when a required option has not been provided. * * @author John Keyes ( john at integralsource.com ) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class MissingOptionException extends ParseException { /** The list of missing options */ private List missingOptions; /** * Construct a new MissingSelectedException * with the specified detail message. * * @param message the detail message */ public MissingOptionException(String message) { super(message); } /** * Constructs a new MissingSelectedException with the * specified list of missing options. * * @param missingOptions the list of missing options * @since 1.2 */ public MissingOptionException(List missingOptions) { this(createMessage(missingOptions)); this.missingOptions = missingOptions; } /** * Return the list of options (as strings) missing in the command line parsed. * * @return the missing options * @since 1.2 */ public List getMissingOptions() { return missingOptions; } /** * Build the exception message from the specified list of options. * * @param missingOptions * @since 1.2 */ private static String createMessage(List missingOptions) { StringBuffer buff = new StringBuffer("Missing required option"); buff.append(missingOptions.size() == 1 ? "" : "s"); buff.append(": "); Iterator it = missingOptions.iterator(); while (it.hasNext()) { buff.append(it.next()); if (it.hasNext()) { buff.append(", "); } } return buff.toString(); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/Option.java100644 0 0 42742 11157377776 21643 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /**

Describes a single command-line option. It maintains * information regarding the short-name of the option, the long-name, * if any exists, a flag indicating if an argument is required for * this option, and a self-documenting description of the option.

* *

An Option is not created independantly, but is create through * an instance of {@link Options}.

* * @see org.apache.commons.cli.Options * @see org.apache.commons.cli.CommandLine * * @author bob mcwhirter (bob @ werken.com) * @author James Strachan * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class Option implements Cloneable, Serializable { private static final long serialVersionUID = 1L; /** constant that specifies the number of argument values has not been specified */ public static final int UNINITIALIZED = -1; /** constant that specifies the number of argument values is infinite */ public static final int UNLIMITED_VALUES = -2; /** the name of the option */ private String opt; /** the long representation of the option */ private String longOpt; /** the name of the argument for this option */ private String argName = "arg"; /** description of the option */ private String description; /** specifies whether this option is required to be present */ private boolean required; /** specifies whether the argument value of this Option is optional */ private boolean optionalArg; /** the number of argument values this option can have */ private int numberOfArgs = UNINITIALIZED; /** the type of this Option */ private Object type; /** the list of argument values **/ private List values = new ArrayList(); /** the character that is the value separator */ private char valuesep; /** * Creates an Option using the specified parameters. * * @param opt short representation of the option * @param description describes the function of the option * * @throws IllegalArgumentException if there are any non valid * Option characters in opt. */ public Option(String opt, String description) throws IllegalArgumentException { this(opt, null, false, description); } /** * Creates an Option using the specified parameters. * * @param opt short representation of the option * @param hasArg specifies whether the Option takes an argument or not * @param description describes the function of the option * * @throws IllegalArgumentException if there are any non valid * Option characters in opt. */ public Option(String opt, boolean hasArg, String description) throws IllegalArgumentException { this(opt, null, hasArg, description); } /** * Creates an Option using the specified parameters. * * @param opt short representation of the option * @param longOpt the long representation of the option * @param hasArg specifies whether the Option takes an argument or not * @param description describes the function of the option * * @throws IllegalArgumentException if there are any non valid * Option characters in opt. */ public Option(String opt, String longOpt, boolean hasArg, String description) throws IllegalArgumentException { // ensure that the option is valid OptionValidator.validateOption(opt); this.opt = opt; this.longOpt = longOpt; // if hasArg is set then the number of arguments is 1 if (hasArg) { this.numberOfArgs = 1; } this.description = description; } /** * Returns the id of this Option. This is only set when the * Option shortOpt is a single character. This is used for switch * statements. * * @return the id of this Option */ public int getId() { return getKey().charAt(0); } /** * Returns the 'unique' Option identifier. * * @return the 'unique' Option identifier */ String getKey() { // if 'opt' is null, then it is a 'long' option if (opt == null) { return longOpt; } return opt; } /** * Retrieve the name of this Option. * * It is this String which can be used with * {@link CommandLine#hasOption(String opt)} and * {@link CommandLine#getOptionValue(String opt)} to check * for existence and argument. * * @return The name of this option */ public String getOpt() { return opt; } /** * Retrieve the type of this Option. * * @return The type of this option */ public Object getType() { return type; } /** * Sets the type of this Option. * * @param type the type of this Option */ public void setType(Object type) { this.type = type; } /** * Retrieve the long name of this Option. * * @return Long name of this option, or null, if there is no long name */ public String getLongOpt() { return longOpt; } /** * Sets the long name of this Option. * * @param longOpt the long name of this Option */ public void setLongOpt(String longOpt) { this.longOpt = longOpt; } /** * Sets whether this Option can have an optional argument. * * @param optionalArg specifies whether the Option can have * an optional argument. */ public void setOptionalArg(boolean optionalArg) { this.optionalArg = optionalArg; } /** * @return whether this Option can have an optional argument */ public boolean hasOptionalArg() { return optionalArg; } /** * Query to see if this Option has a long name * * @return boolean flag indicating existence of a long name */ public boolean hasLongOpt() { return longOpt != null; } /** * Query to see if this Option requires an argument * * @return boolean flag indicating if an argument is required */ public boolean hasArg() { return numberOfArgs > 0 || numberOfArgs == UNLIMITED_VALUES; } /** * Retrieve the self-documenting description of this Option * * @return The string description of this option */ public String getDescription() { return description; } /** * Sets the self-documenting description of this Option * * @param description The description of this option * @since 1.1 */ public void setDescription(String description) { this.description = description; } /** * Query to see if this Option requires an argument * * @return boolean flag indicating if an argument is required */ public boolean isRequired() { return required; } /** * Sets whether this Option is mandatory. * * @param required specifies whether this Option is mandatory */ public void setRequired(boolean required) { this.required = required; } /** * Sets the display name for the argument value. * * @param argName the display name for the argument value. */ public void setArgName(String argName) { this.argName = argName; } /** * Gets the display name for the argument value. * * @return the display name for the argument value. */ public String getArgName() { return argName; } /** * Returns whether the display name for the argument value * has been set. * * @return if the display name for the argument value has been * set. */ public boolean hasArgName() { return argName != null && argName.length() > 0; } /** * Query to see if this Option can take many values. * * @return boolean flag indicating if multiple values are allowed */ public boolean hasArgs() { return numberOfArgs > 1 || numberOfArgs == UNLIMITED_VALUES; } /** * Sets the number of argument values this Option can take. * * @param num the number of argument values */ public void setArgs(int num) { this.numberOfArgs = num; } /** * Sets the value separator. For example if the argument value * was a Java property, the value separator would be '='. * * @param sep The value separator. */ public void setValueSeparator(char sep) { this.valuesep = sep; } /** * Returns the value separator character. * * @return the value separator character. */ public char getValueSeparator() { return valuesep; } /** * Return whether this Option has specified a value separator. * * @return whether this Option has specified a value separator. * @since 1.1 */ public boolean hasValueSeparator() { return valuesep > 0; } /** * Returns the number of argument values this Option can take. * * @return num the number of argument values */ public int getArgs() { return numberOfArgs; } /** * Adds the specified value to this Option. * * @param value is a/the value of this Option */ void addValueForProcessing(String value) { switch (numberOfArgs) { case UNINITIALIZED: throw new RuntimeException("NO_ARGS_ALLOWED"); default: processValue(value); } } /** * Processes the value. If this Option has a value separator * the value will have to be parsed into individual tokens. When * n-1 tokens have been processed and there are more value separators * in the value, parsing is ceased and the remaining characters are * added as a single token. * * @param value The String to be processed. * * @since 1.0.1 */ private void processValue(String value) { // this Option has a separator character if (hasValueSeparator()) { // get the separator character char sep = getValueSeparator(); // store the index for the value separator int index = value.indexOf(sep); // while there are more value separators while (index != -1) { // next value to be added if (values.size() == (numberOfArgs - 1)) { break; } // store add(value.substring(0, index)); // parse value = value.substring(index + 1); // get new index index = value.indexOf(sep); } } // store the actual value or the last value that has been parsed add(value); } /** * Add the value to this Option. If the number of arguments * is greater than zero and there is enough space in the list then * add the value. Otherwise, throw a runtime exception. * * @param value The value to be added to this Option * * @since 1.0.1 */ private void add(String value) { if ((numberOfArgs > 0) && (values.size() > (numberOfArgs - 1))) { throw new RuntimeException("Cannot add value, list full."); } // store value values.add(value); } /** * Returns the specified value of this Option or * null if there is no value. * * @return the value/first value of this Option or * null if there is no value. */ public String getValue() { return hasNoValues() ? null : (String) values.get(0); } /** * Returns the specified value of this Option or * null if there is no value. * * @param index The index of the value to be returned. * * @return the specified value of this Option or * null if there is no value. * * @throws IndexOutOfBoundsException if index is less than 1 * or greater than the number of the values for this Option. */ public String getValue(int index) throws IndexOutOfBoundsException { return hasNoValues() ? null : (String) values.get(index); } /** * Returns the value/first value of this Option or the * defaultValue if there is no value. * * @param defaultValue The value to be returned if ther * is no value. * * @return the value/first value of this Option or the * defaultValue if there are no values. */ public String getValue(String defaultValue) { String value = getValue(); return (value != null) ? value : defaultValue; } /** * Return the values of this Option as a String array * or null if there are no values * * @return the values of this Option as a String array * or null if there are no values */ public String[] getValues() { return hasNoValues() ? null : (String[]) values.toArray(new String[values.size()]); } /** * @return the values of this Option as a List * or null if there are no values */ public List getValuesList() { return values; } /** * Dump state, suitable for debugging. * * @return Stringified form of this object */ public String toString() { StringBuffer buf = new StringBuffer().append("[ option: "); buf.append(opt); if (longOpt != null) { buf.append(" ").append(longOpt); } buf.append(" "); if (hasArgs()) { buf.append("[ARG...]"); } else if (hasArg()) { buf.append(" [ARG]"); } buf.append(" :: ").append(description); if (type != null) { buf.append(" :: ").append(type); } buf.append(" ]"); return buf.toString(); } /** * Returns whether this Option has any values. * * @return whether this Option has any values. */ private boolean hasNoValues() { return values.isEmpty(); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Option option = (Option) o; if (opt != null ? !opt.equals(option.opt) : option.opt != null) { return false; } if (longOpt != null ? !longOpt.equals(option.longOpt) : option.longOpt != null) { return false; } return true; } public int hashCode() { int result; result = (opt != null ? opt.hashCode() : 0); result = 31 * result + (longOpt != null ? longOpt.hashCode() : 0); return result; } /** * A rather odd clone method - due to incorrect code in 1.0 it is public * and in 1.1 rather than throwing a CloneNotSupportedException it throws * a RuntimeException so as to maintain backwards compat at the API level. * * After calling this method, it is very likely you will want to call * clearValues(). * * @throws RuntimeException */ public Object clone() { try { Option option = (Option) super.clone(); option.values = new ArrayList(values); return option; } catch (CloneNotSupportedException cnse) { throw new RuntimeException("A CloneNotSupportedException was thrown: " + cnse.getMessage()); } } /** * Clear the Option values. After a parse is complete, these are left with * data in them and they need clearing if another parse is done. * * See: CLI-71 */ void clearValues() { values.clear(); } /** * This method is not intended to be used. It was a piece of internal * API that was made public in 1.0. It currently throws an UnsupportedOperationException. * @deprecated * @throws UnsupportedOperationException */ public boolean addValue(String value) { throw new UnsupportedOperationException("The addValue method is not intended for client use. " + "Subclasses should use the addValueForProcessing method instead. "); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/OptionBuilder.java100644 0 0 23563 11157377776 23152 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * OptionBuilder allows the user to create Options using descriptive methods. * *

Details on the Builder pattern can be found at * * http://c2.com/cgi-bin/wiki?BuilderPattern.

* * @author John Keyes (john at integralsource.com) * @version $Revision: 754830 $, $Date: 2009-03-16 00:26:44 -0700 (Mon, 16 Mar 2009) $ * @since 1.0 */ public final class OptionBuilder { /** long option */ private static String longopt; /** option description */ private static String description; /** argument name */ private static String argName; /** is required? */ private static boolean required; /** the number of arguments */ private static int numberOfArgs = Option.UNINITIALIZED; /** option type */ private static Object type; /** option can have an optional argument value */ private static boolean optionalArg; /** value separator for argument value */ private static char valuesep; /** option builder instance */ private static OptionBuilder instance = new OptionBuilder(); /** * private constructor to prevent instances being created */ private OptionBuilder() { // hide the constructor } /** * Resets the member variables to their default values. */ private static void reset() { description = null; argName = "arg"; longopt = null; type = null; required = false; numberOfArgs = Option.UNINITIALIZED; // PMM 9/6/02 - these were missing optionalArg = false; valuesep = (char) 0; } /** * The next Option created will have the following long option value. * * @param newLongopt the long option value * @return the OptionBuilder instance */ public static OptionBuilder withLongOpt(String newLongopt) { OptionBuilder.longopt = newLongopt; return instance; } /** * The next Option created will require an argument value. * * @return the OptionBuilder instance */ public static OptionBuilder hasArg() { OptionBuilder.numberOfArgs = 1; return instance; } /** * The next Option created will require an argument value if * hasArg is true. * * @param hasArg if true then the Option has an argument value * @return the OptionBuilder instance */ public static OptionBuilder hasArg(boolean hasArg) { OptionBuilder.numberOfArgs = hasArg ? 1 : Option.UNINITIALIZED; return instance; } /** * The next Option created will have the specified argument value name. * * @param name the name for the argument value * @return the OptionBuilder instance */ public static OptionBuilder withArgName(String name) { OptionBuilder.argName = name; return instance; } /** * The next Option created will be required. * * @return the OptionBuilder instance */ public static OptionBuilder isRequired() { OptionBuilder.required = true; return instance; } /** * The next Option created uses sep as a means to * separate argument values. * * Example: *
     * Option opt = OptionBuilder.withValueSeparator(':')
     *                           .create('D');
     *
     * CommandLine line = parser.parse(args);
     * String propertyName = opt.getValue(0);
     * String propertyValue = opt.getValue(1);
     * 
* * @param sep The value separator to be used for the argument values. * * @return the OptionBuilder instance */ public static OptionBuilder withValueSeparator(char sep) { OptionBuilder.valuesep = sep; return instance; } /** * The next Option created uses '=' as a means to * separate argument values. * * Example: *
     * Option opt = OptionBuilder.withValueSeparator()
     *                           .create('D');
     *
     * CommandLine line = parser.parse(args);
     * String propertyName = opt.getValue(0);
     * String propertyValue = opt.getValue(1);
     * 
* * @return the OptionBuilder instance */ public static OptionBuilder withValueSeparator() { OptionBuilder.valuesep = '='; return instance; } /** * The next Option created will be required if required * is true. * * @param newRequired if true then the Option is required * @return the OptionBuilder instance */ public static OptionBuilder isRequired(boolean newRequired) { OptionBuilder.required = newRequired; return instance; } /** * The next Option created can have unlimited argument values. * * @return the OptionBuilder instance */ public static OptionBuilder hasArgs() { OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES; return instance; } /** * The next Option created can have num argument values. * * @param num the number of args that the option can have * @return the OptionBuilder instance */ public static OptionBuilder hasArgs(int num) { OptionBuilder.numberOfArgs = num; return instance; } /** * The next Option can have an optional argument. * * @return the OptionBuilder instance */ public static OptionBuilder hasOptionalArg() { OptionBuilder.numberOfArgs = 1; OptionBuilder.optionalArg = true; return instance; } /** * The next Option can have an unlimited number of optional arguments. * * @return the OptionBuilder instance */ public static OptionBuilder hasOptionalArgs() { OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES; OptionBuilder.optionalArg = true; return instance; } /** * The next Option can have the specified number of optional arguments. * * @param numArgs - the maximum number of optional arguments * the next Option created can have. * @return the OptionBuilder instance */ public static OptionBuilder hasOptionalArgs(int numArgs) { OptionBuilder.numberOfArgs = numArgs; OptionBuilder.optionalArg = true; return instance; } /** * The next Option created will have a value that will be an instance * of type. * * @param newType the type of the Options argument value * @return the OptionBuilder instance */ public static OptionBuilder withType(Object newType) { OptionBuilder.type = newType; return instance; } /** * The next Option created will have the specified description * * @param newDescription a description of the Option's purpose * @return the OptionBuilder instance */ public static OptionBuilder withDescription(String newDescription) { OptionBuilder.description = newDescription; return instance; } /** * Create an Option using the current settings and with * the specified Option char. * * @param opt the character representation of the Option * @return the Option instance * @throws IllegalArgumentException if opt is not * a valid character. See Option. */ public static Option create(char opt) throws IllegalArgumentException { return create(String.valueOf(opt)); } /** * Create an Option using the current settings * * @return the Option instance * @throws IllegalArgumentException if longOpt has not been set. */ public static Option create() throws IllegalArgumentException { if (longopt == null) { OptionBuilder.reset(); throw new IllegalArgumentException("must specify longopt"); } return create(null); } /** * Create an Option using the current settings and with * the specified Option char. * * @param opt the java.lang.String representation * of the Option * @return the Option instance * @throws IllegalArgumentException if opt is not * a valid character. See Option. */ public static Option create(String opt) throws IllegalArgumentException { Option option = null; try { // create the option option = new Option(opt, description); // set the option properties option.setLongOpt(longopt); option.setRequired(required); option.setOptionalArg(optionalArg); option.setArgs(numberOfArgs); option.setType(type); option.setValueSeparator(valuesep); option.setArgName(argName); } finally { // reset the OptionBuilder properties OptionBuilder.reset(); } // return the Option instance return option; } } commons-cli-1.2-src/src/java/org/apache/commons/cli/OptionGroup.java100644 0 0 10566 11157377776 22657 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * A group of mutually exclusive options. * * @author John Keyes ( john at integralsource.com ) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class OptionGroup implements Serializable { private static final long serialVersionUID = 1L; /** hold the options */ private Map optionMap = new HashMap(); /** the name of the selected option */ private String selected; /** specified whether this group is required */ private boolean required; /** * Add the specified Option to this group. * * @param option the option to add to this group * @return this option group with the option added */ public OptionGroup addOption(Option option) { // key - option name // value - the option optionMap.put(option.getKey(), option); return this; } /** * @return the names of the options in this group as a * Collection */ public Collection getNames() { // the key set is the collection of names return optionMap.keySet(); } /** * @return the options in this group as a Collection */ public Collection getOptions() { // the values are the collection of options return optionMap.values(); } /** * Set the selected option of this group to name. * * @param option the option that is selected * @throws AlreadySelectedException if an option from this group has * already been selected. */ public void setSelected(Option option) throws AlreadySelectedException { // if no option has already been selected or the // same option is being reselected then set the // selected member variable if (selected == null || selected.equals(option.getOpt())) { selected = option.getOpt(); } else { throw new AlreadySelectedException(this, option); } } /** * @return the selected option name */ public String getSelected() { return selected; } /** * @param required specifies if this group is required */ public void setRequired(boolean required) { this.required = required; } /** * Returns whether this option group is required. * * @return whether this option group is required */ public boolean isRequired() { return required; } /** * Returns the stringified version of this OptionGroup. * * @return the stringified representation of this group */ public String toString() { StringBuffer buff = new StringBuffer(); Iterator iter = getOptions().iterator(); buff.append("["); while (iter.hasNext()) { Option option = (Option) iter.next(); if (option.getOpt() != null) { buff.append("-"); buff.append(option.getOpt()); } else { buff.append("--"); buff.append(option.getLongOpt()); } buff.append(" "); buff.append(option.getDescription()); if (iter.hasNext()) { buff.append(", "); } } buff.append("]"); return buff.toString(); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/Options.java100644 0 0 16513 11157377776 22023 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; /** *

Main entry-point into the library.

* *

Options represents a collection of {@link Option} objects, which * describe the possible options for a command-line.

* *

It may flexibly parse long and short options, with or without * values. Additionally, it may parse only a portion of a commandline, * allowing for flexible multi-stage parsing.

* * @see org.apache.commons.cli.CommandLine * * @author bob mcwhirter (bob @ werken.com) * @author James Strachan * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class Options implements Serializable { private static final long serialVersionUID = 1L; /** a map of the options with the character key */ private Map shortOpts = new HashMap(); /** a map of the options with the long key */ private Map longOpts = new HashMap(); /** a map of the required options */ private List requiredOpts = new ArrayList(); /** a map of the option groups */ private Map optionGroups = new HashMap(); /** * Add the specified option group. * * @param group the OptionGroup that is to be added * @return the resulting Options instance */ public Options addOptionGroup(OptionGroup group) { Iterator options = group.getOptions().iterator(); if (group.isRequired()) { requiredOpts.add(group); } while (options.hasNext()) { Option option = (Option) options.next(); // an Option cannot be required if it is in an // OptionGroup, either the group is required or // nothing is required option.setRequired(false); addOption(option); optionGroups.put(option.getKey(), group); } return this; } /** * Lists the OptionGroups that are members of this Options instance. * * @return a Collection of OptionGroup instances. */ Collection getOptionGroups() { return new HashSet(optionGroups.values()); } /** * Add an option that only contains a short-name. * It may be specified as requiring an argument. * * @param opt Short single-character name of the option. * @param hasArg flag signally if an argument is required after this option * @param description Self-documenting description * @return the resulting Options instance */ public Options addOption(String opt, boolean hasArg, String description) { addOption(opt, null, hasArg, description); return this; } /** * Add an option that contains a short-name and a long-name. * It may be specified as requiring an argument. * * @param opt Short single-character name of the option. * @param longOpt Long multi-character name of the option. * @param hasArg flag signally if an argument is required after this option * @param description Self-documenting description * @return the resulting Options instance */ public Options addOption(String opt, String longOpt, boolean hasArg, String description) { addOption(new Option(opt, longOpt, hasArg, description)); return this; } /** * Adds an option instance * * @param opt the option that is to be added * @return the resulting Options instance */ public Options addOption(Option opt) { String key = opt.getKey(); // add it to the long option list if (opt.hasLongOpt()) { longOpts.put(opt.getLongOpt(), opt); } // if the option is required add it to the required list if (opt.isRequired()) { if (requiredOpts.contains(key)) { requiredOpts.remove(requiredOpts.indexOf(key)); } requiredOpts.add(key); } shortOpts.put(key, opt); return this; } /** * Retrieve a read-only list of options in this set * * @return read-only Collection of {@link Option} objects in this descriptor */ public Collection getOptions() { return Collections.unmodifiableCollection(helpOptions()); } /** * Returns the Options for use by the HelpFormatter. * * @return the List of Options */ List helpOptions() { return new ArrayList(shortOpts.values()); } /** * Returns the required options. * * @return List of required options */ public List getRequiredOptions() { return requiredOpts; } /** * Retrieve the {@link Option} matching the long or short name specified. * The leading hyphens in the name are ignored (up to 2). * * @param opt short or long name of the {@link Option} * @return the option represented by opt */ public Option getOption(String opt) { opt = Util.stripLeadingHyphens(opt); if (shortOpts.containsKey(opt)) { return (Option) shortOpts.get(opt); } return (Option) longOpts.get(opt); } /** * Returns whether the named {@link Option} is a member of this {@link Options}. * * @param opt short or long name of the {@link Option} * @return true if the named {@link Option} is a member * of this {@link Options} */ public boolean hasOption(String opt) { opt = Util.stripLeadingHyphens(opt); return shortOpts.containsKey(opt) || longOpts.containsKey(opt); } /** * Returns the OptionGroup the opt belongs to. * @param opt the option whose OptionGroup is being queried. * * @return the OptionGroup if opt is part * of an OptionGroup, otherwise return null */ public OptionGroup getOptionGroup(Option opt) { return (OptionGroup) optionGroups.get(opt.getKey()); } /** * Dump state, suitable for debugging. * * @return Stringified form of this object */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("[ Options: [ short "); buf.append(shortOpts.toString()); buf.append(" ] [ long "); buf.append(longOpts); buf.append(" ]"); return buf.toString(); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/OptionValidator.java100644 0 0 6124 11157377776 23463 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * Validates an Option string. * * @author John Keyes ( john at integralsource.com ) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ * @since 1.1 */ class OptionValidator { /** * Validates whether opt is a permissable Option * shortOpt. The rules that specify if the opt * is valid are: * *

    *
  • opt is not NULL
  • *
  • a single character opt that is either * ' '(special case), '?', '@' or a letter
  • *
  • a multi character opt that only contains * letters.
  • *
* * @param opt The option string to validate * @throws IllegalArgumentException if the Option is not valid. */ static void validateOption(String opt) throws IllegalArgumentException { // check that opt is not NULL if (opt == null) { return; } // handle the single character opt else if (opt.length() == 1) { char ch = opt.charAt(0); if (!isValidOpt(ch)) { throw new IllegalArgumentException("illegal option value '" + ch + "'"); } } // handle the multi character opt else { char[] chars = opt.toCharArray(); for (int i = 0; i < chars.length; i++) { if (!isValidChar(chars[i])) { throw new IllegalArgumentException("opt contains illegal character value '" + chars[i] + "'"); } } } } /** * Returns whether the specified character is a valid Option. * * @param c the option to validate * @return true if c is a letter, ' ', '?' or '@', * otherwise false. */ private static boolean isValidOpt(char c) { return isValidChar(c) || c == ' ' || c == '?' || c == '@'; } /** * Returns whether the specified character is a valid character. * * @param c the character to validate * @return true if c is a letter. */ private static boolean isValidChar(char c) { return Character.isJavaIdentifierPart(c); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/overview.html100644 0 0 3255 11157377776 22240 0ustar 0 0

Commons CLI -- version 1.2

The commons-cli package aides in parsing command-line arguments.

Allow command-line arguments to be parsed against a descriptor of valid options (long and short), potentially with arguments.

command-line arguments may be of the typical String[] form, but also may be a java.util.List. Indexes allow for parsing only a portion of the command-line. Also, functionality for parsing the command-line in phases is built in, allowing for 'cvs-style' command-lines, where some global options are specified before a 'command' argument, and command-specific options are specified after the command argument:

        myApp -p <port> command -p <printer>
    

The homepage for the project is Apache Commons/ commons-cli-1.2-src/src/java/org/apache/commons/cli/package.html100644 0 0 1442 11157377776 21761 0ustar 0 0 Commons CLI 1.2 commons-cli-1.2-src/src/java/org/apache/commons/cli/ParseException.java100644 0 0 2460 11157377776 23275 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * Base for Exceptions thrown during parsing of a command-line. * * @author bob mcwhirter (bob @ werken.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class ParseException extends Exception { /** * Construct a new ParseException * with the specified detail message. * * @param message the detail message */ public ParseException(String message) { super(message); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/Parser.java100644 0 0 30325 11157377776 21621 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Properties; /** * Parser creates {@link CommandLine}s. * * @author John Keyes (john at integralsource.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public abstract class Parser implements CommandLineParser { /** commandline instance */ protected CommandLine cmd; /** current Options */ private Options options; /** list of required options strings */ private List requiredOptions; protected void setOptions(final Options options) { this.options = options; this.requiredOptions = new ArrayList(options.getRequiredOptions()); } protected Options getOptions() { return options; } protected List getRequiredOptions() { return requiredOptions; } /** * Subclasses must implement this method to reduce * the arguments that have been passed to the parse method. * * @param opts The Options to parse the arguments by. * @param arguments The arguments that have to be flattened. * @param stopAtNonOption specifies whether to stop * flattening when a non option has been encountered * @return a String array of the flattened arguments */ protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption); /** * Parses the specified arguments based * on the specifed {@link Options}. * * @param options the Options * @param arguments the arguments * @return the CommandLine * @throws ParseException if an error occurs when parsing the * arguments. */ public CommandLine parse(Options options, String[] arguments) throws ParseException { return parse(options, arguments, null, false); } /** * Parse the arguments according to the specified options and properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered * while parsing the command line tokens. * * @since 1.1 */ public CommandLine parse(Options options, String[] arguments, Properties properties) throws ParseException { return parse(options, arguments, properties, false); } /** * Parses the specified arguments * based on the specifed {@link Options}. * * @param options the Options * @param arguments the arguments * @param stopAtNonOption specifies whether to stop interpreting the * arguments when a non option has been encountered * and to add them to the CommandLines args list. * @return the CommandLine * @throws ParseException if an error occurs when parsing the arguments. */ public CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException { return parse(options, arguments, null, stopAtNonOption); } /** * Parse the arguments according to the specified options and * properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @param stopAtNonOption stop parsing the arguments when the first * non option is encountered. * * @return the list of atomic option and value tokens * * @throws ParseException if there are any problems encountered * while parsing the command line tokens. * * @since 1.1 */ public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption) throws ParseException { // clear out the data in options in case it's been used before (CLI-71) for (Iterator it = options.helpOptions().iterator(); it.hasNext();) { Option opt = (Option) it.next(); opt.clearValues(); } // initialise members setOptions(options); cmd = new CommandLine(); boolean eatTheRest = false; if (arguments == null) { arguments = new String[0]; } List tokenList = Arrays.asList(flatten(getOptions(), arguments, stopAtNonOption)); ListIterator iterator = tokenList.listIterator(); // process each flattened token while (iterator.hasNext()) { String t = (String) iterator.next(); // the value is the double-dash if ("--".equals(t)) { eatTheRest = true; } // the value is a single dash else if ("-".equals(t)) { if (stopAtNonOption) { eatTheRest = true; } else { cmd.addArg(t); } } // the value is an option else if (t.startsWith("-")) { if (stopAtNonOption && !getOptions().hasOption(t)) { eatTheRest = true; cmd.addArg(t); } else { processOption(t, iterator); } } // the value is an argument else { cmd.addArg(t); if (stopAtNonOption) { eatTheRest = true; } } // eat the remaining tokens if (eatTheRest) { while (iterator.hasNext()) { String str = (String) iterator.next(); // ensure only one double-dash is added if (!"--".equals(str)) { cmd.addArg(str); } } } } processProperties(properties); checkRequiredOptions(); return cmd; } /** * Sets the values of Options using the values in properties. * * @param properties The value properties to be processed. */ protected void processProperties(Properties properties) { if (properties == null) { return; } for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { String option = e.nextElement().toString(); if (!cmd.hasOption(option)) { Option opt = getOptions().getOption(option); // get the value from the properties instance String value = properties.getProperty(option); if (opt.hasArg()) { if (opt.getValues() == null || opt.getValues().length == 0) { try { opt.addValueForProcessing(value); } catch (RuntimeException exp) { // if we cannot add the value don't worry about it } } } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) { // if the value is not yes, true or 1 then don't add the // option to the CommandLine break; } cmd.addOption(opt); } } } /** * Throws a {@link MissingOptionException} if all of the required options * are not present. * * @throws MissingOptionException if any of the required Options * are not present. */ protected void checkRequiredOptions() throws MissingOptionException { // if there are required options that have not been processsed if (!getRequiredOptions().isEmpty()) { throw new MissingOptionException(getRequiredOptions()); } } /** *

Process the argument values for the specified Option * opt using the values retrieved from the * specified iterator iter. * * @param opt The current Option * @param iter The iterator over the flattened command line * Options. * * @throws ParseException if an argument value is required * and it is has not been found. */ public void processArgs(Option opt, ListIterator iter) throws ParseException { // loop until an option is found while (iter.hasNext()) { String str = (String) iter.next(); // found an Option, not an argument if (getOptions().hasOption(str) && str.startsWith("-")) { iter.previous(); break; } // found a value try { opt.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(str)); } catch (RuntimeException exp) { iter.previous(); break; } } if (opt.getValues() == null && !opt.hasOptionalArg()) { throw new MissingArgumentException(opt); } } /** * Process the Option specified by arg using the values * retrieved from the specfied iterator iter. * * @param arg The String value representing an Option * @param iter The iterator over the flattened command line arguments. * * @throws ParseException if arg does not represent an Option */ protected void processOption(String arg, ListIterator iter) throws ParseException { boolean hasOption = getOptions().hasOption(arg); // if there is no option throw an UnrecognisedOptionException if (!hasOption) { throw new UnrecognizedOptionException("Unrecognized option: " + arg, arg); } // get the option represented by arg Option opt = (Option) getOptions().getOption(arg).clone(); // if the option is a required option remove the option from // the requiredOptions list if (opt.isRequired()) { getRequiredOptions().remove(opt.getKey()); } // if the option is in an OptionGroup make that option the selected // option of the group if (getOptions().getOptionGroup(opt) != null) { OptionGroup group = getOptions().getOptionGroup(opt); if (group.isRequired()) { getRequiredOptions().remove(group); } group.setSelected(opt); } // if the option takes an argument value if (opt.hasArg()) { processArgs(opt, iter); } // set the option on the command line cmd.addOption(opt); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/PatternOptionBuilder.java100644 0 0 14060 11157377776 24500 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.util.Date; /** *

* Allows Options to be created from a single String. * The pattern contains various single character flags and via * an optional punctuation character, their expected type. *

* * * * * * * * * *
a-a flag
b@-b [classname]
c>-c [filename]
d+-d [classname] (creates object via empty contructor)
e%-e [number] (creates Double/Long instance depeding on existing of a '.')
f/-f [url]
g:-g [string]
* *

* For example, the following allows command line flags of '-v -p string-value -f /dir/file'. * The exclamation mark precede a mandatory option. *

* Options options = PatternOptionBuilder.parsePattern("vp:!f/"); * *

* TODO These need to break out to OptionType and also * to be pluggable. *

* * @version $Revision: 734339 $, $Date: 2009-01-13 21:56:47 -0800 (Tue, 13 Jan 2009) $ */ public class PatternOptionBuilder { /** String class */ public static final Class STRING_VALUE = String.class; /** Object class */ public static final Class OBJECT_VALUE = Object.class; /** Number class */ public static final Class NUMBER_VALUE = Number.class; /** Date class */ public static final Class DATE_VALUE = Date.class; /** Class class */ public static final Class CLASS_VALUE = Class.class; /// can we do this one?? // is meant to check that the file exists, else it errors. // ie) it's for reading not writing. /** FileInputStream class */ public static final Class EXISTING_FILE_VALUE = FileInputStream.class; /** File class */ public static final Class FILE_VALUE = File.class; /** File array class */ public static final Class FILES_VALUE = File[].class; /** URL class */ public static final Class URL_VALUE = URL.class; /** * Retrieve the class that ch represents. * * @param ch the specified character * @return The class that ch represents */ public static Object getValueClass(char ch) { switch (ch) { case '@': return PatternOptionBuilder.OBJECT_VALUE; case ':': return PatternOptionBuilder.STRING_VALUE; case '%': return PatternOptionBuilder.NUMBER_VALUE; case '+': return PatternOptionBuilder.CLASS_VALUE; case '#': return PatternOptionBuilder.DATE_VALUE; case '<': return PatternOptionBuilder.EXISTING_FILE_VALUE; case '>': return PatternOptionBuilder.FILE_VALUE; case '*': return PatternOptionBuilder.FILES_VALUE; case '/': return PatternOptionBuilder.URL_VALUE; } return null; } /** * Returns whether ch is a value code, i.e. * whether it represents a class in a pattern. * * @param ch the specified character * @return true if ch is a value code, otherwise false. */ public static boolean isValueCode(char ch) { return ch == '@' || ch == ':' || ch == '%' || ch == '+' || ch == '#' || ch == '<' || ch == '>' || ch == '*' || ch == '/' || ch == '!'; } /** * Returns the {@link Options} instance represented by pattern. * * @param pattern the pattern string * @return The {@link Options} instance */ public static Options parsePattern(String pattern) { char opt = ' '; boolean required = false; Object type = null; Options options = new Options(); for (int i = 0; i < pattern.length(); i++) { char ch = pattern.charAt(i); // a value code comes after an option and specifies // details about it if (!isValueCode(ch)) { if (opt != ' ') { OptionBuilder.hasArg(type != null); OptionBuilder.isRequired(required); OptionBuilder.withType(type); // we have a previous one to deal with options.addOption(OptionBuilder.create(opt)); required = false; type = null; opt = ' '; } opt = ch; } else if (ch == '!') { required = true; } else { type = getValueClass(ch); } } if (opt != ' ') { OptionBuilder.hasArg(type != null); OptionBuilder.isRequired(required); OptionBuilder.withType(type); // we have a final one to deal with options.addOption(OptionBuilder.create(opt)); } return options; } } commons-cli-1.2-src/src/java/org/apache/commons/cli/PosixParser.java100644 0 0 22701 11157377776 22643 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * The class PosixParser provides an implementation of the * {@link Parser#flatten(Options,String[],boolean) flatten} method. * * @author John Keyes (john at integralsource.com) * @version $Revision: 695760 $, $Date: 2008-09-16 01:05:03 -0700 (Tue, 16 Sep 2008) $ */ public class PosixParser extends Parser { /** holder for flattened tokens */ private List tokens = new ArrayList(); /** specifies if bursting should continue */ private boolean eatTheRest; /** holder for the current option */ private Option currentOption; /** the command line Options */ private Options options; /** * Resets the members to their original state i.e. remove * all of tokens entries and set eatTheRest * to false. */ private void init() { eatTheRest = false; tokens.clear(); } /** *

An implementation of {@link Parser}'s abstract * {@link Parser#flatten(Options,String[],boolean) flatten} method.

* *

The following are the rules used by this flatten method. *

    *
  1. if stopAtNonOption is true then do not * burst anymore of arguments entries, just add each * successive entry without further processing. Otherwise, ignore * stopAtNonOption.
  2. *
  3. if the current arguments entry is "--" * just add the entry to the list of processed tokens
  4. *
  5. if the current arguments entry is "-" * just add the entry to the list of processed tokens
  6. *
  7. if the current arguments entry is two characters * in length and the first character is "-" then check if this * is a valid {@link Option} id. If it is a valid id, then add the * entry to the list of processed tokens and set the current {@link Option} * member. If it is not a valid id and stopAtNonOption * is true, then the remaining entries are copied to the list of * processed tokens. Otherwise, the current entry is ignored.
  8. *
  9. if the current arguments entry is more than two * characters in length and the first character is "-" then * we need to burst the entry to determine its constituents. For more * information on the bursting algorithm see * {@link PosixParser#burstToken(String, boolean) burstToken}.
  10. *
  11. if the current arguments entry is not handled * by any of the previous rules, then the entry is added to the list * of processed tokens.
  12. *
*

* * @param options The command line {@link Options} * @param arguments The command line arguments to be parsed * @param stopAtNonOption Specifies whether to stop flattening * when an non option is found. * @return The flattened arguments String array. */ protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { init(); this.options = options; // an iterator for the command line tokens Iterator iter = Arrays.asList(arguments).iterator(); // process each command line token while (iter.hasNext()) { // get the next command line token String token = (String) iter.next(); // handle long option --foo or --foo=bar if (token.startsWith("--")) { int pos = token.indexOf('='); String opt = pos == -1 ? token : token.substring(0, pos); // --foo if (!options.hasOption(opt)) { processNonOptionToken(token, stopAtNonOption); } else { currentOption = options.getOption(opt); tokens.add(opt); if (pos != -1) { tokens.add(token.substring(pos + 1)); } } } // single hyphen else if ("-".equals(token)) { tokens.add(token); } else if (token.startsWith("-")) { if (token.length() == 2 || options.hasOption(token)) { processOptionToken(token, stopAtNonOption); } // requires bursting else { burstToken(token, stopAtNonOption); } } else { processNonOptionToken(token, stopAtNonOption); } gobble(iter); } return (String[]) tokens.toArray(new String[tokens.size()]); } /** * Adds the remaining tokens to the processed tokens list. * * @param iter An iterator over the remaining tokens */ private void gobble(Iterator iter) { if (eatTheRest) { while (iter.hasNext()) { tokens.add(iter.next()); } } } /** * Add the special token "--" and the current value * to the processed tokens list. Then add all the remaining * argument values to the processed tokens list. * * @param value The current token */ private void processNonOptionToken(String value, boolean stopAtNonOption) { if (stopAtNonOption && (currentOption == null || !currentOption.hasArg())) { eatTheRest = true; tokens.add("--"); } tokens.add(value); } /** *

If an {@link Option} exists for token then * add the token to the processed list.

* *

If an {@link Option} does not exist and stopAtNonOption * is set then add the remaining tokens to the processed tokens list * directly.

* * @param token The current option token * @param stopAtNonOption Specifies whether flattening should halt * at the first non option. */ private void processOptionToken(String token, boolean stopAtNonOption) { if (stopAtNonOption && !options.hasOption(token)) { eatTheRest = true; } if (options.hasOption(token)) { currentOption = options.getOption(token); } tokens.add(token); } /** * Breaks token into its constituent parts * using the following algorithm. * *
    *
  • ignore the first character ("-")
  • *
  • foreach remaining character check if an {@link Option} * exists with that id.
  • *
  • if an {@link Option} does exist then add that character * prepended with "-" to the list of processed tokens.
  • *
  • if the {@link Option} can have an argument value and there * are remaining characters in the token then add the remaining * characters as a token to the list of processed tokens.
  • *
  • if an {@link Option} does NOT exist AND * stopAtNonOption IS set then add the special token * "--" followed by the remaining characters and also * the remaining tokens directly to the processed tokens list.
  • *
  • if an {@link Option} does NOT exist AND * stopAtNonOption IS NOT set then add that * character prepended with "-".
  • *
* * @param token The current token to be burst * @param stopAtNonOption Specifies whether to stop processing * at the first non-Option encountered. */ protected void burstToken(String token, boolean stopAtNonOption) { for (int i = 1; i < token.length(); i++) { String ch = String.valueOf(token.charAt(i)); if (options.hasOption(ch)) { tokens.add("-" + ch); currentOption = options.getOption(ch); if (currentOption.hasArg() && (token.length() != (i + 1))) { tokens.add(token.substring(i + 1)); break; } } else if (stopAtNonOption) { processNonOptionToken(token.substring(i), true); break; } else { tokens.add(token); break; } } } } commons-cli-1.2-src/src/java/org/apache/commons/cli/TypeHandler.java100644 0 0 15406 11157377776 22607 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; /** * This is a temporary implementation. TypeHandler will handle the * pluggableness of OptionTypes and it will direct all of these types * of conversion functionalities to ConvertUtils component in Commons * already. BeanUtils I think. * * @version $Revision: 741425 $, $Date: 2009-02-05 22:10:54 -0800 (Thu, 05 Feb 2009) $ */ public class TypeHandler { /** * Returns the Object of type obj * with the value of str. * * @param str the command line value * @param obj the type of argument * @return The instance of obj initialised with * the value of str. */ public static Object createValue(String str, Object obj) throws ParseException { return createValue(str, (Class) obj); } /** * Returns the Object of type clazz * with the value of str. * * @param str the command line value * @param clazz the type of argument * @return The instance of clazz initialised with * the value of str. */ public static Object createValue(String str, Class clazz) throws ParseException { if (PatternOptionBuilder.STRING_VALUE == clazz) { return str; } else if (PatternOptionBuilder.OBJECT_VALUE == clazz) { return createObject(str); } else if (PatternOptionBuilder.NUMBER_VALUE == clazz) { return createNumber(str); } else if (PatternOptionBuilder.DATE_VALUE == clazz) { return createDate(str); } else if (PatternOptionBuilder.CLASS_VALUE == clazz) { return createClass(str); } else if (PatternOptionBuilder.FILE_VALUE == clazz) { return createFile(str); } else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) { return createFile(str); } else if (PatternOptionBuilder.FILES_VALUE == clazz) { return createFiles(str); } else if (PatternOptionBuilder.URL_VALUE == clazz) { return createURL(str); } else { return null; } } /** * Create an Object from the classname and empty constructor. * * @param classname the argument value * @return the initialised object, or null if it couldn't create * the Object. */ public static Object createObject(String classname) throws ParseException { Class cl = null; try { cl = Class.forName(classname); } catch (ClassNotFoundException cnfe) { throw new ParseException("Unable to find the class: " + classname); } Object instance = null; try { instance = cl.newInstance(); } catch (Exception e) { throw new ParseException(e.getClass().getName() + "; Unable to create an instance of: " + classname); } return instance; } /** * Create a number from a String. If a . is present, it creates a * Double, otherwise a Long. * * @param str the value * @return the number represented by str, if str * is not a number, null is returned. */ public static Number createNumber(String str) throws ParseException { try { if (str.indexOf('.') != -1) { return Double.valueOf(str); } else { return Long.valueOf(str); } } catch (NumberFormatException e) { throw new ParseException(e.getMessage()); } } /** * Returns the class whose name is classname. * * @param classname the class name * @return The class if it is found, otherwise return null */ public static Class createClass(String classname) throws ParseException { try { return Class.forName(classname); } catch (ClassNotFoundException e) { throw new ParseException("Unable to find the class: " + classname); } } /** * Returns the date represented by str. * * @param str the date string * @return The date if str is a valid date string, * otherwise return null. */ public static Date createDate(String str) throws ParseException { throw new UnsupportedOperationException("Not yet implemented"); } /** * Returns the URL represented by str. * * @param str the URL string * @return The URL is str is well-formed, otherwise * return null. */ public static URL createURL(String str) throws ParseException { try { return new URL(str); } catch (MalformedURLException e) { throw new ParseException("Unable to parse the URL: " + str); } } /** * Returns the File represented by str. * * @param str the File location * @return The file represented by str. */ public static File createFile(String str) throws ParseException { return new File(str); } /** * Returns the File[] represented by str. * * @param str the paths to the files * @return The File[] represented by str. */ public static File[] createFiles(String str) throws ParseException { // to implement/port: // return FileW.findFiles(str); throw new UnsupportedOperationException("Not yet implemented"); } } commons-cli-1.2-src/src/java/org/apache/commons/cli/UnrecognizedOptionException.java100644 0 0 3743 11157377776 26055 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * Exception thrown during parsing signalling an unrecognized * option was seen. * * @author bob mcwhiter (bob @ werken.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ public class UnrecognizedOptionException extends ParseException { /** The unrecognized option */ private String option; /** * Construct a new UnrecognizedArgumentException * with the specified detail message. * * @param message the detail message */ public UnrecognizedOptionException(String message) { super(message); } /** * Construct a new UnrecognizedArgumentException * with the specified option and detail message. * * @param message the detail message * @param option the unrecognized option * @since 1.2 */ public UnrecognizedOptionException(String message, String option) { this(message); this.option = option; } /** * Returns the unrecognized option. * * @return the related option * @since 1.2 */ public String getOption() { return option; } } commons-cli-1.2-src/src/java/org/apache/commons/cli/Util.java100644 0 0 4367 11157377776 21271 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * Contains useful helper methods for classes within this package. * * @author John Keyes (john at integralsource.com) * @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $ */ class Util { /** * Remove the hyphens from the begining of str and * return the new String. * * @param str The string from which the hyphens should be removed. * * @return the new String. */ static String stripLeadingHyphens(String str) { if (str == null) { return null; } if (str.startsWith("--")) { return str.substring(2, str.length()); } else if (str.startsWith("-")) { return str.substring(1, str.length()); } return str; } /** * Remove the leading and trailing quotes from str. * E.g. if str is '"one two"', then 'one two' is returned. * * @param str The string from which the leading and trailing quotes * should be removed. * * @return The string without the leading and trailing quotes. */ static String stripLeadingAndTrailingQuotes(String str) { if (str.startsWith("\"")) { str = str.substring(1, str.length()); } if (str.endsWith("\"")) { str = str.substring(0, str.length() - 1); } return str; } } commons-cli-1.2-src/src/media/logo.xcf100644 0 0 47455 11157377773 15101 0ustar 0 0 gimp xcf file,dBB/ gimp-commentCreated with The GIMPªNÒ-ýKðMX& Text Layer#2ÿ     ®3SX&kBX&Í € € €UþþUUüqªÿÿûâªUüqÿUýªÆÿ ÿªý8ªÿÿªþâÿÿùâªÆÿÿUþqÿÿýâ8ýªÿÿüâ8ýUÆÿÿþUþqÿÿþþUÿÿþ ýUâÿÿþUþÿÿþÆþªÿÿýâ8 ýÆÿÿþUÿþªþªÿÿýâþªÿÿþUÿþªþUÿÿþUúâÿÿUÿþªþ8ÿÿþû8ÿÿqÿþªþÆÿÿþüÆÿªÿþªþqÿÿþüqÿªÿþªþÆÿÿþýÿªÿþªþ8ÿÿþÆqÿþªþÿÿþª ÿþªþÆÿÿþU ÿþªÿþU ÿþªþÿÿ"ÿþªþUÿÿ"ÿþªþUÿÿ"ÿþªþUÿÿ"ÿþªþUÿÿ"ÿþªþUÿÿþ ÿþªÿþU ÿþªÿþU ÿþªþªÿÿþª ÿþªþqÿÿþâ ÿþªþÿÿþ8ÿþªþÆÿÿþÿþªþ8ÿÿþÿþªþÆÿÿþÿþªþÿÿþUüUâÿþªþUÿÿýâüqÿâÿþªþUÿÿýâUúÆÿâÿþªþUÿÿý ùÿÿªÿþªýÆÿÿýªUýUÿÿþqþUÿÿþâ ý8Æýqâÿÿþ⪪þâÿÿýýâÿÿýÆUUýªÿÿ ý8ªÿ ÿüÆqüUqªÿÿ ü8UªªU ªþUUü8ªâÿ ÿª þqÿÿýâ8 þqÿÿþþÿÿþÆÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÿþªÆÿþªüÿqÿþªüÆÿ8ÿþªüUÿÿÿþªûâÿªÿþªúUâÿÿUÿþÆÿþþUÿÿÿþÆþÆÿÿþªÿþúUUªâÿÿûâªUUªªþ8þ8ªª,vDDrop-Shadow#2Ì     §,øvDÆvD,Ʀ¶5    ö û  ý ó      ù ý ñ  ô ï  þùü í ýù"$&((ü&$! í  !"##$%&%í$#!! !"%'*.02321.* î  "%'())*ü+,-..ì-,*)('(),/37:<==:72è  $'*-./0//..--.û/12455í420/./037<@DGHGD@:î #(-03566û543211ä2468:;<=<;976557;?DINQRRNIBè  &,159;<=<;975322ä468;=@ABBA?=;:;=@EKQVZ[ZWQIÖ !(.4:>ACCB@>;8632112369HQX]__\VOG?6/("#',158;<<ñ=?CIQZckqsrmdYâ $/:EOX_cdb]VND;2*#ä!%*.1456779<@GPYckqsrmdYâ )4@KV_ehhd^ULA7-%ä#'*-.01248>ENXbkqsrmdYâ #.9FQ\djlje^TI>3)   ä  #%()+-04:CLWajpsrmdXà &2>KWainolf]RF:/%  !#%'+07@JU`iprqlcXà *6CP\fmqqmf\PC7+!  "',4>HT_horqlcXà !-9FT`jqtsnf[NA4(  #)1;GS^hnrqlcWá #/LZfpvxuoeYK=0$ å $-8DQ\gnqpkcWá &2@N\hqwyvoeXJ1% ì )5BO\fnqpkcWà %1>LZfpwywqh\N@3' ë )5BO[fmqpkcWà #/KXckqsqlcYMB6,#  é #-8DQ]gorrmeYß "-9FR]fmpole\QF;1(   ç %.9ER^hosrnf[à )4@LW`hlmke^UJ@6.&è!'0;GS_ipssog\ß $.9EPZbgiie_WNE<4,&!î#)2HR[adec_YQIA92,'#î!%+3=HT_iossoh^Þ #,6@JSY^``^YSMF?82-)&#" ï #&,4=HS^hnrroh_Þ &/8AJQVZ[ZXSNHC=73/+)'&%$$##þ"!!ï"$(-4=HS]fmpqnh_Ø  (09AHNRUVTRNJE@<741.,*)(''&%$#""ð$',3:742/.,+*)'&%#""ð#&+2:CMV^dhhfb[Ç !(.5;@DGIIHFDA>;8631/.,*)'%$"! "$)/6?HPX]aa`\WÚ  &,16;>@ABA@><:7531/-+)'%#! ð"&+2:BJPUYZXUQï #(-1579::Ý986420.,*(&$" "'-4;AGLOPOMIÉ  $(+.0223210/-,*(&$" !',28=ADEDB@ í #%')*++ß*)('%#"  %*/379:986 î !"##à"! "&),.//., à   ð !#$%%$# ñ õ õ ô ç  þõ    ø ÷ øú ü    € € €Øþ þ  þ  ùøù ö÷  ô õ ô ó ô á  ó â  õ Ý "%'((&$! ô%  à !&+/1220.*%  ô,& ß "(.48;=<:72,& ô3,$ Þ '.62' à !+6BNYbilkg`VJ>2' ÐK?3'   +6CO[elonjbWK?3' óL?2' ß  *6CP\fmqpkcXL?2' óL?2' ß *6CP]gnrqldYL?2' óL?2& ß )5CP\gnrqldYL?2& ôL>1& à )5CP\gnrqmdYL>1& ôK>1% á (5BO\gnrqldXK>1% ôK=0% á (4AO\fnqqlcXK=0% ôK=0$ á (4AO[fnqqlcXK=0$ ôJ=0$ á '4AN[fmqpkcWJ=0$ ôJ=0$ á '4AN[fmqpkcWJ=0$ ôJ=0$ á '4AN[emqpkcWJ=0$ ôJ=0$ â (4AO[fmqpkcWJ=0$ ôJ=0$ à (4AO[fmqpkcWJ=0$ ÑJ=0$  (4BO[fnqpkcWJ=0$ õJ=0$ à )5BO\fnqpkcWJ=0$ ôJ=0$ ß *5BO\fnqplcWJ=0$ õJ=0$ à !+6CP\fnqpkcWJ=0$ õJ=0$ Þ ",7DP]gnqpkcWJ=0$ öK>1% Ý %.9ER]gnrqlcXK=0$ öL>2& Ý  '0;FS^horqlcXK=0% ÑM@3( $*3=HT_iorqldXK>1% ÑNB5*! #(.6?JU`ipsrldXK>1% ÐPC7-$!#%(,29BLWajpsrmdYL?2& ÐRF:0' !$&')+-05;DMWajpsrmdYL?2& ÐSH=3*$  #%(*,./0148>ENXbjprqldYL?3' ÐUJ?6/)%#""$&),.1234457:@FOXainqokcXL?3' îVLB:3.*(()*-/256788å9842012368:<==<;:9:;?DJQX_ced`YPF;0& ñPIC=853223579;==à<:9879;@ELRX\]\YSKA7-$ ùLF@<8533ú4679:;;à9864457;@EKPTUTQLE<3*" ùE@<85211û235677ß65310/0259>CGJKKHC=6.& ù<9520.--û./0122à0/-+*))+.159=?A@>:5.(! ù41.,*)((Ù)*++,,+*('%$##$')-0356640,'" ú*(&%#""#$ò"!!$')++ð*'$  ú" ñ ""ð! ûûúñ ýû  ú ò   þ       þ  ó ÷   $ØØØØ;"× Text Layerÿ      yו-å-ñ×±#¶'´,[€€€ý8qªªüUý8Uªªýq8üq8ýqâÿÿýª ýqâÿÿüâ úUªÿÿUõ8âÿÿ8ªÿÿþUôUâÿÿ8qâÿÿþUüqªÿÿþUúUÿÿÆþÆÿÿþUþqÿÿþUþªÿÿþªüªªÿÿüUÆûUÿÿâþqÿÿþâþUÿÿþUþªÿÿþªþqÿÿùªÿÆ8ÿÿþþÿÿþUþ8ÿÿþÆ þâÿÿþUÿþªûâÿÿþÆÿÿþþÆÿÿþU þ8ÿÿþâÿþÆþqÿÿþ8úâÿÿUþ8ÿÿ þâÿÿþqÿþªþÆÿÿ þþªÿÿþÆ þÿÿþÆÿûªÿÿþÆÿþª þ8ÿÿÿûªUÿÿþªþÿÿþª ÿþ8ÿûªÿÿþªþUÿÿþª þâÿÿþUÿûªªÿÿþªþUÿÿþª þªÿÿþUÿûªªÿÿþâþUÿÿ þªÿÿþUÿûªªÿÿþUÿÿ þªÿÿþ8ÿûªªÿÿþUÿþU þªÿÿÿûªUÿÿþÆ þ8þâÿÿþ þªÿÿþÆÿûª8ÿÿþ8 ýUâþÿÿþÆ ÿþqÿþªþâÿÿýâ ü8ÿ8þ8ÿÿþ8 þÿÿþÿþªþqÿÿýªü8âÆþÆÿÿþ þqÿÿþÿþªþâÿÿýâ8ûqÿÿþÿÿþûâÿÿâÿþªþUÿÿýâUUúâÿÿUþUÿÿþÆúqÿÿâÿþªþUÿ ÿþUþUÿÿþªúUÿÿâþÿÿþªþUÿ ÿýâU ý8âÿÿôâqUÆÿÿÆþqÿÿþýÆÿÿý ýqâÿÿýÆ8üUqÆÿÿýâªýUªªýUý8qªªýU ª€€€ù8qªª8ùUªª8 ý8ùUªªqùUª8ÆÿÿýÆýqâÿÿýÆúqÆÿÿýqâÿÿþýÿÿþÿÿþÆý8âÿÿþâü8ÆÿÿýÆÿÿþqþqÿÿúâUUÿÿùqUÿÿªUUýâÿÿþqüƪÆÿÿöUâÿÆqUUÆÿÿùªÿâUUþ8þÿÿúâUÿªýâÿÿþâþÆÿÿûªÿþqÿÿûªÿq þÿÿþªþqÿÿþ8þUÿÿþUþâÿÿþU þ8ÿÿþÆþ8ÿÿþUþUÿÿþqþÿÿþq ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU ÿþªÿþªþUÿÿþUþUÿÿþU þÿÿþâÿþÆþqÿÿþUþqÿÿþ þqÿÿþUþqÿÿþþÆÿÿþÆþÆÿÿýâøU8qÆÿÿ÷ªU88qÆÿÿ÷âU8UâÿÿüÆUüUâÿÿóâUUª8qª ªûqqª ªýq8ª ª ªü8ª€€€ªýqüUªªýUü88ýqªªþUÿþ ý8Æÿÿýª8 õ8âÿÿUÿÿýâUÿþ ùÆÿÿÆUýUÆÿÿþªüUªâÿÿûU8âÿÿûUªÿÿþú8âÿÿªþUÿÿýâªÿUøÿâUUâÿÿþâþUÿÿþúâÿÿªþUÿÿýâþªÿÿûâÿªþÆÿÿþUþÆÿÿþâþâÿÿþþÿÿþªþUÿÿþUþ8ÿÿþªþÿÿþqÿÿþª þâÿÿþ8þUÿÿþqþâÿÿþâþUÿÿþUþâÿÿþU þÿÿþÆþUÿÿþUþªÿÿþUÿÿþUþUÿÿþ þ8ÿÿþþUÿÿþUþªÿÿþUÿÿþUþªÿÿ þâÿÿþUþUÿÿþUþªÿÿþUÿÿþUþÆÿÿ þªÿÿþþUÿÿþUþªÿÿþUÿÿþUÿ þÿÿþªþUÿÿþUþªÿÿþUÿÿþUÿ þUÿÿþªþUÿÿþUþªÿÿþUÿÿþUÿþU þUÿÿþªþUÿÿþUþªÿÿþUÿÿþUÿþU þUÿÿþþUÿÿþUþªÿÿþUÿÿþUþªÿÿþª þUÿÿþUþUÿÿþUþªÿÿþUÿÿþUþÿÿþâ þUÿÿþþUÿÿþUþªÿÿþUÿÿþUþ8ÿÿþ þªÿÿþÆþUÿÿþUþªÿÿþUÿÿþUþâÿÿþ þÆÿÿþqþUÿÿþUþªÿÿþUÿÿþUþqÿÿþâ þÿÿþâþUÿÿþUþªÿÿþUÿÿþUþÆÿÿþqþÿÿþ8þUÿÿþUþªÿÿþUÿÿþUýâÿÿþþÿÿþUþUÿÿþUþªÿÿþUÿÿþqýâÿÿýâúâÿÿUþqÿÿþUþâÿÿûÆÿÿþÆýªÿÿõ88ÿÿâUþâÿÿþÆþUÿÿüqâÿÿûÆqUý8Æÿÿýâqü8qâÿÿ÷âUUªÿÿ ªþ8ýUªªýq8 þqª ªþ8ªªVVV ýUªªúU óÿÿ⪪ÆÿÿªÆÿûÆÿâ8ý8Æÿÿûªÿÿ8üâÿÿû8ÿÿÆü8ÿÿûÿÿªýªÿûªÿÿâýUÿþªÿÿþqþÿþqÿÿþqþ8þÿÿýÆ8þÿÿýÆ þªÿÿý þÿÿýâq ý8âÿÿýâ þqÿÿýâU ýÿÿýâ ýªÿÿþýªqþUÿÿþ⪠þÿÿýªÿþÿÿüªÿqÿþÆûªÿâþÿÿþqûªÿÿªûÿÿªþªÿÿýÆ8öÿÿªÆqøªÆªªÿÿ⪪ÿýâqªþ8ý8ø8UªªUk 5á$ Drop-ShadowD       .¥á$.ÁKØKäá$.Ý6ã?;GŒ   Lþüýüñ  ð üí  í   ù ê &.49<=<80%ß &-38<>=:4," &Å +7BJOTX\_^WI7%   -:CJOSWZ]]ZQE5% #1@LÄ &8HTZ\\]bkw€€u_D*  )bŒeD( ;e‘±¹§Q*=eŠ ƒ]9 &Bh‘³Á¸šoD$*Ky©Ì0V}–”zT0 )Lt”¡”rI'.T€£¯wK'*Mz¦Ãȳ‹\3 >m¡È Bm“£”oD"  3QlxoV7 >j˜µµ˜i<  8d•½ÏÅ¢rC  6f›Ä+S¤ª‘d8 0BJE5"'M~ªÀ·‘_2Ü)Q„³ÏÏ´…R) 3c™Â5b‘¯­\0è  $" /[Ž¸È·ŒX,Ý Cu¨ËÔ¿“^1 2b™Â ?o·¯ŠX,é   6e™Á̸‹V*Ý8ižÇÖÆh8 2b™Á !Gx¦½²ŠW+ê ;l¡ÇѺŒW+Ý1_•ÁÕÊ£n<2b™Á $L­Â¶ŽZ-ï >p¤ÊÔ¾Z-Þ,Y½Óʤp>2b™Á%N‚°Ç¼•a3î >o¤Ë××a2Þ*U‹ºÑÈ¢n<2b™Á %M±Êßl< ì ;k ÉØÉ j:Ý)TЏÎÃh8 2b™Á "I|­Ëʬ}K&ë 6c˜ÄØÎªvD Ü+V‹·Ê¼“_1 2b™Á Bs¦ÉÑ»‘a7 é 0YŒ»ÔÒ´ƒP(Û.[·Ä±†S) 2b™Á8g›ÃÔɨ{O- é !,/*)K|­ÍÓ¾“`3€5c”·¼¢uE! 2b™Á-WŠ·ÑÓ¾špJ. )7@?2" =išÀÐÅ¢rC!  @nš³¯Ž`6 2b™Â !Et¤ÇÖÏ·”pQ;-%#%,7EPQF2-S¬ÆÈ°†X1 *NzªšuJ&3c™Â3[гÎÖÍ·›gVLHJQZabXC+ m ÆÂ*Kr˜·ÊÑÏÆ»°¦ž˜…s[@' -LoŽ¢¤•|aI:35>Ocu|t]@% )Jw¥ÆÃ .Mp‘«½ÅÇĽ´ªw^C*  -Ig€†veWPPV_hleT<% !8X~¤¾× -Gd~“¢ª¬©¡”„oX?)  )?Vjvyume`]]î[SF4!  )A\z•¦é &:Napz~|uiYG4" Þ  1AOY]][WSNH@5( (<82+# +7AIMî !##  í   ö !$&ñ  ð ÷  ÷þþþ?   @þ þð ó Ç      !! €)   ! )&(4>DE@6(  ,8AFFA6) !(*% ,8AFD=2# PI:+%*8HYgqtoaM6#,=N^ksuoaM5  (6EOOE4'%-m¡ÆÑ½“`4  #5Y‡±Ëʰ…W2 3Y‡²ÌÍ´‹]6Ķ–nI, 6V~¤¾ÆºœuO1 6U}£½Ä¶—pL2%$.DeŒ®ÂÁ¬‰b?&&Ad‹®ÃıhEª¡‹mO5!(>Zy”§¬¤sU:&)>Zx”¦ª¡‹nR<0/9Lg„›©¨šcF-.Geƒœ©ªž†iL€zm[F1!'9Nbs~|q_K7&'9Nbs}€zm[I90/7EWiw~vgT?,,@Viw€ykXDNLF<1$)5@HMOMG?4')5@HMNLF=3*%$)1;DJNNJC9-  -:DJNNKE;0&%# !$&&Ã$  !$&&%# #%&&%" "%&&%#  ó  õ  ô  ü þþþþþ>   Aøþüí  ù  ù á  " ì   Ý   "$0;CGE>2# Ä #+17;=><7/&  $+.+"%1$ .Hf…Ÿ¯¯ž„mceo|‹šªµ¶acgn{§ºÀ±Ža6 %A`y„}kTA516CXr¡§„a?$1Mp–¶Êʸ›€nfejt„›²ÁOHEHTl®ÃÁ¤wG"  <`“yZ='&9Uw™°¶¦†^9)Di”»ÓÖã‚fTJHN_z»6)$&1Jp›½Ç³ˆU+ 1Wœ¢ŽjD' 7Z„©¿¾¦~R.4Z‰¶ÒÖÂuR:,'+;Y‚¬ 3ZŠµÈ¼•a3 #Fr™®¦…Y1 !@k˜¼É½šk? (M~¯ÎÒºb<#"@l&L®Èžj:1ZŠ®¸¤yJ$,T…±Ì˰‚Q*"ExªÊͱƒR+  1^‘  FxªÇÅ£p??m¼¾ o? à Bs¥ÈÒ¿•b5 Cu¨ÈÉ«zH" +W‹  Cv¨ÇƦsA &K}­ÇÁi8Ã5c˜ÂÔÉ£p? Cu§ÇȨvD )T‰  Bu§ÇƦtB",U‰·ÎÜf6Ã,WŒºÓέzG$!Cu§ÇǧuB (R‡  Bu§ÇǧtC#0[‘¾ÓÆžg6Ä&Nƒ´Ñв€L'!Cu§ÇǧuB (R‡  Bu§ÇǧtC#2^•ÂÖÊ¢l:Ä "H|¯Îг‚N("Cu§ÇǧuB (R‡  Bu§ÇǧuC#1^”Â×ͨs@ Ä Ex«Ìα€L'!Cu§ÇǧuB (R‡  Bu§ÇǧuC#/Y¾×Ѱ}I" à DwªÉʬzH$!Cu§ÇǧuB (R‡  Bu§ÇǧuC"*R‡·ÔÔ¸ˆS)à FyªÇÄ¢p@ Cu§ÇǧuB (R‡  Bu§ÇǧuC!$Hz¬ÎÖÁ•a3à $K~¬Ã»–c6 Bu§ÇǧuB (R‡  Bu§ÇǧuB 43:H\p|yfJ-  1X‡²Ë˰†X3 "@kš*'@cŠ­ÁÁ­Šb@& &@]x‹‘Š{j[QOS\eki[E- "=b‹®Â­Šc@'/Nuœ3!/Gd‚›¨¨š‚dG. "7Odsywpha^]]\WK:(  (Cc‚œ©©›‚dG/#7Sr0!-@Uhw~~vhU@-+=94.& *7CJNNJC:.!%2>G "%&&%"    á"%&&%"  $ ø ð ù ó  þüþþ?¤¤¤ þ üú  øú í  ù- ë &-13321/,)! ùU>' ÷)8BGHHõJKNNI<) á‚eE( 1FUZWRNMRZeljX< €Ä©Œf?  0LdmgXI@?GVj{~kI'À«„W/&Fh}|hL6)'0B\upN*ɾœm> 4[€„d@%+EaqhK)ÇÈ­~K$ ?k‘žf=  /I[XB%ÁÌ·ŠU* !Etœª™sI( 3CE5 ¼Ì½’\. EtŸ´ªŠc@'".0& á¹ÍÀ–`0 >lš·º¦†eH1!á·ÌÁ—a12\НÀ½ªsXA.!â¶ÌÁ˜b2%Gr›¸Äµ ‡lS=+ á¶ÌÁ˜b2 0S{ž¸ÅÈÀ°šfL5" €̶ÌÁ˜b2 5Ux˜±ÂÊȽ«“x[?' ¶ÌÁ™b24PnŒ¦ºÆÊŸ¢†eD(¶ÌÁ™b2 .D^z•¬½ÈÉÀ¬Œf@"¶ÌÁ™b2 %7Mg›²ÃÊĬ‡[3¶ÌÁ™b2 )-$$,=Xuˆ‡pM+ºÆ¾¤}U4$@b|„yeQB;;BPbquiP3 ¤¬§”xX;$3Mcli_TLHINV^`YH2|}sbL5""3AHIGDCCEHJJD9*âMOMH@4&"&()+-/121.' &æ$!   è  þ)p8 ,d Backgroundÿ     LŸ,dL¿MkMwMƒ,dLóLÿM MM#M/M;MGMSM_ÿÿÿÿÿÿÿÿÿÿÿÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ0ÿ0ÿ0ÿ–2K% ,dSelection MaskMù,dNO OO!,dNMNQN—NßNãNçNëN÷OO éÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ(ÿ À ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2 ÿ2  (ÿ(ÿ€ ÿ2 ÿ³ 0–2K% commons-cli-1.2-src/src/test/org/apache/commons/cli/ApplicationTest.java100644 0 0 24413 11157377775 23526 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import junit.framework.TestCase; /** * This is a collection of tests that test real world applications command lines. * *

* The following applications are tested: *

    *
  • ls
  • *
  • Ant
  • *
  • Groovy
  • *
  • man
  • *
*

* * @author John Keyes (john at integralsource.com) */ public class ApplicationTest extends TestCase { public void testLs() throws Exception { // create the command line parser CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption( "a", "all", false, "do not hide entries starting with ." ); options.addOption( "A", "almost-all", false, "do not list implied . and .." ); options.addOption( "b", "escape", false, "print octal escapes for nongraphic characters" ); options.addOption( OptionBuilder.withLongOpt( "block-size" ) .withDescription( "use SIZE-byte blocks" ) .hasArg() .withArgName("SIZE") .create() ); options.addOption( "B", "ignore-backups", false, "do not list implied entried ending with ~"); options.addOption( "c", false, "with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime" ); options.addOption( "C", false, "list entries by columns" ); String[] args = new String[]{ "--block-size=10" }; CommandLine line = parser.parse( options, args ); assertTrue( line.hasOption( "block-size" ) ); assertEquals( line.getOptionValue( "block-size" ), "10" ); } /** * Ant test */ public void testAnt() throws Exception { // use the GNU parser CommandLineParser parser = new GnuParser( ); Options options = new Options(); options.addOption( "help", false, "print this message" ); options.addOption( "projecthelp", false, "print project help information" ); options.addOption( "version", false, "print the version information and exit" ); options.addOption( "quiet", false, "be extra quiet" ); options.addOption( "verbose", false, "be extra verbose" ); options.addOption( "debug", false, "print debug information" ); options.addOption( "logfile", true, "use given file for log" ); options.addOption( "logger", true, "the class which is to perform the logging" ); options.addOption( "listener", true, "add an instance of a class as a project listener" ); options.addOption( "buildfile", true, "use given buildfile" ); options.addOption( OptionBuilder.withDescription( "use value for given property" ) .hasArgs() .withValueSeparator() .create( 'D' ) ); //, null, true, , false, true ); options.addOption( "find", true, "search for buildfile towards the root of the filesystem and use it" ); String[] args = new String[]{ "-buildfile", "mybuild.xml", "-Dproperty=value", "-Dproperty1=value1", "-projecthelp" }; CommandLine line = parser.parse( options, args ); // check multiple values String[] opts = line.getOptionValues( "D" ); assertEquals( "property", opts[0] ); assertEquals( "value", opts[1] ); assertEquals( "property1", opts[2] ); assertEquals( "value1", opts[3] ); // check single value assertEquals( line.getOptionValue( "buildfile"), "mybuild.xml" ); // check option assertTrue( line.hasOption( "projecthelp") ); } public void testGroovy() throws Exception { Options options = new Options(); options.addOption( OptionBuilder.withLongOpt("define"). withDescription("define a system property"). hasArg(true). withArgName("name=value"). create('D')); options.addOption( OptionBuilder.hasArg(false) .withDescription("usage information") .withLongOpt("help") .create('h')); options.addOption( OptionBuilder.hasArg(false) .withDescription("debug mode will print out full stack traces") .withLongOpt("debug") .create('d')); options.addOption( OptionBuilder.hasArg(false) .withDescription("display the Groovy and JVM versions") .withLongOpt("version") .create('v')); options.addOption( OptionBuilder.withArgName("charset") .hasArg() .withDescription("specify the encoding of the files") .withLongOpt("encoding") .create('c')); options.addOption( OptionBuilder.withArgName("script") .hasArg() .withDescription("specify a command line script") .create('e')); options.addOption( OptionBuilder.withArgName("extension") .hasOptionalArg() .withDescription("modify files in place; create backup if extension is given (e.g. \'.bak\')") .create('i')); options.addOption( OptionBuilder.hasArg(false) .withDescription("process files line by line using implicit 'line' variable") .create('n')); options.addOption( OptionBuilder.hasArg(false) .withDescription("process files line by line and print result (see also -n)") .create('p')); options.addOption( OptionBuilder.withArgName("port") .hasOptionalArg() .withDescription("listen on a port and process inbound lines") .create('l')); options.addOption( OptionBuilder.withArgName("splitPattern") .hasOptionalArg() .withDescription("split lines using splitPattern (default '\\s') using implicit 'split' variable") .withLongOpt("autosplit") .create('a')); Parser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-e", "println 'hello'" }, true); assertTrue(line.hasOption('e')); assertEquals("println 'hello'", line.getOptionValue('e')); } /** * author Slawek Zachcial */ public void testMan() { String cmdLine = "man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath] [-Ppager] [-Slist] " + "[-msystem] [-pstring] [-Llocale] [-eextension] [section] page ..."; Options options = new Options(). addOption("a", "all", false, "find all matching manual pages."). addOption("d", "debug", false, "emit debugging messages."). addOption("e", "extension", false, "limit search to extension type 'extension'."). addOption("f", "whatis", false, "equivalent to whatis."). addOption("k", "apropos", false, "equivalent to apropos."). addOption("w", "location", false, "print physical location of man page(s)."). addOption("l", "local-file", false, "interpret 'page' argument(s) as local filename(s)"). addOption("u", "update", false, "force a cache consistency check."). //FIXME - should generate -r,--prompt string addOption("r", "prompt", true, "provide 'less' pager with prompt."). addOption("c", "catman", false, "used by catman to reformat out of date cat pages."). addOption("7", "ascii", false, "display ASCII translation or certain latin1 chars."). addOption("t", "troff", false, "use troff format pages."). //FIXME - should generate -T,--troff-device device addOption("T", "troff-device", true, "use groff with selected device."). addOption("Z", "ditroff", false, "use groff with selected device."). addOption("D", "default", false, "reset all options to their default values."). //FIXME - should generate -M,--manpath path addOption("M", "manpath", true, "set search path for manual pages to 'path'."). //FIXME - should generate -P,--pager pager addOption("P", "pager", true, "use program 'pager' to display output."). //FIXME - should generate -S,--sections list addOption("S", "sections", true, "use colon separated section list."). //FIXME - should generate -m,--systems system addOption("m", "systems", true, "search for man pages from other unix system(s)."). //FIXME - should generate -L,--locale locale addOption("L", "locale", true, "define the locale for this particular man search."). //FIXME - should generate -p,--preprocessor string addOption("p", "preprocessor", true, "string indicates which preprocessor to run.\n" + " e - [n]eqn p - pic t - tbl\n" + " g - grap r - refer v - vgrind"). addOption("V", "version", false, "show version."). addOption("h", "help", false, "show this usage message."); HelpFormatter hf = new HelpFormatter(); //hf.printHelp(cmdLine, opts); hf.printHelp(60, cmdLine, null, options, null); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/ArgumentIsOptionTest.java100644 0 0 5152 11157377775 24511 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import junit.framework.TestCase; public class ArgumentIsOptionTest extends TestCase { private Options options = null; private CommandLineParser parser = null; public void setUp() { options = new Options().addOption("p", false, "Option p").addOption("attr", true, "Option accepts argument"); parser = new PosixParser(); } public void testOptionAndOptionWithArgument() throws Exception { String[] args = new String[]{ "-p", "-attr", "p" }; CommandLine cl = parser.parse(options, args); assertTrue("Confirm -p is set", cl.hasOption("p")); assertTrue("Confirm -attr is set", cl.hasOption("attr")); assertTrue("Confirm arg of -attr", cl.getOptionValue("attr").equals("p")); assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0); } public void testOptionWithArgument() throws Exception { String[] args = new String[]{ "-attr", "p" }; CommandLine cl = parser.parse(options, args); assertFalse("Confirm -p is set", cl.hasOption("p")); assertTrue("Confirm -attr is set", cl.hasOption("attr")); assertTrue("Confirm arg of -attr", cl.getOptionValue("attr").equals("p")); assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0); } public void testOption() throws Exception { String[] args = new String[]{ "-p" }; CommandLine cl = parser.parse(options, args); assertTrue("Confirm -p is set", cl.hasOption("p")); assertFalse("Confirm -attr is not set", cl.hasOption("attr")); assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/BasicParserTest.java100644 0 0 3215 11157377775 23436 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * @author Emmanuel Bourg * @version $Revision: 695410 $, $Date: 2008-09-15 03:25:38 -0700 (Mon, 15 Sep 2008) $ */ public class BasicParserTest extends ParserTestCase { public void setUp() { super.setUp(); parser = new BasicParser(); } public void testPropertiesOption() throws Exception { // not supported by the BasicParser } public void testShortWithEqual() throws Exception { // not supported by the BasicParser } public void testShortWithoutEqual() throws Exception { // not supported by the BasicParser } public void testLongWithEqual() throws Exception { // not supported by the BasicParser } public void testLongWithEqualSingleDash() throws Exception { // not supported by the BasicParser } } commons-cli-1.2-src/src/test/org/apache/commons/cli/bug/BugCLI133Test.java100644 0 0 2730 11157377775 23312 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli.bug; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import junit.framework.TestCase; /** * @author brianegge */ public class BugCLI133Test extends TestCase { public void testOrder() throws ParseException { Option optionA = new Option("a", "first"); Options opts = new Options(); opts.addOption(optionA); PosixParser posixParser = new PosixParser(); CommandLine line = posixParser.parse(opts, null); assertFalse(line.hasOption(null)); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/bug/BugCLI13Test.java100644 0 0 3622 11157377775 23230 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli.bug; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import junit.framework.TestCase; /** * @author brianegge */ public class BugCLI13Test extends TestCase { public void testCLI13() throws ParseException { final String debugOpt = "debug"; Option debug = OptionBuilder .withArgName( debugOpt ) .withDescription( "turn on debugging" ) .withLongOpt( debugOpt ) .hasArg() .create( 'd' ); Options options = new Options(); options.addOption( debug ); CommandLine commandLine = new PosixParser().parse( options, new String[]{"-d", "true"} ); assertEquals("true", commandLine.getOptionValue( debugOpt )); assertEquals("true", commandLine.getOptionValue( 'd' )); assertTrue(commandLine.hasOption( 'd')); assertTrue(commandLine.hasOption( debugOpt)); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/bug/BugCLI148Test.java100644 0 0 4501 11157377775 23316 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli.bug; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import junit.framework.TestCase; /** * http://issues.apache.org/jira/browse/CLI-148 * * @author brianegge */ public class BugCLI148Test extends TestCase { public void testWorkaround1() throws Exception { Options options = buildCommandLineOptions(); CommandLineParser parser = new PosixParser(); String[] args = new String[] {"-t-something" }; CommandLine commandLine; commandLine = parser.parse( options, args ); assertEquals("-something", commandLine.getOptionValue( 't')); } public void testWorkaround2() throws Exception { Options options = buildCommandLineOptions(); CommandLineParser parser = new PosixParser(); String[] args = new String[] {"-t", "\"-something\"" }; CommandLine commandLine; commandLine = parser.parse( options, args ); assertEquals("-something", commandLine.getOptionValue( 't')); } private Options buildCommandLineOptions() { Option t = OptionBuilder.withArgName( "t").hasArg().create('t'); Option s = OptionBuilder.withArgName( "s").hasArg().create('s'); Options options = new Options(); options.addOption( t); options.addOption( s); return options; } } commons-cli-1.2-src/src/test/org/apache/commons/cli/bug/BugCLI162Test.java100644 0 0 30705 11157377775 23337 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli.bug; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.ParameterMetaData; import java.sql.Types; import junit.framework.TestCase; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class BugCLI162Test extends TestCase { /** Constant for the line separator.*/ private static final String CR = System.getProperty("line.separator"); public void testInfiniteLoop() { Options options = new Options(); options.addOption("h", "help", false, "This is a looooong description"); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(20); formatter.printHelp("app", options); // used to hang & crash } public void testPrintHelpLongLines() throws ParseException, IOException { // Constants used for options final String OPT = "-"; final String OPT_COLUMN_NAMES = "l"; final String OPT_CONNECTION = "c"; final String OPT_DESCRIPTION = "e"; final String OPT_DRIVER = "d"; final String OPT_DRIVER_INFO = "n"; final String OPT_FILE_BINDING = "b"; final String OPT_FILE_JDBC = "j"; final String OPT_FILE_SFMD = "f"; final String OPT_HELP = "h"; final String OPT_HELP_ = "help"; final String OPT_INTERACTIVE = "i"; final String OPT_JDBC_TO_SFMD = "2"; final String OPT_JDBC_TO_SFMD_L = "jdbc2sfmd"; final String OPT_METADATA = "m"; final String OPT_PARAM_MODES_INT = "o"; final String OPT_PARAM_MODES_NAME = "O"; final String OPT_PARAM_NAMES = "a"; final String OPT_PARAM_TYPES_INT = "y"; final String OPT_PARAM_TYPES_NAME = "Y"; final String OPT_PASSWORD = "p"; final String OPT_PASSWORD_L = "password"; final String OPT_SQL = "s"; final String OPT_SQL_L = "sql"; final String OPT_SQL_SPLIT_DEFAULT = "###"; final String OPT_SQL_SPLIT_L = "splitSql"; final String OPT_STACK_TRACE = "t"; final String OPT_TIMING = "g"; final String OPT_TRIM_L = "trim"; final String OPT_USER = "u"; final String OPT_WRITE_TO_FILE = "w"; final String _PMODE_IN = "IN"; final String _PMODE_INOUT = "INOUT"; final String _PMODE_OUT = "OUT"; final String _PMODE_UNK = "Unknown"; final String PMODES = _PMODE_IN + ", " + _PMODE_INOUT + ", " + _PMODE_OUT + ", " + _PMODE_UNK; // Options build Options commandLineOptions; commandLineOptions = new Options(); commandLineOptions.addOption(OPT_HELP, OPT_HELP_, false, "Prints help and quits"); commandLineOptions.addOption(OPT_DRIVER, "driver", true, "JDBC driver class name"); commandLineOptions.addOption(OPT_DRIVER_INFO, "info", false, "Prints driver information and properties. If " + OPT + OPT_CONNECTION + " is not specified, all drivers on the classpath are displayed."); commandLineOptions.addOption(OPT_CONNECTION, "url", true, "Connection URL"); commandLineOptions.addOption(OPT_USER, "user", true, "A database user name"); commandLineOptions .addOption( OPT_PASSWORD, OPT_PASSWORD_L, true, "The database password for the user specified with the " + OPT + OPT_USER + " option. You can obfuscate the password with org.mortbay.jetty.security.Password, see http://docs.codehaus.org/display/JETTY/Securing+Passwords"); commandLineOptions.addOption(OPT_SQL, OPT_SQL_L, true, "Runs SQL or {call stored_procedure(?, ?)} or {?=call function(?, ?)}"); commandLineOptions.addOption(OPT_FILE_SFMD, "sfmd", true, "Writes a SFMD file for the given SQL"); commandLineOptions.addOption(OPT_FILE_BINDING, "jdbc", true, "Writes a JDBC binding node file for the given SQL"); commandLineOptions.addOption(OPT_FILE_JDBC, "node", true, "Writes a JDBC node file for the given SQL (internal debugging)"); commandLineOptions.addOption(OPT_WRITE_TO_FILE, "outfile", true, "Writes the SQL output to the given file"); commandLineOptions.addOption(OPT_DESCRIPTION, "description", true, "SFMD description. A default description is used if omited. Example: " + OPT + OPT_DESCRIPTION + " \"Runs such and such\""); commandLineOptions.addOption(OPT_INTERACTIVE, "interactive", false, "Runs in interactive mode, reading and writing from the console, 'go' or '/' sends a statement"); commandLineOptions.addOption(OPT_TIMING, "printTiming", false, "Prints timing information"); commandLineOptions.addOption(OPT_METADATA, "printMetaData", false, "Prints metadata information"); commandLineOptions.addOption(OPT_STACK_TRACE, "printStack", false, "Prints stack traces on errors"); Option option = new Option(OPT_COLUMN_NAMES, "columnNames", true, "Column XML names; default names column labels. Example: " + OPT + OPT_COLUMN_NAMES + " \"cname1 cname2\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_NAMES, "paramNames", true, "Parameter XML names; default names are param1, param2, etc. Example: " + OPT + OPT_PARAM_NAMES + " \"pname1 pname2\""); commandLineOptions.addOption(option); // OptionGroup pOutTypesOptionGroup = new OptionGroup(); String pOutTypesOptionGroupDoc = OPT + OPT_PARAM_TYPES_INT + " and " + OPT + OPT_PARAM_TYPES_NAME + " are mutually exclusive."; final String typesClassName = Types.class.getName(); option = new Option(OPT_PARAM_TYPES_INT, "paramTypes", true, "Parameter types from " + typesClassName + ". " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_INT + " \"-10 12\""); commandLineOptions.addOption(option); option = new Option(OPT_PARAM_TYPES_NAME, "paramTypeNames", true, "Parameter " + typesClassName + " names. " + pOutTypesOptionGroupDoc + " Example: " + OPT + OPT_PARAM_TYPES_NAME + " \"CURSOR VARCHAR\""); commandLineOptions.addOption(option); commandLineOptions.addOptionGroup(pOutTypesOptionGroup); // OptionGroup modesOptionGroup = new OptionGroup(); String modesOptionGroupDoc = OPT + OPT_PARAM_MODES_INT + " and " + OPT + OPT_PARAM_MODES_NAME + " are mutually exclusive."; option = new Option(OPT_PARAM_MODES_INT, "paramModes", true, "Parameters modes (" + ParameterMetaData.parameterModeIn + "=IN, " + ParameterMetaData.parameterModeInOut + "=INOUT, " + ParameterMetaData.parameterModeOut + "=OUT, " + ParameterMetaData.parameterModeUnknown + "=Unknown" + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_INT + " \"" + ParameterMetaData.parameterModeOut + " " + ParameterMetaData.parameterModeIn + "\""); modesOptionGroup.addOption(option); option = new Option(OPT_PARAM_MODES_NAME, "paramModeNames", true, "Parameters mode names (" + PMODES + "). " + modesOptionGroupDoc + " Example for 2 parameters, OUT and IN: " + OPT + OPT_PARAM_MODES_NAME + " \"" + _PMODE_OUT + " " + _PMODE_IN + "\""); modesOptionGroup.addOption(option); commandLineOptions.addOptionGroup(modesOptionGroup); option = new Option(null, OPT_TRIM_L, true, "Trims leading and trailing spaces from all column values. Column XML names can be optionally specified to set which columns to trim."); option.setOptionalArg(true); commandLineOptions.addOption(option); option = new Option(OPT_JDBC_TO_SFMD, OPT_JDBC_TO_SFMD_L, true, "Converts the JDBC file in the first argument to an SMFD file specified in the second argument."); option.setArgs(2); commandLineOptions.addOption(option); new HelpFormatter().printHelp(this.getClass().getName(), commandLineOptions); } public void testLongLineChunking() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description has ReallyLongValuesThatAreLongerThanTheWidthOfTheColumns " + "and also other ReallyLongValuesThatAreHugerAndBiggerThanTheWidthOfTheColumnsBob, " + "yes. "); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 35, this.getClass().getName(), "Header", options, 0, 5, "Footer"); String expected = "usage:" + CR + " org.apache.commons.cli.bug.B" + CR + " ugCLI162Test" + CR + "Header" + CR + "-x,--extralongarg This" + CR + " description" + CR + " has" + CR + " ReallyLongVal" + CR + " uesThatAreLon" + CR + " gerThanTheWid" + CR + " thOfTheColumn" + CR + " s and also" + CR + " other" + CR + " ReallyLongVal" + CR + " uesThatAreHug" + CR + " erAndBiggerTh" + CR + " anTheWidthOfT" + CR + " heColumnsBob," + CR + " yes." + CR + "Footer" + CR; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } public void testLongLineChunkingIndentIgnored() throws ParseException, IOException { Options options = new Options(); options.addOption("x", "extralongarg", false, "This description is Long." ); HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), "Header", options, 0, 5, "Footer"); System.err.println(sw.toString()); String expected = "usage:" + CR + " org.apache.comm" + CR + " ons.cli.bug.Bug" + CR + " CLI162Test" + CR + "Header" + CR + "-x,--extralongarg" + CR + " This description is" + CR + " Long." + CR + "Footer" + CR; assertEquals( "Long arguments did not split as expected", expected, sw.toString() ); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/bug/BugCLI18Test.java100644 0 0 3657 11157377775 23245 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli.bug; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import junit.framework.TestCase; /** * http://issues.apache.org/jira/browse/CLI-18 */ public class BugCLI18Test extends TestCase { public void testCLI18() { Options options = new Options(); options.addOption(new Option("a", "aaa", false, "aaaaaaa")); options.addOption(new Option(null, "bbb", false, "bbbbbbb dksh fkshd fkhs dkfhsdk fhskd hksdks dhfowehfsdhfkjshf skfhkshf sf jkshfk sfh skfh skf f")); options.addOption(new Option("c", null, false, "ccccccc")); HelpFormatter formatter = new HelpFormatter(); StringWriter out = new StringWriter(); formatter.printHelp(new PrintWriter(out), 80, "foobar", "dsfkfsh kdh hsd hsdh fkshdf ksdh fskdh fsdh fkshfk sfdkjhskjh fkjh fkjsh khsdkj hfskdhf skjdfh ksf khf s", options, 2, 2, "blort j jgj j jg jhghjghjgjhgjhg jgjhgj jhg jhg hjg jgjhghjg jhg hjg jhgjg jgjhghjg jg jgjhgjgjg jhg jhgjh" + '\r' + '\n' + "rarrr", true); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/bug/BugCLI71Test.java100644 0 0 6201 11157377775 23230 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli.bug; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.MissingArgumentException; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import junit.framework.TestCase; public class BugCLI71Test extends TestCase { private Options options; private CommandLineParser parser; public void setUp() { options = new Options(); Option algorithm = new Option("a" , "algo", true, "the algorithm which it to perform executing"); algorithm.setArgName("algorithm name"); options.addOption(algorithm); Option key = new Option("k" , "key", true, "the key the setted algorithm uses to process"); algorithm.setArgName("value"); options.addOption(key); parser = new PosixParser(); } public void testBasic() throws Exception { String[] args = new String[] { "-a", "Caesar", "-k", "A" }; CommandLine line = parser.parse( options, args); assertEquals( "Caesar", line.getOptionValue("a") ); assertEquals( "A", line.getOptionValue("k") ); } public void testMistakenArgument() throws Exception { String[] args = new String[] { "-a", "Caesar", "-k", "A" }; CommandLine line = parser.parse( options, args); args = new String[] { "-a", "Caesar", "-k", "a" }; line = parser.parse( options, args); assertEquals( "Caesar", line.getOptionValue("a") ); assertEquals( "a", line.getOptionValue("k") ); } public void testLackOfError() throws Exception { String[] args = new String[] { "-k", "-a", "Caesar" }; try { CommandLine line = parser.parse( options, args); fail("MissingArgumentException expected"); } catch(MissingArgumentException e) { assertEquals("option missing an argument", "k", e.getOption().getOpt()); } } public void testGetsDefaultIfOptional() throws Exception { String[] args = new String[] { "-k", "-a", "Caesar" }; options.getOption("k").setOptionalArg(true); CommandLine line = parser.parse( options, args); assertEquals( "Caesar", line.getOptionValue("a") ); assertEquals( "a", line.getOptionValue("k", "a") ); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/BugsTest.java100644 0 0 30104 11157377775 22155 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; import java.util.Properties; import junit.framework.TestCase; public class BugsTest extends TestCase { public void test11457() throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("verbose").create()); String[] args = new String[]{"--verbose"}; CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); assertTrue(cmd.hasOption("verbose")); } public void test11458() throws Exception { Options options = new Options(); options.addOption( OptionBuilder.withValueSeparator( '=' ).hasArgs().create( 'D' ) ); options.addOption( OptionBuilder.withValueSeparator( ':' ).hasArgs().create( 'p' ) ); String[] args = new String[] { "-DJAVA_HOME=/opt/java" , "-pfile1:file2:file3" }; CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String[] values = cmd.getOptionValues('D'); assertEquals(values[0], "JAVA_HOME"); assertEquals(values[1], "/opt/java"); values = cmd.getOptionValues('p'); assertEquals(values[0], "file1"); assertEquals(values[1], "file2"); assertEquals(values[2], "file3"); Iterator iter = cmd.iterator(); while (iter.hasNext()) { Option opt = (Option) iter.next(); switch (opt.getId()) { case 'D': assertEquals(opt.getValue(0), "JAVA_HOME"); assertEquals(opt.getValue(1), "/opt/java"); break; case 'p': assertEquals(opt.getValue(0), "file1"); assertEquals(opt.getValue(1), "file2"); assertEquals(opt.getValue(2), "file3"); break; default: fail("-D option not found"); } } } public void test11680() throws Exception { Options options = new Options(); options.addOption("f", true, "foobar"); options.addOption("m", true, "missing"); String[] args = new String[]{"-f", "foo"}; CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); cmd.getOptionValue("f", "default f"); cmd.getOptionValue("m", "default m"); } public void test11456() throws Exception { // Posix Options options = new Options(); options.addOption( OptionBuilder.hasOptionalArg().create( 'a' ) ); options.addOption( OptionBuilder.hasArg().create( 'b' ) ); String[] args = new String[] { "-a", "-bvalue" }; CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse( options, args ); assertEquals( cmd.getOptionValue( 'b' ), "value" ); // GNU options = new Options(); options.addOption( OptionBuilder.hasOptionalArg().create( 'a' ) ); options.addOption( OptionBuilder.hasArg().create( 'b' ) ); args = new String[] { "-a", "-b", "value" }; parser = new GnuParser(); cmd = parser.parse( options, args ); assertEquals( cmd.getOptionValue( 'b' ), "value" ); } public void test12210() throws Exception { // create the main options object which will handle the first parameter Options mainOptions = new Options(); // There can be 2 main exclusive options: -exec|-rep // Therefore, place them in an option group String[] argv = new String[] { "-exec", "-exec_opt1", "-exec_opt2" }; OptionGroup grp = new OptionGroup(); grp.addOption(new Option("exec",false,"description for this option")); grp.addOption(new Option("rep",false,"description for this option")); mainOptions.addOptionGroup(grp); // for the exec option, there are 2 options... Options execOptions = new Options(); execOptions.addOption("exec_opt1", false, " desc"); execOptions.addOption("exec_opt2", false, " desc"); // similarly, for rep there are 2 options... Options repOptions = new Options(); repOptions.addOption("repopto", false, "desc"); repOptions.addOption("repoptt", false, "desc"); // create the parser GnuParser parser = new GnuParser(); // finally, parse the arguments: // first parse the main options to see what the user has specified // We set stopAtNonOption to true so it does not touch the remaining // options CommandLine cmd = parser.parse(mainOptions,argv,true); // get the remaining options... argv = cmd.getArgs(); if(cmd.hasOption("exec")) { cmd = parser.parse(execOptions,argv,false); // process the exec_op1 and exec_opt2... assertTrue( cmd.hasOption("exec_opt1") ); assertTrue( cmd.hasOption("exec_opt2") ); } else if(cmd.hasOption("rep")) { cmd = parser.parse(repOptions,argv,false); // process the rep_op1 and rep_opt2... } else { fail( "exec option not found" ); } } public void test13425() throws Exception { Options options = new Options(); Option oldpass = OptionBuilder.withLongOpt( "old-password" ) .withDescription( "Use this option to specify the old password" ) .hasArg() .create( 'o' ); Option newpass = OptionBuilder.withLongOpt( "new-password" ) .withDescription( "Use this option to specify the new password" ) .hasArg() .create( 'n' ); String[] args = { "-o", "-n", "newpassword" }; options.addOption( oldpass ); options.addOption( newpass ); Parser parser = new PosixParser(); try { parser.parse( options, args ); } // catch the exception and leave the method catch( Exception exp ) { assertTrue( exp != null ); return; } fail( "MissingArgumentException not caught." ); } public void test13666() throws Exception { Options options = new Options(); Option dir = OptionBuilder.withDescription( "dir" ).hasArg().create( 'd' ); options.addOption( dir ); final PrintStream oldSystemOut = System.out; try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final PrintStream print = new PrintStream(bytes); // capture this platform's eol symbol print.println(); final String eol = bytes.toString(); bytes.reset(); System.setOut(new PrintStream(bytes)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "dir", options ); assertEquals("usage: dir"+eol+" -d dir"+eol,bytes.toString()); } finally { System.setOut(oldSystemOut); } } public void test13935() throws Exception { OptionGroup directions = new OptionGroup(); Option left = new Option( "l", "left", false, "go left" ); Option right = new Option( "r", "right", false, "go right" ); Option straight = new Option( "s", "straight", false, "go straight" ); Option forward = new Option( "f", "forward", false, "go forward" ); forward.setRequired( true ); directions.addOption( left ); directions.addOption( right ); directions.setRequired( true ); Options opts = new Options(); opts.addOptionGroup( directions ); opts.addOption( straight ); CommandLineParser parser = new PosixParser(); boolean exception = false; String[] args = new String[] { }; try { CommandLine line = parser.parse(opts, args); } catch (ParseException exp) { exception = true; } if (!exception) { fail("Expected exception not caught."); } exception = false; args = new String[] { "-s" }; try { CommandLine line = parser.parse(opts, args); } catch (ParseException exp) { exception = true; } if (!exception) { fail("Expected exception not caught."); } exception = false; args = new String[] { "-s", "-l" }; try { parser.parse(opts, args); } catch (ParseException exp) { fail("Unexpected exception: " + exp.getClass().getName() + ":" + exp.getMessage()); } opts.addOption( forward ); args = new String[] { "-s", "-l", "-f" }; try { parser.parse(opts, args); } catch (ParseException exp) { fail("Unexpected exception: " + exp.getClass().getName() + ":" + exp.getMessage()); } } public void test14786() throws Exception { Option o = OptionBuilder.isRequired().withDescription("test").create("test"); Options opts = new Options(); opts.addOption(o); opts.addOption(o); CommandLineParser parser = new GnuParser(); String[] args = new String[] { "-test" }; CommandLine line = parser.parse( opts, args ); assertTrue( line.hasOption( "test" ) ); } public void test15046() throws Exception { CommandLineParser parser = new PosixParser(); String[] CLI_ARGS = new String[] {"-z", "c"}; Options options = new Options(); options.addOption(new Option("z", "timezone", true, "affected option")); parser.parse(options, CLI_ARGS); //now add conflicting option options.addOption("c", "conflict", true, "conflict option"); CommandLine line = parser.parse(options, CLI_ARGS); assertEquals( line.getOptionValue('z'), "c" ); assertTrue( !line.hasOption("c") ); } public void test15648() throws Exception { CommandLineParser parser = new PosixParser(); final String[] args = new String[] { "-m", "\"Two Words\"" }; Option m = OptionBuilder.hasArgs().create("m"); Options options = new Options(); options.addOption( m ); CommandLine line = parser.parse( options, args ); assertEquals( "Two Words", line.getOptionValue( "m" ) ); } public void test31148() throws ParseException { Option multiArgOption = new Option("o","option with multiple args"); multiArgOption.setArgs(1); Options options = new Options(); options.addOption(multiArgOption); Parser parser = new PosixParser(); String[] args = new String[]{}; Properties props = new Properties(); props.setProperty("o","ovalue"); CommandLine cl = parser.parse(options,args,props); assertTrue(cl.hasOption('o')); assertEquals("ovalue",cl.getOptionValue('o')); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/CommandLineTest.java100644 0 0 4250 11157377775 23426 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.Properties; import junit.framework.TestCase; /** * @author Emmanuel Bourg * @version $Revision: 667595 $, $Date: 2008-06-13 10:03:31 -0700 (Fri, 13 Jun 2008) $ */ public class CommandLineTest extends TestCase { public void testGetOptionProperties() throws Exception { String[] args = new String[] { "-Dparam1=value1", "-Dparam2=value2", "-Dparam3", "-Dparam4=value4", "-D", "--property", "foo=bar" }; Options options = new Options(); options.addOption(OptionBuilder.withValueSeparator().hasOptionalArgs(2).create('D')); options.addOption(OptionBuilder.withValueSeparator().hasArgs(2).withLongOpt("property").create()); Parser parser = new GnuParser(); CommandLine cl = parser.parse(options, args); Properties props = cl.getOptionProperties("D"); assertNotNull("null properties", props); assertEquals("number of properties in " + props, 4, props.size()); assertEquals("property 1", "value1", props.getProperty("param1")); assertEquals("property 2", "value2", props.getProperty("param2")); assertEquals("property 3", "true", props.getProperty("param3")); assertEquals("property 4", "value4", props.getProperty("param4")); assertEquals("property with long format", "bar", cl.getOptionProperties("property").getProperty("foo")); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/GnuParserTest.java100644 0 0 1730 11157377775 23146 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; public class GnuParserTest extends ParserTestCase { public void setUp() { super.setUp(); parser = new GnuParser(); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/HelpFormatterTest.java100644 0 0 43142 11157377775 24037 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Comparator; import junit.framework.TestCase; /** * Test case for the HelpFormatter class * * @author Slawek Zachcial * @author John Keyes ( john at integralsource.com ) * @author brianegge */ public class HelpFormatterTest extends TestCase { private static final String EOL = System.getProperty("line.separator"); public void testFindWrapPos() throws Exception { HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; //text width should be max 8; the wrap position is 7 assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0)); //starting from 8 must give -1 - the wrap pos is after end assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8)); //if there is no a good position before width to make a wrapping look for the next one text = "aaaa aa"; assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0)); } public void testPrintWrapped() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); String text = "This is a test."; String expected = "This is a" + hf.getNewLine() + "test."; hf.renderWrappedText(sb, 12, 0, text); assertEquals("single line text", expected, sb.toString()); sb.setLength(0); expected = "This is a" + hf.getNewLine() + " test."; hf.renderWrappedText(sb, 12, 4, text); assertEquals("single line padded text", expected, sb.toString()); text = " -p,--period PERIOD is time duration of form " + "DATE[-DATE] where DATE has form YYYY[MM[DD]]"; sb.setLength(0); expected = " -p,--period PERIOD is time duration of" + hf.getNewLine() + " form DATE[-DATE] where DATE" + hf.getNewLine() + " has form YYYY[MM[DD]]"; hf.renderWrappedText(sb, 53, 24, text); assertEquals("single line padded text 2", expected, sb.toString()); text = "aaaa aaaa aaaa" + hf.getNewLine() + "aaaaaa" + hf.getNewLine() + "aaaaa"; expected = text; sb.setLength(0); hf.renderWrappedText(sb, 16, 0, text); assertEquals("multi line text", expected, sb.toString()); expected = "aaaa aaaa aaaa" + hf.getNewLine() + " aaaaaa" + hf.getNewLine() + " aaaaa"; sb.setLength(0); hf.renderWrappedText(sb, 16, 4, text); assertEquals("multi-line padded text", expected, sb.toString()); } public void testPrintOptions() throws Exception { StringBuffer sb = new StringBuffer(); HelpFormatter hf = new HelpFormatter(); final int leftPad = 1; final int descPad = 3; final String lpad = hf.createPadding(leftPad); final String dpad = hf.createPadding(descPad); Options options = null; String expected = null; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa"; hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("simple non-wrapped option", expected, sb.toString()); int nextLineTabStop = leftPad + descPad + "-a".length(); expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "aaaa aaaa"; sb.setLength(0); hf.renderOptions(sb, nextLineTabStop + 17, options, leftPad, descPad); assertEquals("simple wrapped option", expected, sb.toString()); options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 60, options, leftPad, descPad); assertEquals("long non-wrapped option", expected, sb.toString()); nextLineTabStop = leftPad + descPad + "-a,--aaa".length(); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("long wrapped option", expected, sb.toString()); options = new Options(). addOption("a", "aaa", false, "dddd dddd dddd dddd"). addOption("b", false, "feeee eeee eeee eeee"); expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.getNewLine() + lpad + "-b " + dpad + "feeee eeee" + hf.getNewLine() + hf.createPadding(nextLineTabStop) + "eeee eeee"; sb.setLength(0); hf.renderOptions(sb, 25, options, leftPad, descPad); assertEquals("multiple wrapped options", expected, sb.toString()); } public void testPrintHelpWithEmptySyntax() { HelpFormatter formatter = new HelpFormatter(); try { formatter.printHelp(null, new Options()); fail("null command line syntax should be rejected"); } catch (IllegalArgumentException e) { // expected } try { formatter.printHelp("", new Options()); fail("empty command line syntax should be rejected"); } catch (IllegalArgumentException e) { // expected } } public void testAutomaticUsage() throws Exception { HelpFormatter hf = new HelpFormatter(); Options options = null; String expected = "usage: app [-a]"; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(out); options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa"); hf.printUsage(pw, 60, "app", options); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); expected = "usage: app [-a] [-b]"; options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa") .addOption("b", false, "bbb"); hf.printUsage(pw, 60, "app", options); pw.flush(); assertEquals("simple auto usage", expected, out.toString().trim()); out.reset(); } // This test ensures the options are properly sorted // See https://issues.apache.org/jira/browse/CLI-131 public void testPrintUsage() { Option optionA = new Option("a", "first"); Option optionB = new Option("b", "second"); Option optionC = new Option("c", "third"); Options opts = new Options(); opts.addOption(optionA); opts.addOption(optionB); opts.addOption(optionC); HelpFormatter helpFormatter = new HelpFormatter(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(bytesOut); helpFormatter.printUsage(printWriter, 80, "app", opts); printWriter.close(); assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString()); } // uses the test for CLI-131 to implement CLI-155 public void testPrintSortedUsage() { Options opts = new Options(); opts.addOption(new Option("a", "first")); opts.addOption(new Option("b", "second")); opts.addOption(new Option("c", "third")); HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setOptionComparator(new Comparator() { public int compare(Object o1, Object o2) { // reverses the fuctionality of the default comparator Option opt1 = (Option) o1; Option opt2 = (Option) o2; return opt2.getKey().compareToIgnoreCase(opt1.getKey()); } }); StringWriter out = new StringWriter(); helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts); assertEquals("usage: app [-c] [-b] [-a]" + EOL, out.toString()); } public void testPrintSortedUsageWithNullComparator() { Options opts = new Options(); opts.addOption(new Option("a", "first")); opts.addOption(new Option("b", "second")); opts.addOption(new Option("c", "third")); HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setOptionComparator(null); StringWriter out = new StringWriter(); helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts); assertEquals("usage: app [-a] [-b] [-c]" + EOL, out.toString()); } public void testPrintOptionGroupUsage() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create("a")); group.addOption(OptionBuilder.create("b")); group.addOption(OptionBuilder.create("c")); Options options = new Options(); options.addOptionGroup(group); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app [-a | -b | -c]" + EOL, out.toString()); } public void testPrintRequiredOptionGroupUsage() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create("a")); group.addOption(OptionBuilder.create("b")); group.addOption(OptionBuilder.create("c")); group.setRequired(true); Options options = new Options(); options.addOptionGroup(group); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app -a | -b | -c" + EOL, out.toString()); } public void testPrintOptionWithEmptyArgNameUsage() { Option option = new Option("f", true, null); option.setArgName(""); option.setRequired(true); Options options = new Options(); options.addOption(option); StringWriter out = new StringWriter(); HelpFormatter formatter = new HelpFormatter(); formatter.printUsage(new PrintWriter(out), 80, "app", options); assertEquals("usage: app -f" + EOL, out.toString()); } public void testRtrim() { HelpFormatter formatter = new HelpFormatter(); assertEquals(null, formatter.rtrim(null)); assertEquals("", formatter.rtrim("")); assertEquals(" foo", formatter.rtrim(" foo ")); } public void testAccessors() { HelpFormatter formatter = new HelpFormatter(); formatter.setArgName("argname"); assertEquals("arg name", "argname", formatter.getArgName()); formatter.setDescPadding(3); assertEquals("desc padding", 3, formatter.getDescPadding()); formatter.setLeftPadding(7); assertEquals("left padding", 7, formatter.getLeftPadding()); formatter.setLongOptPrefix("~~"); assertEquals("long opt prefix", "~~", formatter.getLongOptPrefix()); formatter.setNewLine("\n"); assertEquals("new line", "\n", formatter.getNewLine()); formatter.setOptPrefix("~"); assertEquals("opt prefix", "~", formatter.getOptPrefix()); formatter.setSyntaxPrefix("-> "); assertEquals("syntax prefix", "-> ", formatter.getSyntaxPrefix()); formatter.setWidth(80); assertEquals("width", 80, formatter.getWidth()); } public void testHeaderStartingWithLineSeparator() { // related to Bugzilla #21215 Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); String header = EOL + "Header"; String footer = "Footer"; StringWriter out = new StringWriter(); formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true); assertEquals( "usage: foobar" + EOL + "" + EOL + "Header" + EOL + "" + EOL + "Footer" + EOL , out.toString()); } public void testOptionWithoutShortFormat() { // related to Bugzilla #19383 (CLI-67) Options options = new Options(); options.addOption(new Option("a", "aaa", false, "aaaaaaa")); options.addOption(new Option(null, "bbb", false, "bbbbbbb")); options.addOption(new Option("c", null, false, "ccccccc")); HelpFormatter formatter = new HelpFormatter(); StringWriter out = new StringWriter(); formatter.printHelp(new PrintWriter(out), 80, "foobar", "", options, 2, 2, "", true); assertEquals( "usage: foobar [-a] [--bbb] [-c]" + EOL + " -a,--aaa aaaaaaa" + EOL + " --bbb bbbbbbb" + EOL + " -c ccccccc" + EOL , out.toString()); } public void testOptionWithoutShortFormat2() { // related to Bugzilla #27635 (CLI-26) Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print version information"); Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items"); Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items"); Option timeLimit = OptionBuilder.withLongOpt("limit") .hasArg() .withValueSeparator() .withDescription("Set time limit for execution, in mintues") .create("l"); Option age = OptionBuilder.withLongOpt("age") .hasArg() .withValueSeparator() .withDescription("Age (in days) of cache item before being recomputed") .create("a"); Option server = OptionBuilder.withLongOpt("server") .hasArg() .withValueSeparator() .withDescription("The NLT server address") .create("s"); Option numResults = OptionBuilder.withLongOpt("results") .hasArg() .withValueSeparator() .withDescription("Number of results per item") .create("r"); Option configFile = OptionBuilder.withLongOpt("config") .hasArg() .withValueSeparator() .withDescription("Use the specified configuration file") .create(); Options mOptions = new Options(); mOptions.addOption(help); mOptions.addOption(version); mOptions.addOption(newRun); mOptions.addOption(trackerRun); mOptions.addOption(timeLimit); mOptions.addOption(age); mOptions.addOption(server); mOptions.addOption(numResults); mOptions.addOption(configFile); HelpFormatter formatter = new HelpFormatter(); final String EOL = System.getProperty("line.separator"); StringWriter out = new StringWriter(); formatter.printHelp(new PrintWriter(out),80,"commandline","header",mOptions,2,2,"footer",true); assertEquals( "usage: commandline [-a ] [--config ] [-h] [-l ] [-n] [-r ]" + EOL + " [-s ] [-t] [-v]" + EOL + "header"+EOL+ " -a,--age Age (in days) of cache item before being recomputed"+EOL+ " --config Use the specified configuration file"+EOL+ " -h,--help print this message"+EOL+ " -l,--limit Set time limit for execution, in mintues"+EOL+ " -n,--new Create NLT cache entries only for new items"+EOL+ " -r,--results Number of results per item"+EOL+ " -s,--server The NLT server address"+EOL+ " -t,--tracker Create NLT cache entries only for tracker items"+EOL+ " -v,--version print version information"+EOL+ "footer"+EOL ,out.toString()); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/OptionBuilderTest.java100644 0 0 14353 11157377775 24044 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import junit.framework.TestCase; public class OptionBuilderTest extends TestCase { public void testCompleteOption( ) { Option simple = OptionBuilder.withLongOpt( "simple option") .hasArg( ) .isRequired( ) .hasArgs( ) .withType( new Float( 10 ) ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); } public void testTwoCompleteOptions( ) { Option simple = OptionBuilder.withLongOpt( "simple option") .hasArg( ) .isRequired( ) .hasArgs( ) .withType( new Float( 10 ) ) .withDescription( "this is a simple option" ) .create( 's' ); assertEquals( "s", simple.getOpt() ); assertEquals( "simple option", simple.getLongOpt() ); assertEquals( "this is a simple option", simple.getDescription() ); assertEquals( simple.getType().getClass(), Float.class ); assertTrue( simple.hasArg() ); assertTrue( simple.isRequired() ); assertTrue( simple.hasArgs() ); simple = OptionBuilder.withLongOpt( "dimple option") .hasArg( ) .withDescription( "this is a dimple option" ) .create( 'd' ); assertEquals( "d", simple.getOpt() ); assertEquals( "dimple option", simple.getLongOpt() ); assertEquals( "this is a dimple option", simple.getDescription() ); assertNull( simple.getType() ); assertTrue( simple.hasArg() ); assertTrue( !simple.isRequired() ); assertTrue( !simple.hasArgs() ); } public void testBaseOptionCharOpt() { Option base = OptionBuilder.withDescription( "option description") .create( 'o' ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testBaseOptionStringOpt() { Option base = OptionBuilder.withDescription( "option description") .create( "o" ); assertEquals( "o", base.getOpt() ); assertEquals( "option description", base.getDescription() ); assertTrue( !base.hasArg() ); } public void testSpecialOptChars() throws Exception { // '?' Option opt1 = OptionBuilder.withDescription("help options").create('?'); assertEquals("?", opt1.getOpt()); // '@' Option opt2 = OptionBuilder.withDescription("read from stdin").create('@'); assertEquals("@", opt2.getOpt()); } public void testOptionArgNumbers() { Option opt = OptionBuilder.withDescription( "option description" ) .hasArgs( 2 ) .create( 'o' ); assertEquals( 2, opt.getArgs() ); } public void testIllegalOptions() { // bad single character option try { OptionBuilder.withDescription( "option description" ).create( '"' ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // bad character in option string try { Option opt = OptionBuilder.create( "opt`" ); fail( "IllegalArgumentException not caught" ); } catch( IllegalArgumentException exp ) { // success } // valid option try { Option opt = OptionBuilder.create( "opt" ); // success } catch( IllegalArgumentException exp ) { fail( "IllegalArgumentException caught" ); } } public void testCreateIncompleteOption() { try { OptionBuilder.hasArg().create(); fail("Incomplete option should be rejected"); } catch (IllegalArgumentException e) { // expected // implicitly reset the builder OptionBuilder.create( "opt" ); } } public void testBuilderIsResettedAlways() { try { OptionBuilder.withDescription("JUnit").create('"'); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); try { OptionBuilder.withDescription("JUnit").create(); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // expected } assertNull("we inherited a description", OptionBuilder.create('x').getDescription()); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/OptionGroupTest.java100644 0 0 21266 11157377775 23553 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import junit.framework.TestCase; /** * @author John Keyes (john at integralsource.com) * @version $Revision: 751120 $ */ public class OptionGroupTest extends TestCase { private Options _options = null; private CommandLineParser parser = new PosixParser(); public void setUp() { Option file = new Option( "f", "file", false, "file to process" ); Option dir = new Option( "d", "directory", false, "directory to process" ); OptionGroup group = new OptionGroup(); group.addOption( file ); group.addOption( dir ); _options = new Options().addOptionGroup( group ); Option section = new Option( "s", "section", false, "section to process" ); Option chapter = new Option( "c", "chapter", false, "chapter to process" ); OptionGroup group2 = new OptionGroup(); group2.addOption( section ); group2.addOption( chapter ); _options.addOptionGroup( group2 ); Option importOpt = new Option( null, "import", false, "section to process" ); Option exportOpt = new Option( null, "export", false, "chapter to process" ); OptionGroup group3 = new OptionGroup(); group3.addOption( importOpt ); group3.addOption( exportOpt ); _options.addOptionGroup( group3 ); _options.addOption( "r", "revision", false, "revision number" ); } public void testSingleOptionFromGroup() throws Exception { String[] args = new String[] { "-f" }; CommandLine cl = parser.parse( _options, args); assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); assertTrue( "Confirm -f is set", cl.hasOption("f") ); assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); } public void testSingleOption() throws Exception { String[] args = new String[] { "-r" }; CommandLine cl = parser.parse( _options, args); assertTrue( "Confirm -r is set", cl.hasOption("r") ); assertTrue( "Confirm -f is NOT set", !cl.hasOption("f") ); assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); } public void testTwoValidOptions() throws Exception { String[] args = new String[] { "-r", "-f" }; CommandLine cl = parser.parse( _options, args); assertTrue( "Confirm -r is set", cl.hasOption("r") ); assertTrue( "Confirm -f is set", cl.hasOption("f") ); assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); } public void testSingleLongOption() throws Exception { String[] args = new String[] { "--file" }; CommandLine cl = parser.parse( _options, args); assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); assertTrue( "Confirm -f is set", cl.hasOption("f") ); assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); } public void testTwoValidLongOptions() throws Exception { String[] args = new String[] { "--revision", "--file" }; CommandLine cl = parser.parse( _options, args); assertTrue( "Confirm -r is set", cl.hasOption("r") ); assertTrue( "Confirm -f is set", cl.hasOption("f") ); assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); assertTrue( "Confirm no extra args", cl.getArgList().size() == 0); } public void testNoOptionsExtraArgs() throws Exception { String[] args = new String[] { "arg1", "arg2" }; CommandLine cl = parser.parse( _options, args); assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); assertTrue( "Confirm -f is NOT set", !cl.hasOption("f") ); assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); assertTrue( "Confirm -s is NOT set", !cl.hasOption("s") ); assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); assertTrue( "Confirm TWO extra args", cl.getArgList().size() == 2); } public void testTwoOptionsFromGroup() throws Exception { String[] args = new String[] { "-f", "-d" }; try { parser.parse( _options, args); fail( "two arguments from group not allowed" ); } catch (AlreadySelectedException e) { assertNotNull("null option group", e.getOptionGroup()); assertEquals("selected option", "f", e.getOptionGroup().getSelected()); assertEquals("option", "d", e.getOption().getOpt()); } } public void testTwoLongOptionsFromGroup() throws Exception { String[] args = new String[] { "--file", "--directory" }; try { parser.parse(_options, args); fail( "two arguments from group not allowed" ); } catch (AlreadySelectedException e) { assertNotNull("null option group", e.getOptionGroup()); assertEquals("selected option", "f", e.getOptionGroup().getSelected()); assertEquals("option", "d", e.getOption().getOpt()); } } public void testTwoOptionsFromDifferentGroup() throws Exception { String[] args = new String[] { "-f", "-s" }; CommandLine cl = parser.parse( _options, args); assertTrue( "Confirm -r is NOT set", !cl.hasOption("r") ); assertTrue( "Confirm -f is set", cl.hasOption("f") ); assertTrue( "Confirm -d is NOT set", !cl.hasOption("d") ); assertTrue( "Confirm -s is set", cl.hasOption("s") ); assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") ); assertTrue( "Confirm NO extra args", cl.getArgList().size() == 0); } public void testValidLongOnlyOptions() throws Exception { CommandLine cl1 = parser.parse(_options, new String[]{"--export"}); assertTrue("Confirm --export is set", cl1.hasOption("export")); CommandLine cl2 = parser.parse(_options, new String[]{"--import"}); assertTrue("Confirm --import is set", cl2.hasOption("import")); } public void testToString() { OptionGroup group1 = new OptionGroup(); group1.addOption(new Option(null, "foo", false, "Foo")); group1.addOption(new Option(null, "bar", false, "Bar")); if (!"[--bar Bar, --foo Foo]".equals(group1.toString())) { assertEquals("[--foo Foo, --bar Bar]", group1.toString()); } OptionGroup group2 = new OptionGroup(); group2.addOption(new Option("f", "foo", false, "Foo")); group2.addOption(new Option("b", "bar", false, "Bar")); if (!"[-b Bar, -f Foo]".equals(group2.toString())) { assertEquals("[-f Foo, -b Bar]", group2.toString()); } } public void testGetNames() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create('a')); group.addOption(OptionBuilder.create('b')); assertNotNull("null names", group.getNames()); assertEquals(2, group.getNames().size()); assertTrue(group.getNames().contains("a")); assertTrue(group.getNames().contains("b")); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/OptionsTest.java100644 0 0 12565 11157377775 22723 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.ArrayList; import java.util.Collection; import junit.framework.TestCase; /** * @author Rob Oxspring roxspring@apache.org * @version $Revision: 680311 $ */ public class OptionsTest extends TestCase { public void testSimple() { Options opts = new Options(); opts.addOption("a", false, "toggle -a"); opts.addOption("b", true, "toggle -b"); assertTrue(opts.hasOption("a")); assertTrue(opts.hasOption("b")); } public void testDuplicateSimple() { Options opts = new Options(); opts.addOption("a", false, "toggle -a"); opts.addOption("a", true, "toggle -a*"); assertEquals("last one in wins", "toggle -a*", opts.getOption("a").getDescription()); } public void testLong() { Options opts = new Options(); opts.addOption("a", "--a", false, "toggle -a"); opts.addOption("b", "--b", true, "set -b"); assertTrue(opts.hasOption("a")); assertTrue(opts.hasOption("b")); } public void testDuplicateLong() { Options opts = new Options(); opts.addOption("a", "--a", false, "toggle -a"); opts.addOption("a", "--a", false, "toggle -a*"); assertEquals("last one in wins", "toggle -a*", opts.getOption("a").getDescription()); } public void testHelpOptions() { Option longOnly1 = OptionBuilder.withLongOpt("long-only1").create(); Option longOnly2 = OptionBuilder.withLongOpt("long-only2").create(); Option shortOnly1 = OptionBuilder.create("1"); Option shortOnly2 = OptionBuilder.create("2"); Option bothA = OptionBuilder.withLongOpt("bothA").create("a"); Option bothB = OptionBuilder.withLongOpt("bothB").create("b"); Options options = new Options(); options.addOption(longOnly1); options.addOption(longOnly2); options.addOption(shortOnly1); options.addOption(shortOnly2); options.addOption(bothA); options.addOption(bothB); Collection allOptions = new ArrayList(); allOptions.add(longOnly1); allOptions.add(longOnly2); allOptions.add(shortOnly1); allOptions.add(shortOnly2); allOptions.add(bothA); allOptions.add(bothB); Collection helpOptions = options.helpOptions(); assertTrue("Everything in all should be in help", helpOptions.containsAll(allOptions)); assertTrue("Everything in help should be in all", allOptions.containsAll(helpOptions)); } public void testMissingOptionException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required option: f", e.getMessage()); } } public void testMissingOptionsException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); options.addOption(OptionBuilder.isRequired().create("x")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required options: f, x", e.getMessage()); } } public void testToString() { Options options = new Options(); options.addOption("f", "foo", true, "Foo"); options.addOption("b", "bar", false, "Bar"); String s = options.toString(); assertNotNull("null string returned", s); assertTrue("foo option missing", s.toLowerCase().indexOf("foo") != -1); assertTrue("bar option missing", s.toLowerCase().indexOf("bar") != -1); } public void testGetOptionsGroups() { Options options = new Options(); OptionGroup group1 = new OptionGroup(); group1.addOption(OptionBuilder.create('a')); group1.addOption(OptionBuilder.create('b')); OptionGroup group2 = new OptionGroup(); group2.addOption(OptionBuilder.create('x')); group2.addOption(OptionBuilder.create('y')); options.addOptionGroup(group1); options.addOptionGroup(group2); assertNotNull(options.getOptionGroups()); assertEquals(2, options.getOptionGroups().size()); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/OptionTest.java100644 0 0 10216 11157377775 22527 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import junit.framework.TestCase; /** * @author brianegge */ public class OptionTest extends TestCase { private static class TestOption extends Option { public TestOption(String opt, boolean hasArg, String description) throws IllegalArgumentException { super(opt, hasArg, description); } public boolean addValue(String value) { addValueForProcessing(value); return true; } } public void testClear() { TestOption option = new TestOption("x", true, ""); assertEquals(0, option.getValuesList().size()); option.addValue("a"); assertEquals(1, option.getValuesList().size()); option.clearValues(); assertEquals(0, option.getValuesList().size()); } // See http://issues.apache.org/jira/browse/CLI-21 public void testClone() throws CloneNotSupportedException { TestOption a = new TestOption("a", true, ""); TestOption b = (TestOption) a.clone(); assertEquals(a, b); assertNotSame(a, b); a.setDescription("a"); assertEquals("", b.getDescription()); b.setArgs(2); b.addValue("b1"); b.addValue("b2"); assertEquals(1, a.getArgs()); assertEquals(0, a.getValuesList().size()); assertEquals(2, b.getValues().length); } private static class DefaultOption extends Option { private final String defaultValue; public DefaultOption(String opt, String description, String defaultValue) throws IllegalArgumentException { super(opt, true, description); this.defaultValue = defaultValue; } public String getValue() { return super.getValue() != null ? super.getValue() : defaultValue; } } public void testSubclass() throws CloneNotSupportedException { Option option = new DefaultOption("f", "file", "myfile.txt"); Option clone = (Option) option.clone(); assertEquals("myfile.txt", clone.getValue()); assertEquals(DefaultOption.class, clone.getClass()); } public void testHasArgName() { Option option = new Option("f", null); option.setArgName(null); assertFalse(option.hasArgName()); option.setArgName(""); assertFalse(option.hasArgName()); option.setArgName("file"); assertTrue(option.hasArgName()); } public void testHasArgs() { Option option = new Option("f", null); option.setArgs(0); assertFalse(option.hasArgs()); option.setArgs(1); assertFalse(option.hasArgs()); option.setArgs(10); assertTrue(option.hasArgs()); option.setArgs(Option.UNLIMITED_VALUES); assertTrue(option.hasArgs()); option.setArgs(Option.UNINITIALIZED); assertFalse(option.hasArgs()); } public void testGetValue() { Option option = new Option("f", null); option.setArgs(Option.UNLIMITED_VALUES); assertEquals("default", option.getValue("default")); assertEquals(null, option.getValue(0)); option.addValueForProcessing("foo"); assertEquals("foo", option.getValue()); assertEquals("foo", option.getValue(0)); assertEquals("foo", option.getValue("default")); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/ParseRequiredTest.java100644 0 0 11147 11157377775 24036 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import junit.framework.TestCase; /** * @author John Keyes (john at integralsource.com) * @version $Revision: 678662 $ */ public class ParseRequiredTest extends TestCase { private Options _options = null; private CommandLineParser parser = new PosixParser(); public void setUp() { _options = new Options() .addOption("a", "enable-a", false, "turn [a] on or off") .addOption( OptionBuilder.withLongOpt( "bfile" ) .hasArg() .isRequired() .withDescription( "set the value of [b]" ) .create( 'b' ) ); } public void testWithRequiredOption() throws Exception { String[] args = new String[] { "-b", "file" }; CommandLine cl = parser.parse(_options,args); assertTrue( "Confirm -a is NOT set", !cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); } public void testOptionAndRequiredOption() throws Exception { String[] args = new String[] { "-a", "-b", "file" }; CommandLine cl = parser.parse(_options,args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("file") ); assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0); } public void testMissingRequiredOption() { String[] args = new String[] { "-a" }; try { CommandLine cl = parser.parse(_options,args); fail( "exception should have been thrown" ); } catch (MissingOptionException e) { assertEquals( "Incorrect exception message", "Missing required option: b", e.getMessage() ); assertTrue(e.getMissingOptions().contains("b")); } catch (ParseException e) { fail( "expected to catch MissingOptionException" ); } } public void testMissingRequiredOptions() { String[] args = new String[] { "-a" }; _options.addOption( OptionBuilder.withLongOpt( "cfile" ) .hasArg() .isRequired() .withDescription( "set the value of [c]" ) .create( 'c' ) ); try { CommandLine cl = parser.parse(_options,args); fail( "exception should have been thrown" ); } catch (MissingOptionException e) { assertEquals( "Incorrect exception message", "Missing required options: b, c", e.getMessage() ); assertTrue(e.getMissingOptions().contains("b")); assertTrue(e.getMissingOptions().contains("c")); } catch (ParseException e) { fail( "expected to catch MissingOptionException" ); } } public void testReuseOptionsTwice() throws Exception { Options opts = new Options(); opts.addOption(OptionBuilder.isRequired().create('v')); GnuParser parser = new GnuParser(); // first parsing parser.parse(opts, new String[] { "-v" }); try { // second parsing, with the same Options instance and an invalid command line parser.parse(opts, new String[0]); fail("MissingOptionException not thrown"); } catch (MissingOptionException e) { // expected } } } commons-cli-1.2-src/src/test/org/apache/commons/cli/ParserTestCase.java100644 0 0 26014 11157377775 23312 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; /** * Abstract test case testing common parser features. * * @author Emmanuel Bourg * @version $Revision: 695672 $, $Date: 2008-09-15 15:19:11 -0700 (Mon, 15 Sep 2008) $ */ public abstract class ParserTestCase extends TestCase { protected Parser parser; protected Options options; public void setUp() { options = new Options() .addOption("a", "enable-a", false, "turn [a] on or off") .addOption("b", "bfile", true, "set the value of [b]") .addOption("c", "copt", false, "turn [c] on or off"); } public void testSimpleShort() throws Exception { String[] args = new String[] { "-a", "-b", "toast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue("Confirm -a is set", cl.hasOption("a")); assertTrue("Confirm -b is set", cl.hasOption("b")); assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast")); assertTrue("Confirm size of extra args", cl.getArgList().size() == 2); } public void testSimpleLong() throws Exception { String[] args = new String[] { "--enable-a", "--bfile", "toast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm arg of --bfile", cl.getOptionValue( "bfile" ).equals( "toast" ) ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testMultiple() throws Exception { String[] args = new String[] { "-c", "foobar", "-b", "toast" }; CommandLine cl = parser.parse(options, args, true); assertTrue("Confirm -c is set", cl.hasOption("c")); assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); cl = parser.parse(options, cl.getArgs()); assertTrue("Confirm -c is not set", !cl.hasOption("c")); assertTrue("Confirm -b is set", cl.hasOption("b")); assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast")); assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar")); } public void testMultipleWithLong() throws Exception { String[] args = new String[] { "--copt", "foobar", "--bfile", "toast" }; CommandLine cl = parser.parse(options, args, true); assertTrue("Confirm -c is set", cl.hasOption("c")); assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); cl = parser.parse(options, cl.getArgs()); assertTrue("Confirm -c is not set", !cl.hasOption("c")); assertTrue("Confirm -b is set", cl.hasOption("b")); assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast")); assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar")); } public void testUnrecognizedOption() throws Exception { String[] args = new String[] { "-a", "-d", "-b", "toast", "foo", "bar" }; try { parser.parse(options, args); fail("UnrecognizedOptionException wasn't thrown"); } catch (UnrecognizedOptionException e) { assertEquals("-d", e.getOption()); } } public void testMissingArg() throws Exception { String[] args = new String[] { "-b" }; boolean caught = false; try { parser.parse(options, args); } catch (MissingArgumentException e) { caught = true; assertEquals("option missing an argument", "b", e.getOption().getOpt()); } assertTrue( "Confirm MissingArgumentException caught", caught ); } public void testDoubleDash() throws Exception { String[] args = new String[] { "--copt", "--", "-b", "toast" }; CommandLine cl = parser.parse(options, args); assertTrue("Confirm -c is set", cl.hasOption("c")); assertTrue("Confirm -b is not set", !cl.hasOption("b")); assertTrue("Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); } public void testSingleDash() throws Exception { String[] args = new String[] { "--copt", "-b", "-", "-a", "-" }; CommandLine cl = parser.parse(options, args); assertTrue("Confirm -a is set", cl.hasOption("a")); assertTrue("Confirm -b is set", cl.hasOption("b")); assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("-")); assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-")); } public void testStopAtUnexpectedArg() throws Exception { String[] args = new String[] { "-c", "foober", "-b", "toast" }; CommandLine cl = parser.parse(options, args, true); assertTrue("Confirm -c is set", cl.hasOption("c")); assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); } public void testStopAtExpectedArg() throws Exception { String[] args = new String[]{"-b", "foo"}; CommandLine cl = parser.parse(options, args, true); assertTrue("Confirm -b is set", cl.hasOption('b')); assertEquals("Confirm -b is set", "foo", cl.getOptionValue('b')); assertTrue("Confirm no extra args: " + cl.getArgList().size(), cl.getArgList().size() == 0); } public void testStopAtNonOptionShort() throws Exception { String[] args = new String[]{"-z", "-a", "-btoast"}; CommandLine cl = parser.parse(options, args, true); assertFalse("Confirm -a is not set", cl.hasOption("a")); assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); } public void testStopAtNonOptionLong() throws Exception { String[] args = new String[]{"--zop==1", "-abtoast", "--b=bar"}; CommandLine cl = parser.parse(options, args, true); assertFalse("Confirm -a is not set", cl.hasOption("a")); assertFalse("Confirm -b is not set", cl.hasOption("b")); assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3); } public void testNegativeArgument() throws Exception { String[] args = new String[] { "-b", "-1"} ; CommandLine cl = parser.parse(options, args); assertEquals("-1", cl.getOptionValue("b")); } public void testArgumentStartingWithHyphen() throws Exception { String[] args = new String[]{"-b", "-foo"}; CommandLine cl = parser.parse(options, args); assertEquals("-foo", cl.getOptionValue("b")); } public void testShortWithEqual() throws Exception { String[] args = new String[] { "-f=bar" }; Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f')); CommandLine cl = parser.parse(options, args); assertEquals("bar", cl.getOptionValue("foo")); } public void testShortWithoutEqual() throws Exception { String[] args = new String[] { "-fbar" }; Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f')); CommandLine cl = parser.parse(options, args); assertEquals("bar", cl.getOptionValue("foo")); } public void testLongWithEqual() throws Exception { String[] args = new String[] { "--foo=bar" }; Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f')); CommandLine cl = parser.parse(options, args); assertEquals("bar", cl.getOptionValue("foo")); } public void testLongWithEqualSingleDash() throws Exception { String[] args = new String[] { "-foo=bar" }; Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f')); CommandLine cl = parser.parse(options, args); assertEquals("bar", cl.getOptionValue("foo")); } public void testPropertiesOption() throws Exception { String[] args = new String[] { "-Jsource=1.5", "-J", "target", "1.5", "foo" }; Options options = new Options(); options.addOption(OptionBuilder.withValueSeparator().hasArgs(2).create('J')); CommandLine cl = parser.parse(options, args); List values = Arrays.asList(cl.getOptionValues("J")); assertNotNull("null values", values); assertEquals("number of values", 4, values.size()); assertEquals("value 1", "source", values.get(0)); assertEquals("value 2", "1.5", values.get(1)); assertEquals("value 3", "target", values.get(2)); assertEquals("value 4", "1.5", values.get(3)); List argsleft = cl.getArgList(); assertEquals("Should be 1 arg left",1,argsleft.size()); assertEquals("Expecting foo","foo",argsleft.get(0)); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java100644 0 0 16716 11157377775 25407 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.io.File; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.Vector; import junit.framework.TestCase; /** * Test case for the PatternOptionBuilder class * * @version $Revision: 741427 $, $Date: 2009-02-05 22:11:37 -0800 (Thu, 05 Feb 2009) $ */ public class PatternOptionBuilderTest extends TestCase { public void testSimplePattern() throws Exception { Options options = PatternOptionBuilder.parsePattern("a:b@cde>f+n%t/m*z#"); String[] args = new String[] {"-c", "-a", "foo", "-b", "java.util.Vector", "-e", "build.xml", "-f", "java.util.Calendar", "-n", "4.5", "-t", "http://commons.apache.org", "-z", "Thu Jun 06 17:48:57 EDT 2002", "-m", "test*"}; CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, args); assertEquals("flag a", "foo", line.getOptionValue("a")); assertEquals("string flag a", "foo", line.getOptionObject("a")); assertEquals("object flag b", new Vector(), line.getOptionObject("b")); assertTrue("boolean true flag c", line.hasOption("c")); assertFalse("boolean false flag d", line.hasOption("d")); assertEquals("file flag e", new File("build.xml"), line.getOptionObject("e")); assertEquals("class flag f", Calendar.class, line.getOptionObject("f")); assertEquals("number flag n", new Double(4.5), line.getOptionObject("n")); assertEquals("url flag t", new URL("http://commons.apache.org"), line.getOptionObject("t")); // tests the char methods of CommandLine that delegate to the String methods assertEquals("flag a", "foo", line.getOptionValue('a')); assertEquals("string flag a", "foo", line.getOptionObject('a')); assertEquals("object flag b", new Vector(), line.getOptionObject('b')); assertTrue("boolean true flag c", line.hasOption('c')); assertFalse("boolean false flag d", line.hasOption('d')); assertEquals("file flag e", new File("build.xml"), line.getOptionObject('e')); assertEquals("class flag f", Calendar.class, line.getOptionObject('f')); assertEquals("number flag n", new Double(4.5), line.getOptionObject('n')); assertEquals("url flag t", new URL("http://commons.apache.org"), line.getOptionObject('t')); // FILES NOT SUPPORTED YET try { assertEquals("files flag m", new File[0], line.getOptionObject('m')); fail("Multiple files are not supported yet, should have failed"); } catch(UnsupportedOperationException uoe) { // expected } // DATES NOT SUPPORTED YET try { assertEquals("date flag z", new Date(1023400137276L), line.getOptionObject('z')); fail("Date is not supported yet, should have failed"); } catch(UnsupportedOperationException uoe) { // expected } } public void testEmptyPattern() throws Exception { Options options = PatternOptionBuilder.parsePattern(""); assertTrue(options.getOptions().isEmpty()); } public void testUntypedPattern() throws Exception { Options options = PatternOptionBuilder.parsePattern("abc"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-abc" }); assertTrue(line.hasOption('a')); assertNull("value a", line.getOptionObject('a')); assertTrue(line.hasOption('b')); assertNull("value b", line.getOptionObject('b')); assertTrue(line.hasOption('c')); assertNull("value c", line.getOptionObject('c')); } public void testNumberPattern() throws Exception { Options options = PatternOptionBuilder.parsePattern("n%d%x%"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-n", "1", "-d", "2.1", "-x", "3,5" }); assertEquals("n object class", Long.class, line.getOptionObject("n").getClass()); assertEquals("n value", new Long(1), line.getOptionObject("n")); assertEquals("d object class", Double.class, line.getOptionObject("d").getClass()); assertEquals("d value", new Double(2.1), line.getOptionObject("d")); assertNull("x object", line.getOptionObject("x")); } public void testClassPattern() throws Exception { Options options = PatternOptionBuilder.parsePattern("c+d+"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-c", "java.util.Calendar", "-d", "System.DateTime" }); assertEquals("c value", Calendar.class, line.getOptionObject("c")); assertNull("d value", line.getOptionObject("d")); } public void testObjectPattern() throws Exception { Options options = PatternOptionBuilder.parsePattern("o@i@n@"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-o", "java.lang.String", "-i", "java.util.Calendar", "-n", "System.DateTime" }); assertEquals("o value", "", line.getOptionObject("o")); assertNull("i value", line.getOptionObject("i")); assertNull("n value", line.getOptionObject("n")); } public void testURLPattern() throws Exception { Options options = PatternOptionBuilder.parsePattern("u/v/"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-u", "http://commons.apache.org", "-v", "foo://commons.apache.org" }); assertEquals("u value", new URL("http://commons.apache.org"), line.getOptionObject("u")); assertNull("v value", line.getOptionObject("v")); } public void testExistingFilePattern() throws Exception { Options options = PatternOptionBuilder.parsePattern("f<"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-f", "test.properties" }); assertEquals("f value", new File("test.properties"), line.getOptionObject("f")); // todo test if an error is returned if the file doesn't exists (when it's implemented) } public void testRequiredOption() throws Exception { Options options = PatternOptionBuilder.parsePattern("!n%m%"); CommandLineParser parser = new PosixParser(); try { parser.parse(options, new String[]{""}); fail("MissingOptionException wasn't thrown"); } catch (MissingOptionException e) { assertEquals(1, e.getMissingOptions().size()); assertTrue(e.getMissingOptions().contains("n")); } } } commons-cli-1.2-src/src/test/org/apache/commons/cli/PosixParserTest.java100644 0 0 15757 11157377775 23555 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; /** * Test case for the PosixParser. * * @version $Revision: 695410 $, $Date: 2008-09-15 03:25:38 -0700 (Mon, 15 Sep 2008) $ */ public class PosixParserTest extends ParserTestCase { public void setUp() { super.setUp(); parser = new PosixParser(); } public void testBursting() throws Exception { String[] args = new String[] { "-acbtoast", "foo", "bar" }; CommandLine cl = parser.parse(options, args); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertTrue( "Confirm -b is set", cl.hasOption("b") ); assertTrue( "Confirm -c is set", cl.hasOption("c") ); assertTrue( "Confirm arg of -b", cl.getOptionValue("b").equals("toast") ); assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2); } public void testUnrecognizedOptionWithBursting() throws Exception { String[] args = new String[] { "-adbtoast", "foo", "bar" }; try { parser.parse(options, args); fail("UnrecognizedOptionException wasn't thrown"); } catch (UnrecognizedOptionException e) { assertEquals("-adbtoast", e.getOption()); } } public void testMissingArgWithBursting() throws Exception { String[] args = new String[] { "-acb" }; boolean caught = false; try { parser.parse(options, args); } catch (MissingArgumentException e) { caught = true; assertEquals("option missing an argument", "b", e.getOption().getOpt()); } assertTrue( "Confirm MissingArgumentException caught", caught ); } public void testStopBursting() throws Exception { String[] args = new String[] { "-azc" }; CommandLine cl = parser.parse(options, args, true); assertTrue( "Confirm -a is set", cl.hasOption("a") ); assertFalse( "Confirm -c is not set", cl.hasOption("c") ); assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue(cl.getArgList().contains("zc")); } public void testStopBursting2() throws Exception { String[] args = new String[] { "-c", "foobar", "-btoast" }; CommandLine cl = parser.parse(options, args, true); assertTrue("Confirm -c is set", cl.hasOption("c")); assertTrue("Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2); cl = parser.parse(options, cl.getArgs()); assertTrue("Confirm -c is not set", !cl.hasOption("c")); assertTrue("Confirm -b is set", cl.hasOption("b")); assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast")); assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1); assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar")); } /** * Real world test with long and short options. */ public void testLongOptionWithShort() throws Exception { Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print version information"); Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items"); Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items"); Option timeLimit = OptionBuilder.withLongOpt("limit").hasArg() .withValueSeparator() .withDescription("Set time limit for execution, in minutes") .create("l"); Option age = OptionBuilder.withLongOpt("age").hasArg() .withValueSeparator() .withDescription("Age (in days) of cache item before being recomputed") .create("a"); Option server = OptionBuilder.withLongOpt("server").hasArg() .withValueSeparator() .withDescription("The NLT server address") .create("s"); Option numResults = OptionBuilder.withLongOpt("results").hasArg() .withValueSeparator() .withDescription("Number of results per item") .create("r"); Option configFile = OptionBuilder.withLongOpt("file").hasArg() .withValueSeparator() .withDescription("Use the specified configuration file") .create(); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(newRun); options.addOption(trackerRun); options.addOption(timeLimit); options.addOption(age); options.addOption(server); options.addOption(numResults); options.addOption(configFile); // create the command line parser CommandLineParser parser = new PosixParser(); String[] args = new String[] { "-v", "-l", "10", "-age", "5", "-file", "filename" }; CommandLine line = parser.parse(options, args); assertTrue(line.hasOption("v")); assertEquals(line.getOptionValue("l"), "10"); assertEquals(line.getOptionValue("limit"), "10"); assertEquals(line.getOptionValue("a"), "5"); assertEquals(line.getOptionValue("age"), "5"); assertEquals(line.getOptionValue("file"), "filename"); } public void testLongWithEqualSingleDash() throws Exception { // not supported by the PosixParser } public void testShortWithEqual() throws Exception { // not supported by the PosixParser } } commons-cli-1.2-src/src/test/org/apache/commons/cli/UtilTest.java100644 0 0 2543 11157377775 22160 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import junit.framework.TestCase; /** * @author brianegge */ public class UtilTest extends TestCase { public void testStripLeadingHyphens() { assertEquals("f", Util.stripLeadingHyphens("-f")); assertEquals("foo", Util.stripLeadingHyphens("--foo")); assertEquals("-foo", Util.stripLeadingHyphens("---foo")); assertNull(Util.stripLeadingHyphens(null)); } public void testStripLeadingAndTrailingQuotes() { assertEquals("foo", Util.stripLeadingAndTrailingQuotes("\"foo\"")); } } commons-cli-1.2-src/src/test/org/apache/commons/cli/ValuesTest.java100644 0 0 16523 11157377775 22525 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.Arrays; import junit.framework.TestCase; public class ValuesTest extends TestCase { /** CommandLine instance */ private CommandLine _cmdline = null; public void setUp() throws Exception { Options options = new Options(); options.addOption("a", false, "toggle -a"); options.addOption("b", true, "set -b"); options.addOption("c", "c", false, "toggle -c"); options.addOption("d", "d", true, "set -d"); options.addOption(OptionBuilder.withLongOpt("e").hasArgs().withDescription("set -e ").create('e')); options.addOption("f", "f", false, "jk"); options.addOption(OptionBuilder.withLongOpt("g").hasArgs(2).withDescription("set -g").create('g')); options.addOption(OptionBuilder.withLongOpt("h").hasArgs(2).withDescription("set -h").create('h')); options.addOption(OptionBuilder.withLongOpt("i").withDescription("set -i").create('i')); options.addOption(OptionBuilder.withLongOpt("j").hasArgs().withDescription("set -j").withValueSeparator('=').create('j')); options.addOption(OptionBuilder.withLongOpt("k").hasArgs().withDescription("set -k").withValueSeparator('=').create('k')); options.addOption(OptionBuilder.withLongOpt("m").hasArgs().withDescription("set -m").withValueSeparator().create('m')); String[] args = new String[] { "-a", "-b", "foo", "--c", "--d", "bar", "-e", "one", "two", "-f", "arg1", "arg2", "-g", "val1", "val2" , "arg3", "-h", "val1", "-i", "-h", "val2", "-jkey=value", "-j", "key=value", "-kkey1=value1", "-kkey2=value2", "-mkey=value"}; CommandLineParser parser = new PosixParser(); _cmdline = parser.parse(options,args); } public void testShortArgs() { assertTrue( _cmdline.hasOption("a") ); assertTrue( _cmdline.hasOption("c") ); assertNull( _cmdline.getOptionValues("a") ); assertNull( _cmdline.getOptionValues("c") ); } public void testShortArgsWithValue() { assertTrue( _cmdline.hasOption("b") ); assertTrue( _cmdline.getOptionValue("b").equals("foo")); assertEquals(1, _cmdline.getOptionValues("b").length); assertTrue( _cmdline.hasOption("d") ); assertTrue( _cmdline.getOptionValue("d").equals("bar")); assertEquals(1, _cmdline.getOptionValues("d").length); } public void testMultipleArgValues() { String[] result = _cmdline.getOptionValues("e"); String[] values = new String[] { "one", "two" }; assertTrue( _cmdline.hasOption("e") ); assertEquals(2, _cmdline.getOptionValues("e").length); assertTrue( Arrays.equals( values, _cmdline.getOptionValues("e") ) ); } public void testTwoArgValues() { String[] result = _cmdline.getOptionValues("g"); String[] values = new String[] { "val1", "val2" }; assertTrue( _cmdline.hasOption("g") ); assertEquals(2, _cmdline.getOptionValues("g").length); assertTrue( Arrays.equals( values, _cmdline.getOptionValues("g") ) ); } public void testComplexValues() { String[] result = _cmdline.getOptionValues("h"); String[] values = new String[] { "val1", "val2" }; assertTrue( _cmdline.hasOption("i") ); assertTrue( _cmdline.hasOption("h") ); assertEquals(2, _cmdline.getOptionValues("h").length); assertTrue( Arrays.equals( values, _cmdline.getOptionValues("h") ) ); } public void testExtraArgs() { String[] args = new String[] { "arg1", "arg2", "arg3" }; assertEquals(3, _cmdline.getArgs().length); assertTrue( Arrays.equals( args, _cmdline.getArgs() ) ); } public void testCharSeparator() { // tests the char methods of CommandLine that delegate to // the String methods String[] values = new String[] { "key", "value", "key", "value" }; assertTrue( _cmdline.hasOption( "j" ) ); assertTrue( _cmdline.hasOption( 'j' ) ); assertEquals( 4, _cmdline.getOptionValues( "j" ).length ); assertEquals( 4, _cmdline.getOptionValues( 'j' ).length ); assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "j" ) ) ); assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'j' ) ) ); values = new String[] { "key1", "value1", "key2", "value2" }; assertTrue( _cmdline.hasOption( "k" ) ); assertTrue( _cmdline.hasOption( 'k' ) ); assertEquals(4, _cmdline.getOptionValues( "k" ).length); assertEquals(4, _cmdline.getOptionValues( 'k' ).length); assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "k" ) ) ); assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'k' ) ) ); values = new String[] { "key", "value" }; assertTrue( _cmdline.hasOption( "m" ) ); assertTrue( _cmdline.hasOption( 'm' ) ); assertEquals(2, _cmdline.getOptionValues( "m" ).length); assertEquals(2, _cmdline.getOptionValues( 'm' ).length); assertTrue( Arrays.equals( values, _cmdline.getOptionValues( "m" ) ) ); assertTrue( Arrays.equals( values, _cmdline.getOptionValues( 'm' ) ) ); } /** * jkeyes - commented out this test as the new architecture * breaks this type of functionality. I have left the test * here in case I get a brainwave on how to resolve this. */ /* public void testGetValue() { // the 'm' option assertTrue( _option.getValues().length == 2 ); assertEquals( _option.getValue(), "key" ); assertEquals( _option.getValue( 0 ), "key" ); assertEquals( _option.getValue( 1 ), "value" ); try { assertEquals( _option.getValue( 2 ), "key" ); fail( "IndexOutOfBounds not caught" ); } catch( IndexOutOfBoundsException exp ) { } try { assertEquals( _option.getValue( -1 ), "key" ); fail( "IndexOutOfBounds not caught" ); } catch( IndexOutOfBoundsException exp ) { } } */ } commons-cli-1.2-src/src/test/org/apache/commons/cli/ValueTest.java100644 0 0 22261 11157377775 22336 0ustar 0 0 /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.commons.cli; import java.util.Arrays; import java.util.Properties; import junit.framework.TestCase; public class ValueTest extends TestCase { private CommandLine _cl = null; private Options opts = new Options(); public void setUp() throws Exception { opts.addOption("a", false, "toggle -a"); opts.addOption("b", true, "set -b"); opts.addOption("c", "c", false, "toggle -c"); opts.addOption("d", "d", true, "set -d"); opts.addOption(OptionBuilder.hasOptionalArg().create('e')); opts.addOption(OptionBuilder.hasOptionalArg().withLongOpt("fish").create()); opts.addOption(OptionBuilder.hasOptionalArgs().withLongOpt("gravy").create()); opts.addOption(OptionBuilder.hasOptionalArgs(2).withLongOpt("hide").create()); opts.addOption(OptionBuilder.hasOptionalArgs(2).create('i')); opts.addOption(OptionBuilder.hasOptionalArgs().create('j')); opts.addOption(OptionBuilder.hasArgs().withValueSeparator(',').create('k')); String[] args = new String[] { "-a", "-b", "foo", "--c", "--d", "bar" }; Parser parser = new PosixParser(); _cl = parser.parse(opts,args); } public void testShortNoArg() { assertTrue( _cl.hasOption("a") ); assertNull( _cl.getOptionValue("a") ); } public void testShortWithArg() { assertTrue( _cl.hasOption("b") ); assertNotNull( _cl.getOptionValue("b") ); assertEquals( _cl.getOptionValue("b"), "foo"); } public void testLongNoArg() { assertTrue( _cl.hasOption("c") ); assertNull( _cl.getOptionValue("c") ); } public void testLongWithArg() { assertTrue( _cl.hasOption("d") ); assertNotNull( _cl.getOptionValue("d") ); assertEquals( _cl.getOptionValue("d"), "bar"); } public void testShortOptionalArgNoValue() throws Exception { String[] args = new String[] { "-e" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("e") ); assertNull( cmd.getOptionValue("e") ); } public void testShortOptionalArgValue() throws Exception { String[] args = new String[] { "-e", "everything" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("e") ); assertEquals( "everything", cmd.getOptionValue("e") ); } public void testLongOptionalNoValue() throws Exception { String[] args = new String[] { "--fish" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("fish") ); assertNull( cmd.getOptionValue("fish") ); } public void testLongOptionalArgValue() throws Exception { String[] args = new String[] { "--fish", "face" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("fish") ); assertEquals( "face", cmd.getOptionValue("fish") ); } public void testShortOptionalArgValues() throws Exception { String[] args = new String[] { "-j", "ink", "idea" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("j") ); assertEquals( "ink", cmd.getOptionValue("j") ); assertEquals( "ink", cmd.getOptionValues("j")[0] ); assertEquals( "idea", cmd.getOptionValues("j")[1] ); assertEquals( cmd.getArgs().length, 0 ); } public void testLongOptionalArgValues() throws Exception { String[] args = new String[] { "--gravy", "gold", "garden" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("gravy") ); assertEquals( "gold", cmd.getOptionValue("gravy") ); assertEquals( "gold", cmd.getOptionValues("gravy")[0] ); assertEquals( "garden", cmd.getOptionValues("gravy")[1] ); assertEquals( cmd.getArgs().length, 0 ); } public void testShortOptionalNArgValues() throws Exception { String[] args = new String[] { "-i", "ink", "idea", "isotope", "ice" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("i") ); assertEquals( "ink", cmd.getOptionValue("i") ); assertEquals( "ink", cmd.getOptionValues("i")[0] ); assertEquals( "idea", cmd.getOptionValues("i")[1] ); assertEquals( cmd.getArgs().length, 2 ); assertEquals( "isotope", cmd.getArgs()[0] ); assertEquals( "ice", cmd.getArgs()[1] ); } public void testLongOptionalNArgValues() throws Exception { String[] args = new String[] { "--hide", "house", "hair", "head" }; Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts,args); assertTrue( cmd.hasOption("hide") ); assertEquals( "house", cmd.getOptionValue("hide") ); assertEquals( "house", cmd.getOptionValues("hide")[0] ); assertEquals( "hair", cmd.getOptionValues("hide")[1] ); assertEquals( cmd.getArgs().length, 1 ); assertEquals( "head", cmd.getArgs()[0] ); } public void testPropertyOptionSingularValue() throws Exception { Properties properties = new Properties(); properties.setProperty( "hide", "seek" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("hide") ); assertEquals( "seek", cmd.getOptionValue("hide") ); assertTrue( !cmd.hasOption("fake") ); } public void testPropertyOptionFlags() throws Exception { Properties properties = new Properties(); properties.setProperty( "a", "true" ); properties.setProperty( "c", "yes" ); properties.setProperty( "e", "1" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "false" ); properties.setProperty( "c", "no" ); properties.setProperty( "e", "0" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( !cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "TRUE" ); properties.setProperty( "c", "nO" ); properties.setProperty( "e", "TrUe" ); cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( cmd.hasOption("e") ); properties = new Properties(); properties.setProperty( "a", "just a string" ); properties.setProperty( "e", "" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( !cmd.hasOption("e") ); } public void testPropertyOptionMultipleValues() throws Exception { Properties properties = new Properties(); properties.setProperty( "k", "one,two" ); Parser parser = new PosixParser(); String[] values = new String[] { "one", "two" }; CommandLine cmd = parser.parse(opts, null, properties); assertTrue( cmd.hasOption("k") ); assertTrue( Arrays.equals( values, cmd.getOptionValues('k') ) ); } public void testPropertyOverrideValues() throws Exception { String[] args = new String[] { "-j", "found", "-i", "ink" }; Properties properties = new Properties(); properties.setProperty( "j", "seek" ); Parser parser = new PosixParser(); CommandLine cmd = parser.parse(opts, args, properties); assertTrue( cmd.hasOption("j") ); assertEquals( "found", cmd.getOptionValue("j") ); assertTrue( cmd.hasOption("i") ); assertEquals( "ink", cmd.getOptionValue("i") ); assertTrue( !cmd.hasOption("fake") ); } } /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 l