Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Map;
- import java.util.HashMap;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.InputMismatchException;
- public class ArgParser{
- public static void main(String[] args) {
- Map<String, List<String>> parsedArgs = ParseArgs(args);
- Map<String, String[]> rules = new HashMap<String, String[]>();
- rules.put("filmes", new String[]{"nome_ator1", "nome_ator2", "decada"});
- rules.put("episodios", new String[]{"nome_ator", "titulo_serie"});
- rules.put("generos", new String[]{"nome_ator"});
- if(!ValidateArgs(parsedArgs, rules, true))
- return;
- for(Map.Entry<String, List<String>> arg: parsedArgs.entrySet()) {
- System.out.println(arg.getKey());
- for(String subArg: arg.getValue())
- System.out.println("\t" + subArg);
- }
- }
- public static Map<String, List<String>> ParseArgs(String[] args) {
- Map<String, List<String>> result = new LinkedHashMap<String, List<String>>();
- List<String> subArgs = null;
- for(String arg: args)
- if(arg.startsWith("-"))
- result.put(arg.substring(1), subArgs = new ArrayList<String>());
- else if(subArgs != null)
- subArgs.add(arg);
- else
- result.put(arg, null);
- return result;
- }
- public static Boolean ValidateArgs(Map<String, List<String>> args, Map<String, String[]> rules, Boolean aLeastOne) {
- Boolean result = true;
- if(aLeastOne && args.isEmpty())
- System.err.println("E necessario ao menos um parametro!");
- for(Map.Entry<String, List<String>> arg: args.entrySet()) {
- if(rules.containsKey(arg.getKey())) {
- String[] subArgs = rules.get(arg.getKey());
- if(subArgs != null && (arg.getValue() == null || arg.getValue().size() != subArgs.length)) {
- String Msg = String.format("O parametro <-%s> espera %d subargumentos.\nModo de uso: <-%s>"
- , arg.getKey(), subArgs.length, arg.getKey());
- for(String str: subArgs)
- Msg += " <" + str + ">";
- System.err.println(Msg);
- result = false;
- }
- } else {
- System.err.println(String.format("Parametro desconhecido <%s%s>"
- , arg.getValue() != null ? "-" : "", arg.getKey()));
- result = false;
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement