001package net.gdface.cli; 002 003import java.util.Collections; 004import java.util.Iterator; 005import java.util.Map; 006 007import org.apache.commons.cli.CommandLine; 008import org.apache.commons.cli.Option; 009import org.apache.commons.cli.Options; 010import org.apache.commons.cli.ParseException; 011 012/** 013 * 傿•°é…置抽象类 014 * @author guyadong 015 * 016 */ 017public abstract class AbstractConfiguration extends Context implements CommonCliConstants, CmdConfig { 018 /** åç±»æä¾›å‘½ä»¤è¡Œå‚数的默认值 */ 019 protected abstract Map<String, Object> getDefaultValueMap(); 020 @Override 021 public void loadConfig(Options options, CommandLine cmd) throws ParseException { 022 Iterator<Option> it = options.getOptions().iterator(); 023 Option opt; 024 String key; 025 Map<String, Object> defaultMap = getDefaultValueMap(); 026 if (defaultMap == null){ 027 defaultMap = Collections.emptyMap();; 028 } 029 while (it.hasNext()) { 030 opt = it.next(); 031 // 优先用长值 032 key = opt.getLongOpt() == null ? opt.getOpt() : opt.getLongOpt(); 033 if(isNeedOption(key)){ 034 Object value; 035 try{ 036 if(opt.hasArg()){ 037 value=cmd.getParsedOptionValue(key); 038 }else{ 039 // ä¸éœ€è¦å‚数的选项视为boolean,直接返回boolean值 040 value = cmd.hasOption(key); 041 } 042 }catch(NoClassDefFoundError e){ 043 System.out.printf("key=%s %s\n",key,cmd.getOptionValue(key)); 044 throw e; 045 } 046 047 if (null == value) { 048 if (opt.isRequired()) { 049 throw new IllegalArgumentException(String.format("%s or %s not define", opt.getOpt(), 050 opt.getLongOpt())); 051 } else { 052 // 没有定义缺çœå€¼åˆ™æŠ›å‡ºå¼‚常,缺çœå€¼å¯ä»¥ä¸ºnull 053 if (!defaultMap.containsKey(key)) { 054 throw new IllegalArgumentException(String.format("%s or %s not default value", opt.getOpt(), 055 opt.getLongOpt())); 056 } 057 value = defaultMap.get(key); 058 } 059 } 060 this.setProperty(key, value); 061 } 062 } 063 } 064 private final boolean isNeedOption(String opt){ 065 return !CONTROL_OPTIONS.contains(opt); 066 } 067}