summaryrefslogtreecommitdiffstats
path: root/ldap/admin/src/java/com/netscape/xmltools/GetOpt.java
blob: a8f11b7fe096ba5804f2b5c4c421f5d6402437e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 * END COPYRIGHT BLOCK **/
package com.netscape.xmltools;
import java.util.*;

/**
 * This class is similar to the <CODE>getopt()</CODE> function in
 * UNIX System V. You can use this class to parse command-line
 * arguments.
 * <P>
 *
 * When you create an object of this class, you specify a string
 * containing the command-line options that you want to check for.
 * The string should contain the letters of these options. If an
 * option requires an argument (for example, "-h <hostname>"),
 * you should add a colon after the letter in this string.
 * <P>
 *
 * For example, in the following string, the <CODE>-h</CODE>,
 * <CODE>-p</CODE>, <CODE>-D,</CODE>, and <CODE>-w</CODE> options
 * all require arguments.  The <CODE>-H</CODE> option does not
 * require any arguments.
 * <PRE>
 * "h:p:D:w:H"
 * </PRE>
 *
 * You can use the <CODE>hasOption</CODE> method to determine if
 * an option has been specified and the <CODE>getOptionParam</CODE>
 * method to get the argument specified after a particular option.
 * <P>
 *
 * If an option not specified in the string is passed in as an
 * argument, the <CODE>GetOpt</CODE> object prints out an error
 * message.  Note that the object does not throw an exception or
 * exit the application if an invalid option is specified.
 * <P>
 *
 * Note that you are still responsible for verifying that any
 * required arguments have been specified.
 * <P>
 *
 * The following example parses the command-line arguments for
 * the hostname, port number, DN, and password to use when
 * connecting and authenticating to an LDAP server.
 * <PRE>
 * import netscape.ldap.*;
 * import netscape.ldap.controls.*;
 * import netscape.ldap.util.*;
 * import java.util.*;
 *
 * public class SearchDirectory {
 *
 *     public static void main( String[] args )
 *     {
 *
 *         String usage = "Usage: java SearchDirectory -h <host> -p <port> "
 *                      + "[-D <bind dn>] [-w <password>]"
 *
 *         int portnumber = LDAPv2.DEFAULT_PORT;
 *
 *         // Check for these options. -H means to print out a usage message.
 *         GetOpt options = new GetOpt( "h:p:D:w:H", args );
 *
 *         // Get the arguments specified for each option.
 *         String hostname = options.getOptionParam( 'h' );
 *         String port = options.getOptionParam( 'p' );
 *         String bindDN = options.getOptionParam( 'D' );
 *         String bindPW = options.getOptionParam( 'w' );
 *
 *         // Check to see if the hostname (which is mandatory)
 *         // is not specified or if the user simply wants to
 *         // see the usage message (-H).
 *         if ( hostname == null || options.hasOption( 'H' ) ) {
 *             System.out.println( usage );
 *             System.exit( 1 );
 *         }
 *
 *         // If a port number was specified, convert the port value
 *         //  to an integer.
 *         if ( port != null ) {
 *             try {
 *                 portnumber = java.lang.Integer.parseInt( port );
 *             } catch ( java.lang.Exception e ) {
 *                 System.out.println( "Invalid port number: " + port );
 *                 System.out.println( usage );
 *                 System.exit( 1 );
 *             }
 *         }
 *
 *         // Create a new connection.
 *         LDAPConnection ld = new LDAPConnection();
 *
 *         try {
 *             // Connect and authenticate to server.
 *             ld.connect( 3, hostname, portnumber, bindDN, bindPW );
 *             ...
 *         } catch ( LDAPException e ) {
 *             System.out.println( "Error: " + e.toString() );
 *         }
 *         ...
 *     }
 * }
 * </PRE>
 *
 * @version 1.0
 */
public class GetOpt implements java.io.Serializable {
    /**
     * Internal variables
     */
    private int m_pos;
    private String optarg;
    private String m_control;
    private Vector m_option;
    private Vector m_ParameterList;
    private Hashtable m_optionHashTable;
    private Hashtable m_optionParamHashTable;
    static final long serialVersionUID = -2570196909939660248L;

    /**
     * Constructs a <CODE>GetOpt</CODE> object.
     * @param strControl a string specifying the letters of
     * all available options. If an option requires an argument
     * (for example, "-h <hostname>"), use a colon after the
     * letter for that option (for example, "h:p:D:w:H").
     * @param args an array of strings representing the list
     * of arguments to parse (for example, the
     * array passed into Main).
     */
    public GetOpt(String strControl, String args[]) {
        m_option = new Vector();
        m_control = strControl;
        m_optionHashTable = new Hashtable();
        m_optionParamHashTable = new Hashtable();
        m_ParameterList = new Vector();

        for (int i=0;i<args.length ;i++ ) {
            String sOpt = args[i];
                if (sOpt.length()>0) {
                    if (sOpt.charAt(0)=='-') {
                        if (sOpt.length()>1) {
                            int nIndex = m_control.indexOf(sOpt.charAt(1));
                            if (nIndex == (-1)) {
                                System.err.println("Invalid usage. No option -" +
                                    sOpt.charAt(1));
                            } else {
                                char cOpt[]= new char[1];
                                cOpt[0]= sOpt.charAt(1);
                                String sName = new String(cOpt);
                                m_optionHashTable.put(sName,"1");
                                if ((m_control != null) && (m_control.length() > (nIndex+1))) {
                                    if (m_control.charAt(nIndex+1)==':') {
                                        i++;
                                        if (i < args.length)
                                            m_optionParamHashTable.put(sName,args[i]);
                                        else
                                            System.err.println("Missing argument for option "+
                                                sOpt);
                                    }
                                }
                            }
                        } else {
                        System.err.println("Invalid usage.");
                    }
                } else {
                    // probably parameters
                    m_ParameterList.addElement(args[i]);
                }
            }
        }
    }

    /**
     * Determines if an option was specified. For example,
     * <CODE>hasOption( 'H' )</CODE> checks if the -H option
     * was specified.
     * <P>
     *
     * @param c letter of the option to check
     * @return <code>true</code> if the option was specified.
     */
    public boolean hasOption(char c) {
        boolean fReturn = false;
        char cOption[]=new char[1];
        cOption[0]=c;
        String s = new String(cOption);
        if (m_optionHashTable.get(s)=="1") {
            fReturn = true;
        }
        return(fReturn);
    }

    /**
     * Gets the argument specified with an option.
     * For example, <CODE>getOptionParameter( 'h' )</CODE>
     * gets the value of the argument specified with
     * the -h option (such as "localhost" in "-h localhost").
     * <P>
     *
     * @param c the letter of the option to check
     * @return the argument specified for this option.
     */
    public String getOptionParam(char c) {
        char cOption[] = new char[1];
        cOption[0]=c;
        String s = new String(cOption);
        String sReturn=(String)m_optionParamHashTable.get(s);
        return(sReturn);
    }

    /**
     * Gets a list of any additional parameters specified
     * (not including the arguments for any options).
     * @return a list of the additional parameters.
     */
    public Vector getParameters() {
        return(m_ParameterList);
    }
}