001package gu.dtalk; 002import static com.google.common.base.Preconditions.checkArgument; 003import static gu.dtalk.CommonUtils.*; 004 005import java.util.Collections; 006import java.util.Map; 007 008import com.google.common.base.MoreObjects; 009import com.google.common.base.Strings; 010 011import gu.dtalk.exception.CmdExecutionException; 012import gu.dtalk.exception.UnsupportCmdException; 013 014/** 015 * 菜单对象 016 * @author guyadong 017 * 018 */ 019public class MenuItem extends BaseItem { 020 public MenuItem() { 021 items.clear(); 022 CmdItem back = makeBack(); 023 // 为菜单项添加返回项 024 items.put(back.getName(), back); 025 } 026 027 @Override 028 public final boolean isContainer() { 029 return true; 030 } 031 032 @Override 033 public final ItemType getCatalog() { 034 return ItemType.MENU; 035 } 036 /** 037 * 执行cmdpath指定的命令 038 * @param cmdpath 039 * @param parameters 命令参数,参数名-参数值(json格式),没有参数,可以输入{@code null}或空 040 * @return 返回值,没有返回值则返回null 041 * @throws UnsupportCmdException 042 * @throws CmdExecutionException 043 */ 044 public Object runCmd(String cmdpath,Map<String, ?> parameters) throws UnsupportCmdException, CmdExecutionException{ 045 checkArgument(!Strings.isNullOrEmpty(cmdpath),"cmd's path is null or empty"); 046 parameters = MoreObjects.firstNonNull(parameters,Collections.<String, Object>emptyMap()); 047 CmdItem cmd = findCmd(cmdpath); 048 if(cmd == null){ 049 throw new UnsupportCmdException(cmdpath + "is not a cmd item" ); 050 } 051 return cmd.runCmd(parameters); 052 } 053 054 public MenuItem readonlyOption(String optpath,boolean readonly){ 055 BaseOption<Object> option = findOption(optpath); 056 if(option != null){ 057 option.setReadOnly(readonly); 058 } 059 return this; 060 } 061 public MenuItem disableItem(String optpath,boolean disable){ 062 BaseItem option = find(optpath); 063 if(option != null){ 064 option.setDisable(disable); 065 } 066 return this; 067 } 068 069 /** 070 * 返回选项的值,如果{@code optpath}指定的{@link BaseOption}不存在则返回{@code null} 071 * @param optpath 072 * @return 073 * @see BaseOption#fetch() 074 */ 075 public <T> T fetchOption(String optpath){ 076 BaseOption<T> option = findOption(optpath); 077 if(option != null){ 078 return option.fetch(); 079 } 080 return null; 081 } 082 /** 083 * 返回选项的值,如果{@code optpath}指定的{@link BaseOption}不存在则返回{@code null} 084 * @param optpath 085 * @return 086 * @see BaseOption#getValue() 087 */ 088 public <T> T optionValueOf(String optpath){ 089 BaseOption<T> option = findOption(optpath); 090 if(option != null){ 091 return option.getValue(); 092 } 093 return null; 094 } 095 /** 096 * 更新选项的值,如果{@code optpath}指定的{@link BaseOption}不存在则跳过 097 * @param optpath 098 * @param value 099 * @return 100 * @see BaseOption#updateFrom(Object) 101 */ 102 public <T>MenuItem updateValueOf(String optpath,T value){ 103 BaseOption<T> option = findOption(optpath); 104 if(option != null){ 105 option.updateFrom(value); 106 } 107 return this; 108 } 109}