Search in sources :

Example 1 with YamlConfiguration

use of net.aufdemrand.denizencore.utilities.YamlConfiguration in project Denizen-For-Bukkit by DenizenScript.

the class YamlCommand method execute.

@Override
public void execute(final ScriptEntry scriptEntry) throws CommandExecutionException {
    Element filename = scriptEntry.getElement("filename");
    Element key = scriptEntry.getElement("key");
    dObject value = scriptEntry.getdObject("value");
    Element split = scriptEntry.getElement("split");
    YAML_Action yaml_action = (YAML_Action) scriptEntry.getObject("yaml_action");
    Element actionElement = scriptEntry.getElement("action");
    Element idElement = scriptEntry.getElement("id");
    Element fixFormatting = scriptEntry.getElement("fix_formatting");
    YamlConfiguration yamlConfiguration;
    dB.report(scriptEntry, getName(), idElement.debug() + actionElement.debug() + (filename != null ? filename.debug() : "") + (yaml_action != null ? aH.debugObj("yaml_action", yaml_action.name()) : "") + (key != null ? key.debug() : "") + (value != null ? value.debug() : "") + (split != null ? split.debug() : "") + fixFormatting.debug());
    // Do action
    Action action = Action.valueOf(actionElement.asString().toUpperCase());
    String id = idElement.asString().toUpperCase();
    switch(action) {
        case LOAD:
            File file = new File(DenizenAPI.getCurrentInstance().getDataFolder(), filename.asString());
            if (!file.exists()) {
                dB.echoError("File cannot be found!");
                return;
            }
            try {
                FileInputStream fis = new FileInputStream(file);
                String str = ScriptHelper.convertStreamToString(fis);
                if (fixFormatting.asBoolean()) {
                    str = ScriptHelper.ClearComments("", str, false);
                }
                yamlConfiguration = YamlConfiguration.load(str);
                fis.close();
            } catch (Exception e) {
                dB.echoError(e);
                return;
            }
            if (yamls.containsKey(id)) {
                yamls.remove(id);
            }
            if (yamlConfiguration != null) {
                yamls.put(id, yamlConfiguration);
            }
            break;
        case UNLOAD:
            if (yamls.containsKey(id)) {
                yamls.remove(id);
            } else {
                dB.echoError("Unknown YAML ID '" + id + "'");
            }
            break;
        case SAVE:
            if (yamls.containsKey(id)) {
                try {
                    if (!Settings.allowStrangeYAMLSaves()) {
                        File fileObj = new File(DenizenAPI.getCurrentInstance().getDataFolder().getAbsolutePath() + "/" + filename.asString());
                        String directory = URLDecoder.decode(System.getProperty("user.dir"));
                        if (!fileObj.getCanonicalPath().startsWith(directory)) {
                            dB.echoError("Outside-the-main-folder YAML saves disabled by administrator.");
                            return;
                        }
                    }
                    File fileObj = new File(DenizenAPI.getCurrentInstance().getDataFolder().getAbsolutePath() + "/" + filename.asString());
                    fileObj.getParentFile().mkdirs();
                    if (!Utilities.isSafeFile(fileObj)) {
                        dB.echoError(scriptEntry.getResidingQueue(), "Cannot edit that file!");
                        return;
                    }
                    FileWriter fw = new FileWriter(fileObj.getAbsoluteFile());
                    BufferedWriter writer = new BufferedWriter(fw);
                    writer.write(yamls.get(id).saveToString());
                    writer.close();
                    fw.close();
                } catch (IOException e) {
                    dB.echoError(e);
                }
            } else {
                dB.echoError("Unknown YAML ID '" + id + "'");
            }
            break;
        case WRITE:
            if (yamls.containsKey(id)) {
                if (value instanceof Element) {
                    yamls.get(id).set(key.asString(), ((Element) value).asString());
                } else if (split != null && split.asBoolean()) {
                    yamls.get(id).set(key.asString(), value);
                } else {
                    yamls.get(id).set(key.asString(), value.identify());
                }
            } else {
                dB.echoError("Unknown YAML ID '" + id + "'");
            }
            break;
        case SET:
            if (yamls.containsKey(id)) {
                if (yaml_action == null || key == null || value == null) {
                    dB.echoError("Must specify a YAML action and value!");
                    return;
                }
                YamlConfiguration yaml = yamls.get(id);
                int index = -1;
                if (key.asString().contains("[")) {
                    try {
                        if (dB.verbose) {
                            dB.echoDebug(scriptEntry, "Try index: " + key.asString().split("\\[")[1].replace("]", ""));
                        }
                        index = Integer.valueOf(key.asString().split("\\[")[1].replace("]", "")) - 1;
                    } catch (Exception e) {
                        if (dB.verbose) {
                            dB.echoError(scriptEntry.getResidingQueue(), e);
                        }
                        index = -1;
                    }
                    key = Element.valueOf(key.asString().split("\\[")[0]);
                }
                String keyStr = key.asString();
                String valueStr = value.identify();
                switch(yaml_action) {
                    case INCREASE:
                        Set(yaml, index, keyStr, String.valueOf(aH.getFloatFrom(Get(yaml, index, keyStr, "0")) + aH.getFloatFrom(valueStr)));
                        break;
                    case DECREASE:
                        Set(yaml, index, keyStr, String.valueOf(aH.getFloatFrom(Get(yaml, index, keyStr, "0")) - aH.getFloatFrom(valueStr)));
                        break;
                    case MULTIPLY:
                        Set(yaml, index, keyStr, String.valueOf(aH.getFloatFrom(Get(yaml, index, keyStr, "1")) * aH.getFloatFrom(valueStr)));
                        break;
                    case DIVIDE:
                        Set(yaml, index, keyStr, String.valueOf(aH.getFloatFrom(Get(yaml, index, keyStr, "1")) / aH.getFloatFrom(valueStr)));
                        break;
                    case DELETE:
                        yaml.set(keyStr, null);
                        break;
                    case SET_VALUE:
                        Set(yaml, index, keyStr, valueStr);
                        break;
                    case INSERT:
                        {
                            List<String> list = yaml.getStringList(keyStr);
                            if (list == null) {
                                list = new ArrayList<String>();
                            }
                            list.add(valueStr);
                            yaml.set(keyStr, list);
                            break;
                        }
                    case REMOVE:
                        {
                            List<String> list = yaml.getStringList(keyStr);
                            if (list == null) {
                                if (dB.verbose) {
                                    dB.echoDebug(scriptEntry, "List null!");
                                }
                                break;
                            }
                            if (index > -1 && index < list.size()) {
                                if (dB.verbose) {
                                    dB.echoDebug(scriptEntry, "Remove ind: " + index);
                                }
                                list.remove(index);
                                yaml.set(keyStr, list);
                            } else {
                                if (dB.verbose) {
                                    dB.echoDebug(scriptEntry, "Remvoe value: " + valueStr);
                                }
                                for (int i = 0; i < list.size(); i++) {
                                    if (list.get(i).equalsIgnoreCase(valueStr)) {
                                        list.remove(i);
                                        break;
                                    }
                                }
                                yaml.set(keyStr, list);
                                break;
                            }
                            break;
                        }
                    case SPLIT:
                        {
                            List<String> list = yaml.getStringList(keyStr);
                            if (list == null) {
                                list = new ArrayList<String>();
                            }
                            list.addAll(dList.valueOf(valueStr));
                            yaml.set(keyStr, list);
                            break;
                        }
                }
            } else {
                dB.echoError("Unknown YAML ID '" + id + "'");
            }
            break;
        case CREATE:
            if (yamls.containsKey(id)) {
                yamls.remove(id);
            }
            yamlConfiguration = new YamlConfiguration();
            yamls.put(id.toUpperCase(), yamlConfiguration);
            break;
    }
}
Also used : Element(net.aufdemrand.denizencore.objects.Element) YamlConfiguration(net.aufdemrand.denizencore.utilities.YamlConfiguration) InvalidArgumentsException(net.aufdemrand.denizencore.exceptions.InvalidArgumentsException) CommandExecutionException(net.aufdemrand.denizencore.exceptions.CommandExecutionException) net.aufdemrand.denizencore.objects.dObject(net.aufdemrand.denizencore.objects.dObject) net.aufdemrand.denizencore.objects.dList(net.aufdemrand.denizencore.objects.dList)

