HwapX

Java Argument Parser

Dec 15th, 2013
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. import java.util.Map;
  2. import java.util.List;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.InputMismatchException;
  6.  
  7. public class ArgParser{
  8.  
  9.     public static void main(String[] args) {
  10.         Map<String, List<String>> parsedArgs = ParseArgs(args);
  11.         Map<String, Integer> rules = new HashMap<String, Integer>();
  12.         rules.put("filmes", 3);
  13.         rules.put("episodios", 2);
  14.         rules.put("generos", 1);
  15.         ValidateArgs(parsedArgs, rules);
  16.        
  17.         for(Map.Entry<String, List<String>> arg: parsedArgs.entrySet()) {
  18.             System.out.println(arg.getKey());
  19.             for(String subArg: arg.getValue())
  20.                 System.out.println("\t" + subArg);
  21.         }
  22.     }
  23.  
  24.     public static Map<String, List<String>> ParseArgs(String[] args) {
  25.         Map<String, List<String>> result = new HashMap<String, List<String>>();
  26.         List<String> subArgs = null;
  27.        
  28.         for(String arg: args) {
  29.             if(arg.startsWith("-")) {
  30.                 subArgs = new ArrayList<String>();
  31.                 result.put(arg.substring(1), subArgs);
  32.             }
  33.             else {
  34.                 if(subArgs != null)
  35.                     subArgs.add(arg);
  36.                 else
  37.                     throw new IllegalArgumentException("Invalid argument");
  38.             }
  39.         }
  40.        
  41.         return result;
  42.     }
  43.    
  44.     public static void ValidateArgs(Map<String, List<String>> args, Map<String, Integer> rules) {
  45.         for(Map.Entry<String, Integer> rule: rules.entrySet()) {
  46.             List<String> subArgs = args.get(rule.getKey());
  47.             if(subArgs == null || subArgs.size() != rule.getValue())
  48.                 throw new InputMismatchException("Expected subargument count " + rule.getValue());
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment