下面列出了怎么用org.bukkit.configuration.MemorySection的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Recursively visits every MemorySection and creates a {@link PermissionDefinition} when applicable.
*
* @param node the node to visit
* @param collection the collection to add constructed permission definitions to
*/
private static void addChildren(MemorySection node, Map<String, PermissionDefinition> collection) {
// A MemorySection may have a permission entry, as well as MemorySection children
boolean hasPermissionEntry = false;
for (String key : node.getKeys(false)) {
if (node.get(key) instanceof MemorySection && !"children".equals(key)) {
addChildren((MemorySection) node.get(key), collection);
} else if (PERMISSION_FIELDS.contains(key)) {
hasPermissionEntry = true;
} else {
throw new IllegalStateException("Unexpected key '" + key + "'");
}
}
if (hasPermissionEntry) {
PermissionDefinition permDef = new PermissionDefinition(node);
collection.put(permDef.node, permDef);
}
}
/**
* Recursively walks through the given memory section to gather all keys.
* Assumes that the ending value is a boolean and throws an exception otherwise.
*
* @param parentSection the memory section to traverse
* @param children list to add all results to
*/
private static void collectChildren(MemorySection parentSection, List<String> children) {
for (Map.Entry<String, Object> entry : parentSection.getValues(false).entrySet()) {
if (entry.getValue() instanceof MemorySection) {
collectChildren((MemorySection) entry.getValue(), children);
} else if (entry.getValue() instanceof Boolean) {
if (!Boolean.TRUE.equals(entry.getValue())) {
throw new IllegalStateException("Child entry '" + entry.getKey()
+ "' has unexpected value '" + entry.getValue() + "'");
}
children.add(parentSection.getCurrentPath() + "." + entry.getKey());
} else {
throw new IllegalStateException("Found child entry at '" + entry.getKey() + "' with value "
+ "of unexpected type: '" + parentSection.getCurrentPath() + "." + entry.getValue() + "'");
}
}
}
/**
* Reads plugin.yml and returns the defined commands by main label and aliases.
*
* @return collection of all labels and their aliases
*/
@SuppressWarnings("unchecked")
private static Map<String, List<String>> getLabelsFromPluginFile() {
FileConfiguration pluginFile = YamlConfiguration.loadConfiguration(getJarFile("/plugin.yml"));
MemorySection commandList = (MemorySection) pluginFile.get("commands");
Map<String, Object> commandDefinitions = commandList.getValues(false);
Map<String, List<String>> commandLabels = new HashMap<>();
for (Map.Entry<String, Object> commandDefinition : commandDefinitions.entrySet()) {
MemorySection definition = (MemorySection) commandDefinition.getValue();
List<String> alternativeLabels = definition.get("aliases") == null
? Collections.EMPTY_LIST
: (List<String>) definition.get("aliases");
commandLabels.put(commandDefinition.getKey(), alternativeLabels);
}
return commandLabels;
}
public ConfigurationSection toTrMenuSection(int priority, boolean useSlot) {
MemorySection section = new MemoryConfiguration();
if (getRequirement() != null) {
section.set("condition", getRequirement());
}
if (priority >= 0) {
section.set("priority", priority);
}
section.set("display.material", getMaterial());
if (getName() != null) {
section.set("display.name", getName());
}
if (getLore() != null) {
section.set("display.lore", getLore());
}
if (getAmount() != null) {
section.set("display.amount", getAmount());
}
if (getShiny() != null && !"false".equalsIgnoreCase(getShiny())) {
if (Boolean.parseBoolean(getShiny())) {
section.set("display.shiny", true);
} else {
section.set("display.shiny", getShiny());
}
}
if (getFlags() != null && !getFlags().isEmpty()) {
section.set("display.flags", getFlags());
}
if (!getSlots().isEmpty() && useSlot) {
if (getSlots().size() == 1) {
section.set("display.slot", getSlots().get(0));
} else {
section.set("display.slots", getSlots());
}
}
actions.forEach((type, actions) -> section.set("actions." + type, actions));
return section;
}
@Override
public ConfigurationSection createSection(String path) {
ConfigurationSection section = super.createSection(path);
if (section instanceof MemorySection) {
SimpleReflection.setFieldValue(MemorySection.class, section, "map", new ConcurrentHashMap<>(), true);
}
return section;
}
/**
* Returns all permission entries from the plugin.yml file.
*
* @return map with the permission entries by permission node
*/
private static Map<String, PermissionDefinition> getPermissionsFromPluginYmlFile() {
FileConfiguration pluginFile = YamlConfiguration.loadConfiguration(getJarFile("/plugin.yml"));
MemorySection permsList = (MemorySection) pluginFile.get("permissions");
Map<String, PermissionDefinition> permissions = new HashMap<>();
addChildren(permsList, permissions);
return ImmutableMap.copyOf(permissions);
}
PermissionDefinition(MemorySection memorySection) {
this.node = removePermissionsPrefix(memorySection.getCurrentPath());
this.expectedDefault = mapToDefaultPermission(memorySection.getString("default"));
if (memorySection.get("children") instanceof MemorySection) {
List<String> children = new ArrayList<>();
collectChildren((MemorySection) memorySection.get("children"), children);
this.children = removeStart(memorySection.getCurrentPath() + ".children.", children);
} else {
this.children = Collections.emptySet();
}
}
private static void checkDescription(Object memorySection, String description, String detailedDescription) {
if (memorySection instanceof MemorySection) {
MemorySection memSection = (MemorySection) memorySection;
assertThat(memSection.getString("description"), equalTo(description));
assertThat(memSection.getString("detailedDescription"), equalTo(detailedDescription));
} else {
fail("Expected MemorySection, got '" + memorySection + "'");
}
}
private static void checkArgs(Object memorySection, Argument... arguments) {
if (memorySection instanceof MemorySection) {
MemorySection memSection = (MemorySection) memorySection;
int i = 1;
for (Argument arg : arguments) {
assertThat(memSection.getString("arg" + i + ".label"), equalTo(arg.label));
assertThat(memSection.getString("arg" + i + ".description"), equalTo(arg.description));
++i;
}
assertThat(memSection.get("arg" + i), nullValue());
} else {
fail("Expected MemorySection, got '" + memorySection + "'");
}
}
/**
* Since CommandInitializer contains all descriptions for commands in English, the help_en.yml file
* only contains an entry for one command as to provide an example.
*/
@Test
public void shouldOnlyHaveDescriptionForOneCommand() {
// given
FileConfiguration configuration = YamlConfiguration.loadConfiguration(DEFAULT_MESSAGES_FILE);
// when
Object commands = configuration.get("commands");
// then
assertThat(commands, instanceOf(MemorySection.class));
assertThat(((MemorySection) commands).getKeys(false), contains("authme"));
}
/**
* Returns the leaf keys of the section at the given path of the file configuration.
*
* @param path the path whose leaf keys should be retrieved
* @return leaf keys of the memory section,
* empty set if the configuration does not have a memory section at the given path
*/
private Set<String> getLeafKeys(String path) {
if (!(configuration.get(path) instanceof MemorySection)) {
return Collections.emptySet();
}
MemorySection memorySection = (MemorySection) configuration.get(path);
// MemorySection#getKeys(true) returns all keys on all levels, e.g. if the configuration has
// 'commands.authme.register' then it also has 'commands.authme' and 'commands'. We can traverse each node and
// build its parents (e.g. for commands.authme.register.description: commands.authme.register, commands.authme,
// and commands, which we can remove from the collection since we know they are not a leaf.
Set<String> leafKeys = memorySection.getKeys(true);
Set<String> allKeys = new HashSet<>(leafKeys);
for (String key : allKeys) {
List<String> pathParts = Arrays.asList(key.split("\\."));
// We perform construction of parents & their removal in reverse order so we can build the lowest-level
// parent of a node first. As soon as the parent doesn't exist in the set already, we know we can continue
// with the next node since another node has already removed the concerned parents.
for (int i = pathParts.size() - 1; i > 0; --i) {
// e.g. for commands.authme.register -> i = {2, 1} => {commands.authme, commands}
String parentPath = String.join(".", pathParts.subList(0, i));
if (!leafKeys.remove(parentPath)) {
break;
}
}
}
return leafKeys.stream().map(leaf -> path + "." + leaf).collect(Collectors.toSet());
}
/**
* 加载图标
*
* @param map 图标设置
* @param defIcon 默认图标
* @return 图标
*/
public static Icon loadIcon(Map<String, Object> map, Icon defIcon) {
List<Mat> materials = Lists.newArrayList();
List<String> names;
List<List<String>> lores;
List<List<Integer>> slots;
List<ItemFlag> flags = Lists.newArrayList();
NBTCompound nbtCompound = new NBTCompound();
Map displayMap = Maps.sectionToMap(BUTTON_DISPLAY.getFromMap(map));
Map actionsMap = Maps.sectionToMap(BUTTON_ACTIONS.getFromMap(map, new HashMap<>()));
HashMap<ClickType, List<AbstractAction>> actions = new HashMap<>();
Object name = ICON_DISPLAY_NAME.getFromMap(displayMap);
Object mats = ICON_DISPLAY_MATERIALS.getFromMap(displayMap);
Object lore = ICON_DISPLAY_LORES.getFromMap(displayMap);
Object slot = ICON_DISPLAY_SLOTS.getFromMap(displayMap);
Object flag = ICON_DISPLAY_FLAGS.getFromMap(displayMap);
Object nbt = ICON_DISPLAY_NBTS.getFromMap(displayMap);
String shiny = String.valueOf(Maps.getSimilar(displayMap, ICON_DISPLAY_SHINY.getName()));
String amount = String.valueOf(Maps.getSimilar(displayMap, ICON_DISPLAY_AMOUNT.getName()));
shiny = "null".equals(shiny) ? "false" : shiny;
amount = "null".equals(amount) ? "1" : amount;
// Actions
for (ClickType value : ClickType.values()) {
List<String> actStrs = Maps.getSimilarOrDefault(actionsMap, value.name(), null);
if (actStrs != null && !actStrs.isEmpty()) {
actions.put(value, TrAction.readActions(actStrs));
}
}
actions.put(null, TrAction.readActions(TrUtils.castList(Maps.getSimilar(actionsMap, "ALL"), String.class)));
// Materials
if (mats == null && defIcon == null) {
throw new NullPointerException("Materials can not be null");
} else if (mats != null) {
if (mats instanceof List) {
List<String> list = TrUtils.castList(mats, String.class);
list.forEach(m -> materials.add(new Mat(String.valueOf(m))));
} else {
materials.add(new Mat(String.valueOf(mats)));
}
}
names = TrUtils.castList(name, String.class);
lores = TrUtils.readList(lore, String.class);
slots = TrUtils.readList(slot, Integer.class);
if (defIcon != null) {
if (names.isEmpty()) {
names = defIcon.getItem().getNames();
}
if (lore == null) {
lores = defIcon.getItem().getLores();
}
if (materials.isEmpty()) {
materials.addAll(defIcon.getItem().getMaterials());
}
}
// flags
if (flag != null) {
if (flag instanceof List) {
TrUtils.castList(flag, String.class).forEach(f -> flags.add(Items.asItemFlag(f)));
flags.removeIf(Objects::isNull);
}
}
if (nbt instanceof MemorySection) {
nbtCompound = NBTCompound.translateSection(new NBTCompound(), (MemorySection) nbt);
}
Item item = (displayMap == null && defIcon != null) ? defIcon.getItem() : new Item(names, materials, lores, slots, flags, nbtCompound, shiny, amount);
return new Icon(0, null, item, actions);
}
private static int convert(File file, int count) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
count += convert(f, count);
}
return count;
} else if (!file.getName().endsWith(".yml")) {
return count;
}
try {
ListIterator<Character> buttons = Arrays.asList('#', '-', '+', '=', '<', '>', '~', '_', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z').listIterator();
YamlConfiguration trmenu = new YamlConfiguration();
YamlConfiguration conf = YamlConfiguration.loadConfiguration(file);
List<String> cmds = conf.contains("menu-settings.command") ? Arrays.asList(conf.getString("menu-settings.command").split(";( )?")) : new ArrayList<>();
for (int i = 0; i < cmds.size(); i++) {
cmds.set(i, cmds.get(i) + "-fromCC");
}
int rows = conf.getInt("menu-settings.rows", 6);
int update = conf.getInt("menu-settings.auto-refresh", -1) * 20;
trmenu.set("Title", conf.getString("menu-settings.name"));
trmenu.set("Open-Commands", cmds);
trmenu.set("Open-Actions", conf.contains("menu-settings.open-action") ? conf.getString("menu-settings.open-action").split(";( )?") : "");
List<String> shape = Lists.newArrayList();
while (rows > 0) {
shape.add(" ");
rows--;
}
trmenu.set("Shape", shape);
conf.getValues(false).forEach((icon, value) -> {
if (!"menu-settings".equalsIgnoreCase(icon)) {
MemorySection section = (MemorySection) value;
int x = section.getInt("POSITION-X") - 1;
int y = section.getInt("POSITION-Y") - 1;
char[] chars = shape.get(y).toCharArray();
char symbol = buttons.next();
chars[x] = symbol;
shape.set(y, new String(chars));
if (update > 0) {
trmenu.set("Buttons." + symbol + ".update", update);
}
trmenu.set("Buttons." + symbol + ".display.mats", section.get("ID"));
trmenu.set("Buttons." + symbol + ".display.name", section.get("NAME"));
trmenu.set("Buttons." + symbol + ".display.lore", section.get("LORE"));
if (section.contains("COMMAND")) {
trmenu.set("Buttons." + symbol + ".actions.all", section.getString("COMMAND").split(";( )?"));
}
if (section.contains("ENCHANTMENT")) {
trmenu.set("Buttons." + symbol + ".display.shiny", true);
}
}
});
trmenu.set("Shape", fixShape(shape));
file.renameTo(new File(file.getParent(), file.getName().replace(".yml", "") + ".CONVERTED.TRMENU"));
trmenu.save(new File(TrMenu.getPlugin().getDataFolder(), "menus/" + file.getName().replace(".yml", "") + "-fromcc.yml"));
return count + 1;
} catch (Throwable e) {
e.printStackTrace();
}
return count;
}
public SecuredFile() {
SimpleReflection.setFieldValue(MemorySection.class, this, "map", new ConcurrentHashMap<>(map), true);
}
public static Particle deserialize(Map<String, Object> map) {
return new Particle(Particles.fromName((String) map.get("particleEffect")), ParticleShape.valueOf(((String) map.get("particleShape")).toUpperCase()), new OrdinaryColor(Color.deserialize(((MemorySection) map.get("particleColor")).getValues(false))));
}
private static boolean isNotInnerNode(String key, FileConfiguration configuration) {
return !(configuration.get(key) instanceof MemorySection);
}