Example 2 with YamlConfiguration

use of net.aufdemrand.denizencore.utilities.YamlConfiguration in project Denizen-For-Bukkit by DenizenScript.

the class InventoryScriptContainer method getInventoryFrom.

public dInventory getInventoryFrom(dPlayer player, dNPC npc) {
    // TODO: Clean all this code!
    dInventory inventory = null;
    BukkitTagContext context = new BukkitTagContext(player, npc, false, null, shouldDebug(), new dScript(this));
    try {
        if (contains("INVENTORY")) {
            if (InventoryType.valueOf(getString("INVENTORY").toUpperCase()) != null) {
                inventory = new dInventory(InventoryType.valueOf(getString("INVENTORY").toUpperCase()));
                if (contains("TITLE")) {
                    inventory.setTitle(TagManager.tag(getString("TITLE"), context));
                }
                inventory.setIdentifiers("script", getName());
            } else {
                dB.echoError("Invalid inventory type specified. Assuming \"CHEST\"");
            }
        }
        int size = 0;
        if (contains("SIZE")) {
            if (inventory != null && !getInventoryType().name().equalsIgnoreCase("CHEST")) {
                dB.echoError("You can only set the size of chest inventories!");
            } else {
                size = aH.getIntegerFrom(TagManager.tag(getString("SIZE"), context));
                if (size == 0) {
                    dB.echoError("Inventory size can't be 0. Assuming default of inventory type...");
                }
                if (size % 9 != 0) {
                    size = (int) Math.ceil(size / 9) * 9;
                    dB.echoError("Inventory size must be a multiple of 9! Rounding up to " + size + "...");
                }
                if (size < 0) {
                    size = size * -1;
                    dB.echoError("Inventory size must be a positive number! Inverting to " + size + "...");
                }
                inventory = new dInventory(size, contains("TITLE") ? TagManager.tag(getString("TITLE"), context) : "Chest");
                inventory.setIdentifiers("script", getName());
            }
        }
        if (size == 0) {
            size = getInventoryType().getDefaultSize();
        }
        boolean[] filledSlots = new boolean[size];
        if (contains("SLOTS")) {
            ItemStack[] finalItems = new ItemStack[size];
            int itemsAdded = 0;
            for (String items : getStringList("SLOTS")) {
                items = TagManager.tag(items, context).trim();
                if (items.isEmpty()) {
                    continue;
                }
                if (!items.startsWith("[") || !items.endsWith("]")) {
                    dB.echoError("Inventory script \"" + getName() + "\" has an invalid slots line: [" + items + "]... Ignoring it");
                    continue;
                }
                String[] itemsInLine = items.substring(1, items.length() - 1).split("\\[?\\]?\\s+\\[", -1);
                for (String item : itemsInLine) {
                    if (contains("DEFINITIONS." + item)) {
                        dItem def = dItem.valueOf(TagManager.tag(getString("DEFINITIONS." + item), context), player, npc);
                        if (def == null) {
                            dB.echoError("Invalid definition '" + item + "' in inventory script '" + getName() + "'" + "... Ignoring it and assuming \"AIR\"");
                            finalItems[itemsAdded] = new ItemStack(Material.AIR);
                        } else {
                            finalItems[itemsAdded] = def.getItemStack();
                        }
                    } else if (dItem.matches(item)) {
                        finalItems[itemsAdded] = dItem.valueOf(item, player, npc).getItemStack();
                    } else {
                        finalItems[itemsAdded] = new ItemStack(Material.AIR);
                        if (!item.isEmpty()) {
                            dB.echoError("Inventory script \"" + getName() + "\" has an invalid slot item: [" + item + "]... Ignoring it and assuming \"AIR\"");
                        }
                    }
                    filledSlots[itemsAdded] = !item.isEmpty();
                    itemsAdded++;
                }
            }
            if (inventory == null) {
                size = finalItems.length % 9 == 0 ? finalItems.length : Math.round(finalItems.length / 9) * 9;
                inventory = new dInventory(size == 0 ? 9 : size, contains("TITLE") ? TagManager.tag(getString("TITLE"), context) : "Chest");
            }
            inventory.setContents(finalItems);
        }
        if (contains("PROCEDURAL ITEMS")) {
            // TODO: Document this feature!
            if (inventory == null) {
                size = InventoryType.CHEST.getDefaultSize();
                inventory = new dInventory(size, contains("TITLE") ? TagManager.tag(getString("TITLE"), context) : "Chest");
            }
            List<ScriptEntry> entries = getEntries(new BukkitScriptEntryData(player, npc), "PROCEDURAL ITEMS");
            if (!entries.isEmpty()) {
                long id = DetermineCommand.getNewId();
                ScriptBuilder.addObjectToEntries(entries, "ReqId", id);
                InstantQueue queue = InstantQueue.getQueue(ScriptQueue.getNextId("INV_SCRIPT_ITEM_PROC"));
                queue.addEntries(entries);
                queue.setReqId(id);
                if (contains("DEFINITIONS")) {
                    YamlConfiguration section = getConfigurationSection("DEFINITIONS");
                    for (StringHolder string : section.getKeys(false)) {
                        String definition = string.str;
                        queue.addDefinition(definition, section.getString(definition));
                    }
                }
                queue.start();
                if (DetermineCommand.hasOutcome(id)) {
                    dList list = dList.valueOf(DetermineCommand.getOutcome(id).get(0));
                    if (list != null) {
                        int x = 0;
                        for (dItem item : list.filter(dItem.class)) {
                            while (x < filledSlots.length && filledSlots[x]) {
                                x++;
                            }
                            if (x >= filledSlots.length || filledSlots[x]) {
                                break;
                            }
                            inventory.setSlots(x, item.getItemStack());
                            filledSlots[x] = true;
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        dB.echoError("Woah! An exception has been called with this inventory script!");
        dB.echoError(e);
        inventory = null;
    }
    if (inventory != null) {
        InventoryScriptHelper.tempInventoryScripts.put(inventory.getInventory(), getName());
    }
    return inventory;
}
Also used : net.aufdemrand.denizencore.objects.dList(net.aufdemrand.denizencore.objects.dList) net.aufdemrand.denizen.objects.dInventory(net.aufdemrand.denizen.objects.dInventory) ScriptEntry(net.aufdemrand.denizencore.scripts.ScriptEntry) YamlConfiguration(net.aufdemrand.denizencore.utilities.YamlConfiguration) net.aufdemrand.denizen.objects.dItem(net.aufdemrand.denizen.objects.dItem) StringHolder(net.aufdemrand.denizencore.utilities.text.StringHolder) BukkitTagContext(net.aufdemrand.denizen.tags.BukkitTagContext) BukkitScriptEntryData(net.aufdemrand.denizen.BukkitScriptEntryData) net.aufdemrand.denizencore.objects.dScript(net.aufdemrand.denizencore.objects.dScript) InstantQueue(net.aufdemrand.denizencore.scripts.queues.core.InstantQueue) ItemStack(org.bukkit.inventory.ItemStack)

Example 3 with YamlConfiguration

use of net.aufdemrand.denizencore.utilities.YamlConfiguration in project Denizen-For-Bukkit by DenizenScript.

the class MapScriptContainer method applyTo.

public void applyTo(MapView mapView) {
    DenizenMapRenderer renderer = new DenizenMapRenderer(mapView.getRenderers(), aH.getBooleanFrom(getString("AUTO UPDATE", "true")));
    boolean debug = true;
    if (contains("DEBUG")) {
        debug = aH.getBooleanFrom(getString("DEBUG"));
    }
    if (contains("OBJECTS")) {
        YamlConfiguration objectsSection = getConfigurationSection("OBJECTS");
        List<StringHolder> objectKeys1 = new ArrayList<StringHolder>(objectsSection.getKeys(false));
        List<String> objectKeys = new ArrayList<String>(objectKeys1.size());
        for (StringHolder sh : objectKeys1) {
            objectKeys.add(sh.str);
        }
        Collections.sort(objectKeys, new NaturalOrderComparator());
        for (String objectKey : objectKeys) {
            YamlConfiguration objectSection = objectsSection.getConfigurationSection(objectKey);
            if (!objectSection.contains("TYPE")) {
                dB.echoError("Map script '" + getName() + "' has an object without a specified type!");
                return;
            }
            String type = objectSection.getString("TYPE").toUpperCase();
            String x = objectSection.getString("X", "0");
            String y = objectSection.getString("Y", "0");
            String visible = objectSection.getString("VISIBLE", "true");
            if (type.equals("IMAGE")) {
                if (!objectSection.contains("IMAGE")) {
                    dB.echoError("Map script '" + getName() + "'s image '" + objectKey + "' has no specified image location!");
                    return;
                }
                String image = objectSection.getString("IMAGE");
                int width = aH.getIntegerFrom(objectSection.getString("WIDTH", "0"));
                int height = aH.getIntegerFrom(objectSection.getString("HEIGHT", "0"));
                if (CoreUtilities.toLowerCase(image).endsWith(".gif")) {
                    renderer.addObject(new MapAnimatedImage(x, y, visible, debug, image, width, height));
                } else {
                    renderer.addObject(new MapImage(x, y, visible, debug, image, width, height));
                }
            } else if (type.equals("TEXT")) {
                if (!objectSection.contains("TEXT")) {
                    dB.echoError("Map script '" + getName() + "'s text object '" + objectKey + "' has no specified text!");
                    return;
                }
                String text = objectSection.getString("TEXT");
                renderer.addObject(new MapText(x, y, visible, debug, text));
            } else if (type.equals("CURSOR")) {
                if (!objectSection.contains("CURSOR")) {
                    dB.echoError("Map script '" + getName() + "'s cursor '" + objectKey + "' has no specified cursor type!");
                    return;
                }
                String cursor = objectSection.getString("CURSOR");
                if (cursor == null) {
                    dB.echoError("Map script '" + getName() + "'s cursor '" + objectKey + "' is missing a cursor type!");
                    return;
                }
                renderer.addObject(new MapCursor(x, y, visible, debug, objectSection.getString("DIRECTION", "0"), cursor));
            } else if (type.equals("DOT")) {
                renderer.addObject(new MapDot(x, y, visible, debug, objectSection.getString("RADIUS", "1"), objectSection.getString("COLOR", "black")));
            }
        }
    }
    DenizenMapManager.setMap(mapView, renderer);
}
Also used : ArrayList(java.util.ArrayList) YamlConfiguration(net.aufdemrand.denizencore.utilities.YamlConfiguration) NaturalOrderComparator(net.aufdemrand.denizencore.utilities.NaturalOrderComparator) StringHolder(net.aufdemrand.denizencore.utilities.text.StringHolder)

Example 4 with YamlConfiguration

use of net.aufdemrand.denizencore.utilities.YamlConfiguration in project Denizen-For-Bukkit by DenizenScript.

the class YamlCommand method yaml.

@TagManager.TagEvents
public void yaml(ReplaceableTagEvent event) {
    if (!event.matches("yaml")) {
        return;
    }
    Attribute attribute = event.getAttributes();
    // -->
    if (attribute.getAttribute(2).equalsIgnoreCase("list")) {
        dList list = new dList();
        list.addAll(yamls.keySet());
        event.setReplaced(list.getAttribute(attribute.fulfill(2)));
        return;
    }
    // YAML tag requires name context and type context.
    if ((!event.hasNameContext() || !(event.hasTypeContext() || attribute.getAttribute(2).equalsIgnoreCase("to_json"))) && !attribute.hasAlternative()) {
        dB.echoError("YAML tag '" + event.raw_tag + "' is missing required context. Tag replacement aborted.");
        return;
    }
    // Set id (name context) and path (type context)
    String id = event.getNameContext().toUpperCase();
    String path = event.getTypeContext();
    // Check if there is a yaml file loaded with the specified id
    if (!yamls.containsKey(id)) {
        if (!attribute.hasAlternative()) {
            dB.echoError("YAML tag '" + event.raw_tag + "' has specified an invalid ID, or the specified id has already" + " been closed. Tag replacement aborted. ID given: '" + id + "'.");
        }
        return;
    }
    // Catch up with what has already been processed.
    attribute.fulfill(1);
    // -->
    if (attribute.startsWith("contains")) {
        event.setReplaced(new Element(getYaml(id).contains(path)).getAttribute(attribute.fulfill(1)));
        return;
    }
    // -->
    if (attribute.startsWith("is_list")) {
        event.setReplaced(new Element(getYaml(id).isList(path)).getAttribute(attribute.fulfill(1)));
        return;
    }
    // -->
    if (attribute.startsWith("read")) {
        attribute.fulfill(1);
        if (getYaml(id).isList(path)) {
            List<String> value = getYaml(id).getStringList(path);
            if (value == null) {
                // If value is null, the key at the specified path didn't exist.
                return;
            } else {
                event.setReplaced(new dList(value).getAttribute(attribute));
                return;
            }
        } else {
            String value = getYaml(id).getString(path);
            if (value == null) {
                // If value is null, the key at the specified path didn't exist.
                return;
            } else {
                event.setReplaced(new Element(value).getAttribute(attribute));
                return;
            }
        }
    }
    // -->
    if (attribute.startsWith("list_deep_keys")) {
        Set<StringHolder> keys;
        if (path != null && path.length() > 0) {
            YamlConfiguration section = getYaml(id).getConfigurationSection(path);
            if (section == null) {
                return;
            }
            keys = section.getKeys(true);
        } else {
            keys = getYaml(id).getKeys(true);
        }
        if (keys == null) {
            return;
        } else {
            event.setReplaced(new dList(keys).getAttribute(attribute.fulfill(1)));
            return;
        }
    }
    // -->
    if (attribute.startsWith("list_keys")) {
        Set<StringHolder> keys;
        if (path != null && path.length() > 0) {
            YamlConfiguration section = getYaml(id).getConfigurationSection(path);
            if (section == null) {
                return;
            }
            keys = section.getKeys(false);
        } else {
            keys = getYaml(id).getKeys(false);
        }
        if (keys == null) {
            return;
        } else {
            event.setReplaced(new dList(keys).getAttribute(attribute.fulfill(1)));
            return;
        }
    }
    // -->
    if (attribute.startsWith("to_json")) {
        JSONObject jsobj = new JSONObject(getYaml(id).getMap());
        event.setReplaced(new Element(jsobj.toString()).getAttribute(attribute.fulfill(1)));
        return;
    }
}
Also used : StringHolder(net.aufdemrand.denizencore.utilities.text.StringHolder) JSONObject(org.json.JSONObject) Attribute(net.aufdemrand.denizencore.tags.Attribute) net.aufdemrand.denizencore.objects.dList(net.aufdemrand.denizencore.objects.dList) Element(net.aufdemrand.denizencore.objects.Element) YamlConfiguration(net.aufdemrand.denizencore.utilities.YamlConfiguration)

Aggregations

YamlConfiguration (net.aufdemrand.denizencore.utilities.YamlConfiguration)4 net.aufdemrand.denizencore.objects.dList (net.aufdemrand.denizencore.objects.dList)3 StringHolder (net.aufdemrand.denizencore.utilities.text.StringHolder)3 Element (net.aufdemrand.denizencore.objects.Element)2 ArrayList (java.util.ArrayList)1 BukkitScriptEntryData (net.aufdemrand.denizen.BukkitScriptEntryData)1 net.aufdemrand.denizen.objects.dInventory (net.aufdemrand.denizen.objects.dInventory)1 net.aufdemrand.denizen.objects.dItem (net.aufdemrand.denizen.objects.dItem)1 BukkitTagContext (net.aufdemrand.denizen.tags.BukkitTagContext)1 CommandExecutionException (net.aufdemrand.denizencore.exceptions.CommandExecutionException)1 InvalidArgumentsException (net.aufdemrand.denizencore.exceptions.InvalidArgumentsException)1 net.aufdemrand.denizencore.objects.dObject (net.aufdemrand.denizencore.objects.dObject)1 net.aufdemrand.denizencore.objects.dScript (net.aufdemrand.denizencore.objects.dScript)1 ScriptEntry (net.aufdemrand.denizencore.scripts.ScriptEntry)1 InstantQueue (net.aufdemrand.denizencore.scripts.queues.core.InstantQueue)1 Attribute (net.aufdemrand.denizencore.tags.Attribute)1 NaturalOrderComparator (net.aufdemrand.denizencore.utilities.NaturalOrderComparator)1 ItemStack (org.bukkit.inventory.ItemStack)1 JSONObject (org.json.JSONObject)1