View Javadoc
1   /*
2    * Copyright 2007-2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.gwe.utils.cmd;
18  
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  /**
23   * @author Marco Ruiz
24   * @since Mar 13, 2008
25   */
26  public class OptionParser {
27  
28  	private List<String> parts;
29  	
30  	public OptionParser(String prefix, String arg, char... separators) {
31  		parts = new ArrayList<String>(separators.length + 1);
32  
33  		if (arg == null || !arg.startsWith(prefix)) return;
34  
35  		String partsArg = arg.substring(prefix.length());
36  		for (int idx = separators.length - 1; idx >= 0; idx--) {
37  	        String value = null;
38  			int sepIndex = partsArg.lastIndexOf(separators[idx]);
39  	        if (sepIndex != -1) {
40  	        	value = partsArg.substring(sepIndex + 1);
41  	        	partsArg = partsArg.substring(0, sepIndex); 
42  	        }
43  	        parts.add(0, value);
44          }
45          parts.add(0, partsArg);
46  	}
47  	
48  	public String getEle(int index, String defaultValue) {
49  		if (index > parts.size() - 1) return defaultValue;
50  		String result = parts.get(index);
51  		return (result != null && !"".equals(result)) ? result : defaultValue;
52  	}
53  	
54  	public static void main(String[] args) {
55  		OptionParser parser = new OptionParser("prefix=", "prefix=alfa:gama:delta@whatever-now:end", new char[]{':', ':', '@', '-', ':'});
56  		System.out.println(parser.getEle(0, null));
57  		System.out.println(parser.getEle(1, null));
58  		System.out.println(parser.getEle(2, null));
59  		System.out.println(parser.getEle(3, null));
60  		System.out.println(parser.getEle(4, null));
61  		System.out.println(parser.getEle(5, null));
62  		System.out.println(parser.getEle(6, null));
63  		System.out.println(parser.getEle(7, null));
64  	}
65  }
66